3 import java_cup.runtime.ComplexSymbolFactory;
4 import java_cup.runtime.ScannerBuffer;
6 import java.util.Arrays;
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Iterator;
13 import java.util.List;
17 import iotpolicy.parser.Lexer;
18 import iotpolicy.parser.Parser;
19 import iotpolicy.tree.ParseNode;
20 import iotpolicy.tree.ParseNodeVector;
21 import iotpolicy.tree.ParseTreeHandler;
22 import iotpolicy.tree.Declaration;
23 import iotpolicy.tree.DeclarationHandler;
24 import iotpolicy.tree.CapabilityDecl;
25 import iotpolicy.tree.InterfaceDecl;
26 import iotpolicy.tree.RequiresDecl;
27 import iotpolicy.tree.EnumDecl;
28 import iotpolicy.tree.StructDecl;
30 import iotrmi.Java.IoTRMITypes;
33 /** Class IoTCompiler is the main interface/stub compiler for
34 * files generation. This class calls helper classes
35 * such as Parser, Lexer, InterfaceDecl, CapabilityDecl,
36 * RequiresDecl, ParseTreeHandler, etc.
38 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
42 public class IoTCompiler {
47 // Maps multiple interfaces to multiple objects of ParseTreeHandler
48 private Map<String,ParseTreeHandler> mapIntfacePTH;
49 private Map<String,DeclarationHandler> mapIntDeclHand;
50 private Map<String,Map<String,Set<String>>> mapInt2NewInts;
51 // Data structure to store our types (primitives and non-primitives) for compilation
52 private Map<String,String> mapPrimitives;
53 private Map<String,String> mapNonPrimitivesJava;
54 private Map<String,String> mapNonPrimitivesCplus;
55 // Other data structures
56 private Map<String,Integer> mapIntfaceObjId; // Maps interface name to object Id
57 private Map<String,Integer> mapNewIntfaceObjId; // Maps new interface name to its object Id (keep track of stubs)
58 private PrintWriter pw;
60 private String subdir;
66 private final static String OUTPUT_DIRECTORY = "output_files";
68 private enum ParamCategory {
70 PRIMITIVES, // All the primitive types, e.g. byte, short, int, long, etc.
71 NONPRIMITIVES, // Non-primitive types, e.g. Set, Map, List, etc.
73 STRUCT, // Struct type
74 USERDEFINED // Assumed as driver classes
81 public IoTCompiler() {
83 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
84 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
85 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
86 mapIntfaceObjId = new HashMap<String,Integer>();
87 mapNewIntfaceObjId = new HashMap<String,Integer>();
88 mapPrimitives = new HashMap<String,String>();
89 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
90 mapNonPrimitivesJava = new HashMap<String,String>();
91 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
92 mapNonPrimitivesCplus = new HashMap<String,String>();
93 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
95 dir = OUTPUT_DIRECTORY;
101 * setDataStructures() sets parse tree and other data structures based on policy files.
103 * It also generates parse tree (ParseTreeHandler) and
104 * copies useful information from parse tree into
105 * InterfaceDecl, CapabilityDecl, and RequiresDecl
107 * Additionally, the data structure handles are
108 * returned from tree-parsing for further process.
110 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
112 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
113 DeclarationHandler decHandler = new DeclarationHandler();
114 // Process ParseNode and generate Declaration objects
116 ptHandler.processInterfaceDecl();
117 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
118 decHandler.addInterfaceDecl(origInt, intDecl);
120 ptHandler.processCapabilityDecl();
121 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
122 decHandler.addCapabilityDecl(origInt, capDecl);
124 ptHandler.processRequiresDecl();
125 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
126 decHandler.addRequiresDecl(origInt, reqDecl);
128 ptHandler.processEnumDecl();
129 EnumDecl enumDecl = ptHandler.getEnumDecl();
130 decHandler.addEnumDecl(origInt, enumDecl);
132 ptHandler.processStructDecl();
133 StructDecl structDecl = ptHandler.getStructDecl();
134 decHandler.addStructDecl(origInt, structDecl);
136 mapIntfacePTH.put(origInt, ptHandler);
137 mapIntDeclHand.put(origInt, decHandler);
138 // Set object Id counter to 0 for each interface
139 mapIntfaceObjId.put(origInt, new Integer(0));
144 * getMethodsForIntface() reads for methods in the data structure
146 * It is going to give list of methods for a certain interface
147 * based on the declaration of capabilities.
149 public void getMethodsForIntface(String origInt) {
151 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
152 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
153 // Get set of new interfaces, e.g. CameraWithCaptureAndData
154 // Generate this new interface with all the methods it needs
155 // from different capabilities it declares
156 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
157 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
158 Set<String> setIntfaces = reqDecl.getInterfaces();
159 for (String strInt : setIntfaces) {
161 // Initialize a set of methods
162 Set<String> setMethods = new HashSet<String>();
163 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
164 List<String> listCapab = reqDecl.getCapabList(strInt);
165 for (String strCap : listCapab) {
167 // Get list of methods for each capability
168 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
169 List<String> listCapabMeth = capDecl.getMethods(strCap);
170 for (String strMeth : listCapabMeth) {
172 // Add methods into setMethods
173 // This is to also handle redundancies (say two capabilities
174 // share the same methods)
175 setMethods.add(strMeth);
178 // Add interface and methods information into map
179 mapNewIntMethods.put(strInt, setMethods);
181 // Map the map of interface-methods to the original interface
182 mapInt2NewInts.put(origInt, mapNewIntMethods);
187 * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
189 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
191 for (String method : methods) {
193 List<String> methParams = intDecl.getMethodParams(method);
194 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
195 print("public " + intDecl.getMethodType(method) + " " +
196 intDecl.getMethodId(method) + "(");
197 for (int i = 0; i < methParams.size(); i++) {
198 // Check for params with driver class types and exchange it
199 // with its remote interface
200 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
201 print(paramType + " " + methParams.get(i));
202 // Check if this is the last element (don't print a comma)
203 if (i != methParams.size() - 1) {
213 * HELPER: writeMethodJavaInterface() writes the method of the interface
215 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
217 for (String method : methods) {
219 List<String> methParams = intDecl.getMethodParams(method);
220 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
221 print("public " + intDecl.getMethodType(method) + " " +
222 intDecl.getMethodId(method) + "(");
223 for (int i = 0; i < methParams.size(); i++) {
224 // Check for params with driver class types and exchange it
225 // with its remote interface
226 String paramType = methPrmTypes.get(i);
227 print(paramType + " " + methParams.get(i));
228 // Check if this is the last element (don't print a comma)
229 if (i != methParams.size() - 1) {
239 * HELPER: generateEnumJava() writes the enumeration declaration
241 private void generateEnumJava() throws IOException {
243 // Create a new directory
244 createDirectory(dir);
245 for (String intface : mapIntfacePTH.keySet()) {
246 // Get the right EnumDecl
247 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
248 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
249 Set<String> enumTypes = enumDecl.getEnumDeclarations();
250 // Iterate over enum declarations
251 for (String enType : enumTypes) {
252 // Open a new file to write into
253 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
254 pw = new PrintWriter(new BufferedWriter(fw));
255 println("public enum " + enType + " {");
256 List<String> enumMembers = enumDecl.getMembers(enType);
257 for (int i = 0; i < enumMembers.size(); i++) {
259 String member = enumMembers.get(i);
261 // Check if this is the last element (don't print a comma)
262 if (i != enumMembers.size() - 1)
269 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
276 * HELPER: generateStructJava() writes the struct declaration
278 private void generateStructJava() throws IOException {
280 // Create a new directory
281 createDirectory(dir);
282 for (String intface : mapIntfacePTH.keySet()) {
283 // Get the right StructDecl
284 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
285 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
286 List<String> structTypes = structDecl.getStructTypes();
287 // Iterate over enum declarations
288 for (String stType : structTypes) {
289 // Open a new file to write into
290 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
291 pw = new PrintWriter(new BufferedWriter(fw));
292 println("public class " + stType + " {");
293 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
294 List<String> structMembers = structDecl.getMembers(stType);
295 for (int i = 0; i < structMembers.size(); i++) {
297 String memberType = structMemberTypes.get(i);
298 String member = structMembers.get(i);
299 println("public static " + memberType + " " + member + ";");
303 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
310 * generateJavaLocalInterface() writes the local interface and provides type-checking.
312 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
313 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
314 * The local interface has to be the input parameter for the stub and the stub
315 * interface has to be the input parameter for the local class.
317 public void generateJavaLocalInterfaces() throws IOException {
319 // Create a new directory
320 createDirectory(dir);
321 for (String intface : mapIntfacePTH.keySet()) {
322 // Open a new file to write into
323 FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
324 pw = new PrintWriter(new BufferedWriter(fw));
325 // Pass in set of methods and get import classes
326 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
327 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
328 List<String> methods = intDecl.getMethods();
329 Set<String> importClasses = getImportClasses(methods, intDecl);
330 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
331 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
332 printImportStatements(allImportClasses);
333 // Write interface header
335 println("public interface " + intface + " {");
337 writeMethodJavaLocalInterface(methods, intDecl);
340 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
346 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
348 public void generateJavaInterfaces() throws IOException {
350 // Create a new directory
351 String path = createDirectories(dir, subdir);
352 for (String intface : mapIntfacePTH.keySet()) {
354 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
355 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
357 // Open a new file to write into
358 String newIntface = intMeth.getKey();
359 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
360 pw = new PrintWriter(new BufferedWriter(fw));
361 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
362 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
363 // Pass in set of methods and get import classes
364 List<String> methods = intDecl.getMethods();
365 Set<String> importClasses = getImportClasses(methods, intDecl);
366 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
367 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
368 printImportStatements(allImportClasses);
369 // Write interface header
371 println("public interface " + newIntface + " {\n");
373 writeMethodJavaInterface(methods, intDecl);
376 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
383 * HELPER: writePropertiesJavaPermission() writes the permission in properties
385 private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
387 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
388 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
389 String newIntface = intMeth.getKey();
390 int newObjectId = getNewIntfaceObjectId(newIntface);
391 println("private final static int object" + newObjectId + "Id = " +
392 newObjectId + ";\t//" + newIntface);
393 Set<String> methodIds = intMeth.getValue();
394 print("private static Integer[] object" + newObjectId + "Permission = { ");
396 for (String methodId : methodIds) {
397 int methodNumId = intDecl.getMethodNumId(methodId);
398 print(Integer.toString(methodNumId));
399 // Check if this is the last element (don't print a comma)
400 if (i != methodIds.size() - 1) {
406 println("private static List<Integer> set" + newObjectId + "Allowed;");
412 * HELPER: writePropertiesJavaStub() writes the properties of the stub class
414 private void writePropertiesJavaStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
416 println("private IoTRMICall rmiCall;");
417 println("private String address;");
418 println("private int[] ports;\n");
420 Integer objId = mapIntfaceObjId.get(intface);
421 println("private final static int objectId = " + objId + ";");
422 mapNewIntfaceObjId.put(newIntface, objId);
423 mapIntfaceObjId.put(intface, objId++);
425 // We assume that each class only has one callback interface for now
426 Iterator it = callbackClasses.iterator();
427 String callbackType = (String) it.next();
428 println("// Callback properties");
429 println("private IoTRMIObject rmiObj;");
430 println("List<" + callbackType + "> listCallbackObj;");
431 println("private static int objIdCnt = 0;");
432 // Generate permission stuff for callback stubs
433 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
434 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
435 writePropertiesJavaPermission(callbackType, intDecl);
442 * HELPER: writeConstructorJavaPermission() writes the permission in constructor
444 private void writeConstructorJavaPermission(String intface) {
446 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
447 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
448 String newIntface = intMeth.getKey();
449 int newObjectId = getNewIntfaceObjectId(newIntface);
450 println("set" + newObjectId + "Allowed = new ArrayList<Integer>(Arrays.asList(object" + newObjectId +"Permission));");
456 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
458 private void writeConstructorJavaStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
460 println("public " + newStubClass + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
461 println("address = _address;");
462 println("ports = _ports;");
463 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
465 Iterator it = callbackClasses.iterator();
466 String callbackType = (String) it.next();
467 writeConstructorJavaPermission(intface);
468 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
469 println("___initCallBack();");
476 * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
478 private void writeJavaMethodCallbackPermission(String intface) {
480 println("int methodId = IoTRMIObject.getMethodId(method);");
481 // Get all the different stubs
482 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
483 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
484 String newIntface = intMeth.getKey();
485 int newObjectId = getNewIntfaceObjectId(newIntface);
486 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
487 println("throw new Error(\"Callback object for " + intface + " is not allowed to access method: \" + methodId);");
494 * HELPER: writeJavaInitCallbackPermission() writes the permission for callback
496 private void writeJavaInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
499 String method = "___initCallBack()";
500 int methodNumId = intDecl.getHelperMethodNumId(method);
501 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
502 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
503 String newIntface = intMeth.getKey();
504 int newObjectId = getNewIntfaceObjectId(newIntface);
505 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
512 * HELPER: writeInitCallbackJavaStub() writes callback initialization in stub
514 private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
516 println("public void ___initCallBack() {");
517 // Generate main thread for callbacks
518 println("Thread thread = new Thread() {");
519 println("public void run() {");
521 println("rmiObj = new IoTRMIObject(ports[0]);");
522 println("while (true) {");
523 println("byte[] method = rmiObj.getMethodBytes();");
524 writeJavaMethodCallbackPermission(intface);
525 println("int objId = IoTRMIObject.getObjectId(method);");
526 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
527 println("if (skel != null) {");
528 println("skel.invokeMethod(rmiObj);");
531 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
535 println(" catch (Exception ex) {");
536 println("ex.printStackTrace();");
537 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
541 println("thread.start();\n");
542 // Generate info sending part
543 String method = "___initCallBack()";
544 int methodNumId = intDecl.getHelperMethodNumId(method);
545 println("int methodId = " + methodNumId + ";");
546 println("Class<?> retType = void.class;");
547 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
548 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
549 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
555 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
557 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
559 // Iterate and find enum declarations
560 for (int i = 0; i < methParams.size(); i++) {
561 String paramType = methPrmTypes.get(i);
562 String param = methParams.get(i);
563 String simpleType = getGenericType(paramType);
564 if (isEnumClass(simpleType)) {
565 // Check if this is enum type
566 if (isArray(param)) { // An array
567 println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
568 println("int paramEnum" + i + "[] = new int[len" + i + "];");
569 println("for (int i = 0; i < len" + i + "; i++) {");
570 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
572 } else if (isList(paramType)) { // A list
573 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
574 println("int paramEnum" + i + "[] = new int[len" + i + "];");
575 println("for (int i = 0; i < len" + i + "; i++) {");
576 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
578 } else { // Just one element
579 println("int paramEnum" + i + "[] = new int[1];");
580 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
588 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
590 private void checkAndWriteEnumRetTypeJavaStub(String retType) {
592 // Strips off array "[]" for return type
593 String pureType = getSimpleArrayType(getGenericType(retType));
594 // Take the inner type of generic
595 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
596 pureType = getGenericType(retType);
597 if (isEnumClass(pureType)) {
598 // Check if this is enum type
600 println("int[] retEnum = (int[]) retObj;");
601 println(pureType + "[] enumVals = " + pureType + ".values();");
602 if (isArray(retType)) { // An array
603 println("int retLen = retEnum.length;");
604 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
605 println("for (int i = 0; i < retLen; i++) {");
606 println("enumRetVal[i] = enumVals[retEnum[i]];");
608 } else if (isList(retType)) { // A list
609 println("int retLen = retEnum.length;");
610 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
611 println("for (int i = 0; i < retLen; i++) {");
612 println("enumRetVal.add(enumVals[retEnum[i]]);");
614 } else { // Just one element
615 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
617 println("return enumRetVal;");
623 * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
625 private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes,
626 InterfaceDecl intDecl, String method) {
628 // Iterate and find struct declarations
629 for (int i = 0; i < methParams.size(); i++) {
630 String paramType = methPrmTypes.get(i);
631 String param = methParams.get(i);
632 String simpleType = getGenericType(paramType);
633 if (isStructClass(simpleType)) {
634 // Check if this is enum type
635 int methodNumId = intDecl.getMethodNumId(method);
636 String helperMethod = methodNumId + "struct" + i;
637 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
638 println("Class<?> retTypeStruct" + i + " = void.class;");
639 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
640 if (isArray(param)) { // An array
641 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
642 } else if (isList(paramType)) { // A list
643 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
644 } else { // Just one element
645 println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
647 println("rmiCall.remoteCall(objectId, methodIdStruct" + i +
648 ", retTypeStruct" + i + ", null, paramClsStruct" + i +
649 ", paramObjStruct" + i + ");\n");
656 * HELPER: isStructPresent() checks presence of struct
658 private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
660 // Iterate and find enum declarations
661 for (int i = 0; i < methParams.size(); i++) {
662 String paramType = methPrmTypes.get(i);
663 String param = methParams.get(i);
664 String simpleType = getGenericType(paramType);
665 if (isStructClass(simpleType))
673 * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
675 private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
677 // Iterate and find struct declarations - count number of params
678 for (int i = 0; i < methParams.size(); i++) {
679 String paramType = methPrmTypes.get(i);
680 String param = methParams.get(i);
681 String simpleType = getGenericType(paramType);
682 if (isStructClass(simpleType)) {
683 int members = getNumOfMembers(simpleType);
684 if (isArray(param)) { // An array
685 String structLen = getSimpleArrayType(param) + ".length";
686 print(members + "*" + structLen);
687 } else if (isList(paramType)) { // A list
688 String structLen = getSimpleArrayType(param) + ".size()";
689 print(members + "*" + structLen);
691 print(Integer.toString(members));
694 if (i != methParams.size() - 1) {
702 * HELPER: writeStructMembersJavaStub() writes parameters of struct
704 private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
706 // Get the struct declaration for this struct and generate initialization code
707 StructDecl structDecl = getStructDecl(simpleType);
708 List<String> memTypes = structDecl.getMemberTypes(simpleType);
709 List<String> members = structDecl.getMembers(simpleType);
710 if (isArray(param)) { // An array
711 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".length; i++) {");
712 for (int i = 0; i < members.size(); i++) {
713 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
714 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
715 print("paramObj[pos++] = " + getSimpleIdentifier(param) + "[i].");
716 print(getSimpleIdentifier(members.get(i)));
720 } else if (isList(paramType)) { // A list
721 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
722 for (int i = 0; i < members.size(); i++) {
723 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
724 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
725 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".get(i).");
726 print(getSimpleIdentifier(members.get(i)));
730 } else { // Just one struct element
731 for (int i = 0; i < members.size(); i++) {
732 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
733 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
734 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".");
735 print(getSimpleIdentifier(members.get(i)));
743 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
745 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
747 print("int paramLen = ");
748 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
750 println("Object[] paramObj = new Object[paramLen];");
751 println("Class<?>[] paramCls = new Class<?>[paramLen];");
752 println("int pos = 0;");
753 // Iterate again over the parameters
754 for (int i = 0; i < methParams.size(); i++) {
755 String paramType = methPrmTypes.get(i);
756 String param = methParams.get(i);
757 String simpleType = getGenericType(paramType);
758 if (isStructClass(simpleType)) {
759 writeStructMembersJavaStub(simpleType, paramType, param);
760 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
761 println("paramCls[pos] = int.class;");
762 print("paramObj[pos++] = ");
763 if (isArray(methParams.get(i)))
764 print(getSimpleIdentifier(methParams.get(i)) + ".length");
765 else if (isList(methPrmTypes.get(i)))
766 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
768 print("new Integer(1)");
771 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
772 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
773 print("paramObj[pos++] = ");
774 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
783 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
785 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
787 // Get the struct declaration for this struct and generate initialization code
788 StructDecl structDecl = getStructDecl(simpleType);
789 List<String> memTypes = structDecl.getMemberTypes(simpleType);
790 List<String> members = structDecl.getMembers(simpleType);
791 if (isArrayOrList(retType, retType)) { // An array or list
792 println("for(int i = 0; i < retLen; i++) {");
794 if (isArray(retType)) { // An array
795 for (int i = 0; i < members.size(); i++) {
796 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
797 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
798 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
801 } else if (isList(retType)) { // A list
802 println(simpleType + " structRetMem = new " + simpleType + "();");
803 for (int i = 0; i < members.size(); i++) {
804 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
805 print("structRetMem." + getSimpleIdentifier(members.get(i)));
806 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
808 println("structRet.add(structRetMem);");
810 } else { // Just one struct element
811 for (int i = 0; i < members.size(); i++) {
812 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
813 print("structRet." + getSimpleIdentifier(members.get(i)));
814 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
817 println("return structRet;");
822 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
824 private void writeStructReturnJavaStub(String simpleType, String retType) {
826 // Handle the returned struct!!!
827 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
828 // Minimum retLen is 1 if this is a single struct object
829 println("int retLen = (int) retLenObj;");
830 int numMem = getNumOfMembers(simpleType);
831 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
832 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
833 println("int retPos = 0;");
834 // Get the struct declaration for this struct and generate initialization code
835 StructDecl structDecl = getStructDecl(simpleType);
836 List<String> memTypes = structDecl.getMemberTypes(simpleType);
837 List<String> members = structDecl.getMembers(simpleType);
838 if (isArrayOrList(retType, retType)) { // An array or list
839 println("for(int i = 0; i < retLen; i++) {");
840 for (int i = 0; i < members.size(); i++) {
841 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
842 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
843 println("retClsVal[retPos++] = null;");
846 } else { // Just one struct element
847 for (int i = 0; i < members.size(); i++) {
848 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
849 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
850 println("retClsVal[retPos++] = null;");
853 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
854 if (isArray(retType)) { // An array
855 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
856 println("for(int i = 0; i < retLen; i++) {");
857 println("structRet[i] = new " + simpleType + "();");
859 } else if (isList(retType)) { // A list
860 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
862 println(simpleType + " structRet = new " + simpleType + "();");
863 println("int retObjPos = 0;");
864 writeStructRetMembersJavaStub(simpleType, retType);
869 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
871 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
872 List<String> methPrmTypes, String method, String callbackType) {
874 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
875 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
876 String retType = intDecl.getMethodType(method);
877 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
878 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
879 // Generate array of parameter types
880 if (isStructPresent(methParams, methPrmTypes)) {
881 writeStructParamClassJavaStub(methParams, methPrmTypes, callbackType);
883 print("Class<?>[] paramCls = new Class<?>[] { ");
884 for (int i = 0; i < methParams.size(); i++) {
885 String prmType = methPrmTypes.get(i);
886 if (checkCallbackType(prmType, callbackType)) { // Check if this has callback object
888 } else { // Generate normal classes if it's not a callback object
889 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
890 print(getSimpleType(getEnumType(paramType)) + ".class");
892 // Check if this is the last element (don't print a comma)
893 if (i != methParams.size() - 1) {
898 // Generate array of parameter objects
899 print("Object[] paramObj = new Object[] { ");
900 for (int i = 0; i < methParams.size(); i++) {
901 String paramType = methPrmTypes.get(i);
902 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
903 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
904 if (isArray(methParams.get(i)))
905 print(getSimpleIdentifier(methParams.get(i)) + ".length");
906 else if (isList(methPrmTypes.get(i)))
907 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
909 print("new Integer(1)");
911 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
912 // Check if this is the last element (don't print a comma)
913 if (i != methParams.size() - 1) {
919 // Check if this is "void"
920 if (retType.equals("void")) {
921 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
922 } else { // We do have a return value
923 // Generate array of parameter types
924 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
925 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
927 // This is an enum type
928 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
929 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
930 checkAndWriteEnumRetTypeJavaStub(retType);
931 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
932 // Check if the return value NONPRIMITIVES
933 String retGenValType = getGenericType(retType);
934 println("Class<?> retGenValType = " + retGenValType + ".class;");
935 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
936 println("return (" + retType + ")retObj;");
938 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
939 println("return (" + retType + ")retObj;");
946 /*private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
947 List<String> methPrmTypes, String method) {
949 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
950 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
951 String retType = intDecl.getMethodType(method);
952 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
953 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
954 // Generate array of parameter types
955 if (isStructPresent(methParams, methPrmTypes)) {
956 writeStructParamClassJavaStub(methParams, methPrmTypes);
958 print("Class<?>[] paramCls = new Class<?>[] { ");
959 for (int i = 0; i < methParams.size(); i++) {
960 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
961 print(getSimpleType(getEnumType(paramType)) + ".class");
962 // Check if this is the last element (don't print a comma)
963 if (i != methParams.size() - 1) {
968 // Generate array of parameter objects
969 print("Object[] paramObj = new Object[] { ");
970 for (int i = 0; i < methParams.size(); i++) {
971 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
972 // Check if this is the last element (don't print a comma)
973 if (i != methParams.size() - 1) {
979 // Check if this is "void"
980 if (retType.equals("void")) {
981 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
982 } else { // We do have a return value
983 // Generate array of parameter types
984 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
985 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
987 // This is an enum type
988 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
989 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
990 checkAndWriteEnumRetTypeJavaStub(retType);
991 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
992 // Check if the return value NONPRIMITIVES
993 String retGenValType = getGenericType(retType);
994 println("Class<?> retGenValType = " + retGenValType + ".class;");
995 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
996 println("return (" + retType + ")retObj;");
998 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
999 println("return (" + retType + ")retObj;");
1007 * HELPER: returnGenericCallbackType() returns the callback type
1009 private String returnGenericCallbackType(String paramType) {
1011 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
1012 return getGenericType(paramType);
1019 * HELPER: checkCallbackType() checks the callback type
1021 private boolean checkCallbackType(String paramType, String callbackType) {
1023 String prmType = returnGenericCallbackType(paramType);
1024 if (callbackType == null) // If there is no callbackType it means not a callback method
1027 return callbackType.equals(prmType);
1032 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
1034 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
1035 List<String> methPrmTypes, String method, String callbackType) {
1038 // Check if this is single object, array, or list of objects
1039 for (int i = 0; i < methParams.size(); i++) {
1040 String paramType = methPrmTypes.get(i);
1041 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1042 String param = methParams.get(i);
1043 if (isArrayOrList(paramType, param)) { // Generate loop
1044 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
1045 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
1047 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(" +
1048 getSimpleIdentifier(param) + ", objIdCnt++);");
1049 println("listCallbackObj.add(skel" + i + ");");
1050 if (isArrayOrList(paramType, param))
1055 println(" catch (Exception ex) {");
1056 println("ex.printStackTrace();");
1057 println("throw new Error(\"Exception when generating skeleton objects!\");");
1062 /* private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
1063 List<String> methPrmTypes, String method, String callbackType) {
1066 // Check if this is single object, array, or list of objects
1067 for (int i = 0; i < methParams.size(); i++) {
1068 String paramType = methPrmTypes.get(i);
1069 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1070 String param = methParams.get(i);
1071 if (isArrayOrList(paramType, param)) { // Generate loop
1072 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
1073 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
1075 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(" +
1076 getSimpleIdentifier(param) + ", objIdCnt++);");
1077 println("listCallbackObj.add(skel" + i + ");");
1078 if (isArrayOrList(paramType, param))
1083 println(" catch (Exception ex) {");
1084 println("ex.printStackTrace();");
1085 println("throw new Error(\"Exception when generating skeleton objects!\");");
1087 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1088 String retType = intDecl.getMethodType(method);
1089 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
1090 // Generate array of parameter types
1091 print("Class<?>[] paramCls = new Class<?>[] { ");
1092 for (int i = 0; i < methParams.size(); i++) {
1093 String paramType = methPrmTypes.get(i);
1094 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1096 } else { // Generate normal classes if it's not a callback object
1097 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1098 print(getSimpleType(prmType) + ".class");
1100 if (i != methParams.size() - 1) // Check if this is the last element
1104 // Generate array of parameter objects
1105 print("Object[] paramObj = new Object[] { ");
1106 for (int i = 0; i < methParams.size(); i++) {
1107 String paramType = methPrmTypes.get(i);
1108 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1109 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
1110 if (isArray(methParams.get(i)))
1111 print(getSimpleIdentifier(methParams.get(i)) + ".length");
1112 else if (isList(methPrmTypes.get(i)))
1113 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
1115 print("new Integer(1)");
1117 print(getSimpleIdentifier(methParams.get(i)));
1118 if (i != methParams.size() - 1)
1122 // Check if this is "void"
1123 if (retType.equals("void")) {
1124 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1125 } else { // We do have a return value
1126 // Check if the return value NONPRIMITIVES
1127 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
1128 String[] retGenValType = getTypeOfGeneric(retType);
1129 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
1130 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
1131 println("return (" + retType + ")retObj;");
1133 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1134 println("return (" + retType + ")retObj;");
1141 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1143 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1145 boolean isDefined = false;
1146 for (String method : methods) {
1148 List<String> methParams = intDecl.getMethodParams(method);
1149 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1150 print("public " + intDecl.getMethodType(method) + " " +
1151 intDecl.getMethodId(method) + "(");
1152 boolean isCallbackMethod = false;
1153 String callbackType = null;
1154 for (int i = 0; i < methParams.size(); i++) {
1156 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1157 // Check if this has callback object
1158 if (callbackClasses.contains(paramType)) {
1159 isCallbackMethod = true;
1160 callbackType = paramType;
1161 // Even if there're 2 callback arguments, we expect them to be of the same interface
1163 print(methPrmTypes.get(i) + " " + methParams.get(i));
1164 // Check if this is the last element (don't print a comma)
1165 if (i != methParams.size() - 1) {
1170 // Now, write the body of stub!
1171 if (isCallbackMethod)
1172 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1174 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1176 // Write the init callback helper method
1177 if (isCallbackMethod && !isDefined) {
1178 writeInitCallbackJavaStub(callbackType, intDecl);
1186 * generateJavaStubClasses() generate stubs based on the methods list in Java
1188 public void generateJavaStubClasses() throws IOException {
1190 // Create a new directory
1191 String path = createDirectories(dir, subdir);
1192 for (String intface : mapIntfacePTH.keySet()) {
1194 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1195 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1197 // Open a new file to write into
1198 String newIntface = intMeth.getKey();
1199 String newStubClass = newIntface + "_Stub";
1200 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1201 pw = new PrintWriter(new BufferedWriter(fw));
1202 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1203 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1204 // Pass in set of methods and get import classes
1205 Set<String> methods = intMeth.getValue();
1206 Set<String> importClasses = getImportClasses(methods, intDecl);
1207 List<String> stdImportClasses = getStandardJavaImportClasses();
1208 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1209 printImportStatements(allImportClasses); println("");
1210 // Find out if there are callback objects
1211 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1212 boolean callbackExist = !callbackClasses.isEmpty();
1213 // Write class header
1214 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1216 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1217 // Write constructor
1218 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1220 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1223 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1230 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1232 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1234 println("private IoTRMICall rmiCall;");
1235 println("private String address;");
1236 println("private int[] ports;\n");
1237 // Get the object Id
1238 println("private int objectId = 0;");
1239 if (callbackExist) {
1240 // We assume that each class only has one callback interface for now
1241 Iterator it = callbackClasses.iterator();
1242 String callbackType = (String) it.next();
1243 println("// Callback properties");
1244 println("private IoTRMIObject rmiObj;");
1245 println("List<" + callbackType + "> listCallbackObj;");
1246 println("private static int objIdCnt = 0;");
1247 // Generate permission stuff for callback stubs
1248 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1249 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1250 writePropertiesJavaPermission(callbackType, intDecl);
1257 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1259 private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1261 // TODO: If we want callback in callback, then we need to add address and port initializations
1262 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1263 println("objectId = _objectId;");
1264 println("rmiCall = _rmiCall;");
1265 if (callbackExist) {
1266 Iterator it = callbackClasses.iterator();
1267 String callbackType = (String) it.next();
1268 writeConstructorJavaPermission(intface);
1269 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1270 println("___initCallBack();");
1271 println("// TODO: Add address and port initialization here if we want callback in callback!");
1278 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1280 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1281 * because all these stubs are populated by the class that takes in this object as a callback
1282 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1284 public void generateJavaCallbackStubClasses() throws IOException {
1286 // Create a new directory
1287 String path = createDirectories(dir, subdir);
1288 for (String intface : mapIntfacePTH.keySet()) {
1290 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1291 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1293 // Open a new file to write into
1294 String newIntface = intMeth.getKey();
1295 String newStubClass = newIntface + "_CallbackStub";
1296 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1297 pw = new PrintWriter(new BufferedWriter(fw));
1298 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1299 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1300 // Pass in set of methods and get import classes
1301 Set<String> methods = intMeth.getValue();
1302 Set<String> importClasses = getImportClasses(methods, intDecl);
1303 List<String> stdImportClasses = getStandardJavaImportClasses();
1304 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1305 printImportStatements(allImportClasses); println("");
1306 // Find out if there are callback objects
1307 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1308 boolean callbackExist = !callbackClasses.isEmpty();
1309 // Write class header
1310 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1312 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1313 // Write constructor
1314 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1316 // TODO: perhaps need to generate callback for callback
1317 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1320 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1327 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1329 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1331 println("private " + intface + " mainObj;");
1332 //println("private int ports;");
1333 println("private IoTRMIObject rmiObj;\n");
1335 if (callbackExist) {
1336 println("private static int objIdCnt = 0;");
1337 println("private IoTRMICall rmiCall;");
1339 writePropertiesJavaPermission(intface, intDecl);
1345 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1347 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1349 // Use this set to handle two same methodIds
1350 for (String method : methods) {
1351 List<String> methParams = intDecl.getMethodParams(method);
1352 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1353 // Check for params with structs
1354 for (int i = 0; i < methParams.size(); i++) {
1355 String paramType = methPrmTypes.get(i);
1356 String param = methParams.get(i);
1357 String simpleType = getGenericType(paramType);
1358 if (isStructClass(simpleType)) {
1359 int methodNumId = intDecl.getMethodNumId(method);
1360 String helperMethod = methodNumId + "struct" + i;
1361 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1362 // Iterate over interfaces to give permissions to
1363 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1364 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1365 String newIntface = intMeth.getKey();
1366 int newObjectId = getNewIntfaceObjectId(newIntface);
1367 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1376 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1378 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1380 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1381 println("mainObj = _mainObj;");
1382 println("rmiObj = new IoTRMIObject(_port);");
1383 // Generate permission control initialization
1384 writeConstructorJavaPermission(intface);
1385 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1386 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1387 println("___waitRequestInvokeMethod();");
1393 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1395 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1397 if (methodType.equals("void"))
1398 print("mainObj." + methodId + "(");
1400 print("return mainObj." + methodId + "(");
1401 for (int i = 0; i < methParams.size(); i++) {
1403 print(getSimpleIdentifier(methParams.get(i)));
1404 // Check if this is the last element (don't print a comma)
1405 if (i != methParams.size() - 1) {
1414 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1416 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1418 // This is a callback skeleton generation
1419 if (callbackSkeleton)
1420 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1422 println("public void ___regCB() throws IOException {");
1423 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1424 println("new Class<?>[] { null, null, null });");
1425 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1431 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1433 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1434 boolean callbackSkeleton) {
1436 boolean isDefined = false;
1437 for (String method : methods) {
1439 List<String> methParams = intDecl.getMethodParams(method);
1440 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1441 String methodId = intDecl.getMethodId(method);
1442 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1443 boolean isCallbackMethod = false;
1444 String callbackType = null;
1445 for (int i = 0; i < methParams.size(); i++) {
1447 String origParamType = methPrmTypes.get(i);
1448 String paramType = checkAndGetParamClass(origParamType);
1449 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1450 isCallbackMethod = true;
1451 callbackType = origParamType;
1453 print(paramType + " " + methParams.get(i));
1454 // Check if this is the last element (don't print a comma)
1455 if (i != methParams.size() - 1) {
1460 // Now, write the body of skeleton!
1461 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1463 if (isCallbackMethod && !isDefined) { // Make sure that this function is only defined once!
1464 writeInitCallbackJavaSkeleton(callbackSkeleton);
1472 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1474 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1475 String callbackType, boolean isStructMethod) {
1477 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1478 String offsetPfx = "";
1480 offsetPfx = "offset";
1481 // Iterate over callback objects
1482 for (int i = 0; i < methParams.size(); i++) {
1483 String paramType = methPrmTypes.get(i);
1484 String param = methParams.get(i);
1485 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1487 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1488 // Print array if this is array or list if this is a list of callback objects
1489 if (isArray(param)) {
1490 println("int numStubs" + i + " = (int) paramObj[" + offsetPfx + i + "];");
1491 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1492 } else if (isList(paramType)) {
1493 println("int numStubs" + i + " = (int) paramObj[" + offsetPfx + i + "];");
1494 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1496 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1497 println("objIdCnt++;");
1500 // Generate a loop if needed
1501 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1502 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1503 if (isArray(param)) {
1504 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1505 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1506 println("objIdCnt++;");
1508 } else if (isList(paramType)) {
1509 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1510 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1511 println("objIdCnt++;");
1514 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1517 return mapStubParam;
1522 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1524 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1526 // Iterate and find enum declarations
1527 for (int i = 0; i < methParams.size(); i++) {
1528 String paramType = methPrmTypes.get(i);
1529 String param = methParams.get(i);
1530 String simpleType = getGenericType(paramType);
1531 if (isEnumClass(simpleType)) {
1532 // Check if this is enum type
1533 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1534 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1535 if (isArray(param)) { // An array
1536 println("int len" + i + " = paramInt" + i + ".length;");
1537 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1538 println("for (int i = 0; i < len" + i + "; i++) {");
1539 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1541 } else if (isList(paramType)) { // A list
1542 println("int len" + i + " = paramInt" + i + ".length;");
1543 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1544 println("for (int i = 0; i < len" + i + "; i++) {");
1545 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1547 } else { // Just one element
1548 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1556 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1558 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1560 // Strips off array "[]" for return type
1561 String pureType = getSimpleArrayType(getGenericType(retType));
1562 // Take the inner type of generic
1563 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1564 pureType = getGenericType(retType);
1565 if (isEnumClass(pureType)) {
1566 // Check if this is enum type
1568 if (isArray(retType)) { // An array
1569 print(pureType + "[] retEnum = " + methodId + "(");
1570 } else if (isList(retType)) { // A list
1571 print("List<" + pureType + "> retEnum = " + methodId + "(");
1572 } else { // Just one element
1573 print(pureType + " retEnum = " + methodId + "(");
1580 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1582 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1584 // Strips off array "[]" for return type
1585 String pureType = getSimpleArrayType(getGenericType(retType));
1586 // Take the inner type of generic
1587 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1588 pureType = getGenericType(retType);
1589 if (isEnumClass(pureType)) {
1590 // Check if this is enum type
1591 if (isArray(retType)) { // An array
1592 println("int retLen = retEnum.length;");
1593 println("int[] retEnumVal = new int[retLen];");
1594 println("for (int i = 0; i < retLen; i++) {");
1595 println("retEnumVal[i] = retEnum[i].ordinal();");
1597 } else if (isList(retType)) { // A list
1598 println("int retLen = retEnum.size();");
1599 println("int[] retEnumVal = new int[retLen];");
1600 println("for (int i = 0; i < retLen; i++) {");
1601 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1603 } else { // Just one element
1604 println("int[] retEnumVal = new int[1];");
1605 println("retEnumVal[0] = retEnum.ordinal();");
1607 println("Object retObj = retEnumVal;");
1613 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1615 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1616 String method, InterfaceDecl intDecl) {
1618 // Iterate and find struct declarations - count number of params
1619 for (int i = 0; i < methParams.size(); i++) {
1620 String paramType = methPrmTypes.get(i);
1621 String param = methParams.get(i);
1622 String simpleType = getGenericType(paramType);
1623 if (isStructClass(simpleType)) {
1624 int members = getNumOfMembers(simpleType);
1625 print(Integer.toString(members) + "*");
1626 int methodNumId = intDecl.getMethodNumId(method);
1627 print("struct" + methodNumId + "Size" + i);
1630 if (i != methParams.size() - 1) {
1638 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1640 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1641 String param, String method, InterfaceDecl intDecl, int iVar) {
1643 // Get the struct declaration for this struct and generate initialization code
1644 StructDecl structDecl = getStructDecl(simpleType);
1645 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1646 List<String> members = structDecl.getMembers(simpleType);
1647 if (isArrayOrList(paramType, param)) { // An array or list
1648 int methodNumId = intDecl.getMethodNumId(method);
1649 String counter = "struct" + methodNumId + "Size" + iVar;
1650 println("for(int i = 0; i < " + counter + "; i++) {");
1652 if (isArrayOrList(paramType, param)) { // An array or list
1653 for (int i = 0; i < members.size(); i++) {
1654 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1655 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1656 println("paramClsGen[pos++] = null;");
1659 } else { // Just one struct element
1660 for (int i = 0; i < members.size(); i++) {
1661 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1662 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1663 println("paramClsGen[pos++] = null;");
1670 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1672 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1673 List<String> methPrmTypes, String method) {
1675 println("int objPos = 0;");
1676 for (int i = 0; i < methParams.size(); i++) {
1677 String paramType = methPrmTypes.get(i);
1678 String param = methParams.get(i);
1679 String simpleType = getGenericType(paramType);
1680 if (isStructClass(simpleType)) {
1681 int methodNumId = intDecl.getMethodNumId(method);
1682 String counter = "struct" + methodNumId + "Size" + i;
1684 if (isArray(param)) { // An array
1685 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1686 println("for(int i = 0; i < " + counter + "; i++) {");
1687 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1689 } else if (isList(paramType)) { // A list
1690 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1692 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1693 // Initialize members
1694 StructDecl structDecl = getStructDecl(simpleType);
1695 List<String> members = structDecl.getMembers(simpleType);
1696 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1697 if (isArrayOrList(paramType, param)) { // An array or list
1698 println("for(int i = 0; i < " + counter + "; i++) {");
1700 if (isArray(param)) { // An array
1701 for (int j = 0; j < members.size(); j++) {
1702 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1703 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1704 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1707 } else if (isList(paramType)) { // A list
1708 println(simpleType + " paramStructMem = new " + simpleType + "();");
1709 for (int j = 0; j < members.size(); j++) {
1710 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1711 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1712 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1714 println("paramStruct" + i + ".add(paramStructMem);");
1716 } else { // Just one struct element
1717 for (int j = 0; j < members.size(); j++) {
1718 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1719 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1720 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1724 // Take offsets of parameters
1725 println("int offset" + i +" = objPos++;");
1732 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1734 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1736 // Minimum retLen is 1 if this is a single struct object
1737 if (isArray(retType))
1738 println("int retLen = retStruct.length;");
1739 else if (isList(retType))
1740 println("int retLen = retStruct.size();");
1741 else // Just single struct object
1742 println("int retLen = 1;");
1743 println("Object retLenObj = retLen;");
1744 println("rmiObj.sendReturnObj(retLenObj);");
1745 int numMem = getNumOfMembers(simpleType);
1746 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1747 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1748 println("int retPos = 0;");
1749 // Get the struct declaration for this struct and generate initialization code
1750 StructDecl structDecl = getStructDecl(simpleType);
1751 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1752 List<String> members = structDecl.getMembers(simpleType);
1753 if (isArray(retType)) { // An array or list
1754 println("for(int i = 0; i < retLen; i++) {");
1755 for (int i = 0; i < members.size(); i++) {
1756 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1757 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1758 print("retObj[retPos++] = retStruct[i].");
1759 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1763 } else if (isList(retType)) { // An array or list
1764 println("for(int i = 0; i < retLen; i++) {");
1765 for (int i = 0; i < members.size(); i++) {
1766 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1767 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1768 print("retObj[retPos++] = retStruct.get(i).");
1769 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1773 } else { // Just one struct element
1774 for (int i = 0; i < members.size(); i++) {
1775 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1776 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1777 print("retObj[retPos++] = retStruct.");
1778 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1787 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1789 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1790 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1791 boolean isStructMethod) {
1793 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1794 Map<Integer,String> mapStubParam = null;
1795 if (isCallbackMethod) {
1796 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType, isStructMethod);
1798 // Check if this is "void"
1799 String retType = intDecl.getMethodType(method);
1800 if (retType.equals("void")) {
1801 print(intDecl.getMethodId(method) + "(");
1802 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1803 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1804 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1805 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1806 } else { // We do have a return value
1807 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1809 for (int i = 0; i < methParams.size(); i++) {
1811 String paramType = methPrmTypes.get(i);
1812 if (isCallbackMethod && checkCallbackType(paramType, callbackType)) {
1813 print(mapStubParam.get(i)); // Get the callback parameter
1814 } else if (isEnumClass(getGenericType(paramType))) { // Enum class
1815 print(getEnumParam(paramType, methParams.get(i), i));
1816 } else if (isStructClass(getGenericType(paramType))) {
1817 print("paramStruct" + i);
1819 String prmType = checkAndGetArray(paramType, methParams.get(i));
1821 print("(" + prmType + ") paramObj[offset" + i + "]");
1823 print("(" + prmType + ") paramObj[" + i + "]");
1825 if (i != methParams.size() - 1)
1829 if (!retType.equals("void")) {
1830 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1831 checkAndWriteEnumRetConvJavaSkeleton(retType);
1832 println("rmiObj.sendReturnObj(retObj);");
1833 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1834 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1835 println("rmiObj.sendReturnObj(retCls, retObj);");
1837 println("rmiObj.sendReturnObj(retObj);");
1839 if (isCallbackMethod) { // Catch exception if this is callback
1841 println(" catch(Exception ex) {");
1842 println("ex.printStackTrace();");
1843 println("throw new Error(\"Exception from callback object instantiation!\");");
1850 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1852 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1853 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1855 // Generate array of parameter objects
1856 boolean isCallbackMethod = false;
1857 String callbackType = null;
1858 print("int paramLen = ");
1859 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1861 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1862 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1863 println("int pos = 0;");
1864 // Iterate again over the parameters
1865 for (int i = 0; i < methParams.size(); i++) {
1866 String paramType = methPrmTypes.get(i);
1867 String param = methParams.get(i);
1868 String simpleType = getGenericType(paramType);
1869 if (isStructClass(simpleType)) {
1870 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1872 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1873 if (callbackClasses.contains(prmType)) {
1874 isCallbackMethod = true;
1875 callbackType = prmType;
1876 println("paramCls[pos] = int.class;");
1877 println("paramClsGen[pos++] = null;");
1878 } else { // Generate normal classes if it's not a callback object
1879 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1880 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1881 print("paramClsGen[pos++] = ");
1882 String prmTypeOth = methPrmTypes.get(i);
1883 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1884 println(getTypeOfGeneric(prmType)[0] + ".class;");
1890 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1891 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1892 // Write the return value part
1893 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1898 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1900 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1901 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1903 // Generate array of parameter objects
1904 boolean isCallbackMethod = false;
1905 String callbackType = null;
1906 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1907 for (int i = 0; i < methParams.size(); i++) {
1909 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1910 if (callbackClasses.contains(paramType)) {
1911 isCallbackMethod = true;
1912 callbackType = paramType;
1914 } else { // Generate normal classes if it's not a callback object
1915 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1916 print(getSimpleType(getEnumType(prmType)) + ".class");
1918 if (i != methParams.size() - 1)
1922 // Generate generic class if it's a generic type.. null otherwise
1923 print("new Class<?>[] { ");
1924 for (int i = 0; i < methParams.size(); i++) {
1925 String prmType = methPrmTypes.get(i);
1926 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1927 !isEnumClass(getGenericType(prmType)) &&
1928 !callbackClasses.contains(getGenericType(prmType)))
1929 print(getGenericType(prmType) + ".class");
1932 if (i != methParams.size() - 1)
1936 // Write the return value part
1937 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1942 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1944 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1946 // Use this set to handle two same methodIds
1947 Set<String> uniqueMethodIds = new HashSet<String>();
1948 for (String method : methods) {
1950 List<String> methParams = intDecl.getMethodParams(method);
1951 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1952 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1953 String methodId = intDecl.getMethodId(method);
1954 print("public void ___");
1955 String helperMethod = methodId;
1956 if (uniqueMethodIds.contains(methodId))
1957 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1959 uniqueMethodIds.add(methodId);
1960 String retType = intDecl.getMethodType(method);
1961 print(helperMethod + "(");
1962 boolean begin = true;
1963 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1964 String paramType = methPrmTypes.get(i);
1965 String param = methParams.get(i);
1966 String simpleType = getGenericType(paramType);
1967 if (isStructClass(simpleType)) {
1968 if (!begin) { // Generate comma for not the beginning variable
1969 print(", "); begin = false;
1971 int methodNumId = intDecl.getMethodNumId(method);
1972 print("int struct" + methodNumId + "Size" + i);
1975 // Check if this is "void"
1976 if (retType.equals("void"))
1979 println(") throws IOException {");
1980 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1983 String methodId = intDecl.getMethodId(method);
1984 print("public void ___");
1985 String helperMethod = methodId;
1986 if (uniqueMethodIds.contains(methodId))
1987 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1989 uniqueMethodIds.add(methodId);
1990 // Check if this is "void"
1991 String retType = intDecl.getMethodType(method);
1992 if (retType.equals("void"))
1993 println(helperMethod + "() {");
1995 println(helperMethod + "() throws IOException {");
1996 // Now, write the helper body of skeleton!
1997 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2001 // Write method helper for structs
2002 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
2007 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
2009 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
2010 InterfaceDecl intDecl) {
2012 // Use this set to handle two same methodIds
2013 for (String method : methods) {
2015 List<String> methParams = intDecl.getMethodParams(method);
2016 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2017 // Check for params with structs
2018 for (int i = 0; i < methParams.size(); i++) {
2019 String paramType = methPrmTypes.get(i);
2020 String param = methParams.get(i);
2021 String simpleType = getGenericType(paramType);
2022 if (isStructClass(simpleType)) {
2023 int methodNumId = intDecl.getMethodNumId(method);
2024 print("public int ___");
2025 String helperMethod = methodNumId + "struct" + i;
2026 println(helperMethod + "() {");
2027 // Now, write the helper body of skeleton!
2028 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
2029 println("return (int) paramObj[0];");
2038 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
2040 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
2041 InterfaceDecl intDecl) {
2043 // Use this set to handle two same methodIds
2044 for (String method : methods) {
2046 List<String> methParams = intDecl.getMethodParams(method);
2047 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2048 // Check for params with structs
2049 for (int i = 0; i < methParams.size(); i++) {
2050 String paramType = methPrmTypes.get(i);
2051 String param = methParams.get(i);
2052 String simpleType = getGenericType(paramType);
2053 if (isStructClass(simpleType)) {
2054 int methodNumId = intDecl.getMethodNumId(method);
2055 print("public int ___");
2056 String helperMethod = methodNumId + "struct" + i;
2057 println(helperMethod + "(IoTRMIObject rmiObj) {");
2058 // Now, write the helper body of skeleton!
2059 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
2060 println("return (int) paramObj[0];");
2069 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
2071 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2073 // Use this set to handle two same methodIds
2074 for (String method : methods) {
2076 List<String> methParams = intDecl.getMethodParams(method);
2077 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2078 // Check for params with structs
2079 for (int i = 0; i < methParams.size(); i++) {
2080 String paramType = methPrmTypes.get(i);
2081 String param = methParams.get(i);
2082 String simpleType = getGenericType(paramType);
2083 if (isStructClass(simpleType)) {
2084 int methodNumId = intDecl.getMethodNumId(method);
2085 println("int struct" + methodNumId + "Size" + i + " = 0;");
2093 * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
2095 private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
2097 List<String> methParams = intDecl.getMethodParams(method);
2098 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2099 boolean structExist = false;
2100 // Check for params with structs
2101 for (int i = 0; i < methParams.size(); i++) {
2102 String paramType = methPrmTypes.get(i);
2103 String param = methParams.get(i);
2104 String simpleType = getGenericType(paramType);
2105 boolean begin = true;
2106 if (isStructClass(simpleType)) {
2109 print(", "); begin = false;
2111 int methodNumId = intDecl.getMethodNumId(method);
2112 print("struct" + methodNumId + "Size" + i);
2120 * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
2122 private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2124 // Use this set to handle two same methodIds
2125 for (String method : methods) {
2127 List<String> methParams = intDecl.getMethodParams(method);
2128 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2129 // Check for params with structs
2130 for (int i = 0; i < methParams.size(); i++) {
2131 String paramType = methPrmTypes.get(i);
2132 String param = methParams.get(i);
2133 String simpleType = getGenericType(paramType);
2134 if (isStructClass(simpleType)) {
2135 int methodNumId = intDecl.getMethodNumId(method);
2137 String helperMethod = methodNumId + "struct" + i;
2138 String tempVar = "struct" + methodNumId + "Size" + i;
2139 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2140 print(tempVar + " = ___");
2141 println(helperMethod + "(); break;");
2149 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2151 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2153 // Use this set to handle two same methodIds
2154 for (String method : methods) {
2156 List<String> methParams = intDecl.getMethodParams(method);
2157 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2158 // Check for params with structs
2159 for (int i = 0; i < methParams.size(); i++) {
2160 String paramType = methPrmTypes.get(i);
2161 String param = methParams.get(i);
2162 String simpleType = getGenericType(paramType);
2163 if (isStructClass(simpleType)) {
2164 int methodNumId = intDecl.getMethodNumId(method);
2166 String helperMethod = methodNumId + "struct" + i;
2167 String tempVar = "struct" + methodNumId + "Size" + i;
2168 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2169 print(tempVar + " = ___");
2170 println(helperMethod + "(rmiObj); break;");
2178 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2180 private void writeJavaMethodPermission(String intface) {
2182 // Get all the different stubs
2183 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2184 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2185 String newIntface = intMeth.getKey();
2186 int newObjectId = getNewIntfaceObjectId(newIntface);
2187 println("if (_objectId == object" + newObjectId + "Id) {");
2188 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2189 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2193 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2200 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2202 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2204 // Use this set to handle two same methodIds
2205 Set<String> uniqueMethodIds = new HashSet<String>();
2206 println("private void ___waitRequestInvokeMethod() throws IOException {");
2207 // Write variables here if we have callbacks or enums or structs
2208 writeCountVarStructSkeleton(methods, intDecl);
2209 println("while (true) {");
2210 println("rmiObj.getMethodBytes();");
2211 println("int _objectId = rmiObj.getObjectId();");
2212 println("int methodId = rmiObj.getMethodId();");
2213 // Generate permission check
2214 writeJavaMethodPermission(intface);
2215 println("switch (methodId) {");
2216 // Print methods and method Ids
2217 for (String method : methods) {
2218 String methodId = intDecl.getMethodId(method);
2219 int methodNumId = intDecl.getMethodNumId(method);
2220 print("case " + methodNumId + ": ___");
2221 String helperMethod = methodId;
2222 if (uniqueMethodIds.contains(methodId))
2223 helperMethod = helperMethod + methodNumId;
2225 uniqueMethodIds.add(methodId);
2226 print(helperMethod + "(");
2227 writeInputCountVarStructSkeleton(method, intDecl);
2228 println("); break;");
2230 String method = "___initCallBack()";
2231 // Print case -9999 (callback handler) if callback exists
2232 if (callbackExist) {
2233 int methodId = intDecl.getHelperMethodNumId(method);
2234 println("case " + methodId + ": ___regCB(); break;");
2236 writeMethodCallStructSkeleton(methods, intDecl);
2237 println("default: ");
2238 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2246 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2248 public void generateJavaSkeletonClass() throws IOException {
2250 // Create a new directory
2251 String path = createDirectories(dir, subdir);
2252 for (String intface : mapIntfacePTH.keySet()) {
2253 // Open a new file to write into
2254 String newSkelClass = intface + "_Skeleton";
2255 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2256 pw = new PrintWriter(new BufferedWriter(fw));
2257 // Pass in set of methods and get import classes
2258 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2259 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2260 List<String> methods = intDecl.getMethods();
2261 Set<String> importClasses = getImportClasses(methods, intDecl);
2262 List<String> stdImportClasses = getStandardJavaImportClasses();
2263 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2264 printImportStatements(allImportClasses);
2265 // Find out if there are callback objects
2266 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2267 boolean callbackExist = !callbackClasses.isEmpty();
2268 // Write class header
2270 println("public class " + newSkelClass + " implements " + intface + " {\n");
2272 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2273 // Write constructor
2274 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2276 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2277 // Write method helper
2278 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2279 // Write waitRequestInvokeMethod() - main loop
2280 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2283 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2289 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2291 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2293 println("private " + intface + " mainObj;");
2294 // For callback skeletons, this is its own object Id
2295 println("private int objectId = 0;");
2297 if (callbackExist) {
2298 println("private static int objIdCnt = 0;");
2299 println("private IoTRMICall rmiCall;");
2306 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2308 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2310 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2311 println("mainObj = _mainObj;");
2312 println("objectId = _objectId;");
2318 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2320 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2322 // Use this set to handle two same methodIds
2323 Set<String> uniqueMethodIds = new HashSet<String>();
2324 for (String method : methods) {
2326 List<String> methParams = intDecl.getMethodParams(method);
2327 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2328 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
2329 String methodId = intDecl.getMethodId(method);
2330 print("public void ___");
2331 String helperMethod = methodId;
2332 if (uniqueMethodIds.contains(methodId))
2333 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2335 uniqueMethodIds.add(methodId);
2336 String retType = intDecl.getMethodType(method);
2337 print(helperMethod + "(");
2338 boolean begin = true;
2339 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2340 String paramType = methPrmTypes.get(i);
2341 String param = methParams.get(i);
2342 String simpleType = getGenericType(paramType);
2343 if (isStructClass(simpleType)) {
2344 if (!begin) { // Generate comma for not the beginning variable
2345 print(", "); begin = false;
2347 int methodNumId = intDecl.getMethodNumId(method);
2348 print("int struct" + methodNumId + "Size" + i);
2351 // Check if this is "void"
2352 if (retType.equals("void"))
2353 println(", IoTRMIObject rmiObj) {");
2355 println(", IoTRMIObject rmiObj) throws IOException {");
2356 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2359 String methodId = intDecl.getMethodId(method);
2360 print("public void ___");
2361 String helperMethod = methodId;
2362 if (uniqueMethodIds.contains(methodId))
2363 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2365 uniqueMethodIds.add(methodId);
2366 // Check if this is "void"
2367 String retType = intDecl.getMethodType(method);
2368 if (retType.equals("void"))
2369 println(helperMethod + "(IoTRMIObject rmiObj) {");
2371 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2372 // Now, write the helper body of skeleton!
2373 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2377 // Write method helper for structs
2378 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2383 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2385 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2387 // Use this set to handle two same methodIds
2388 Set<String> uniqueMethodIds = new HashSet<String>();
2389 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2390 // Write variables here if we have callbacks or enums or structs
2391 writeCountVarStructSkeleton(methods, intDecl);
2392 // Write variables here if we have callbacks or enums or structs
2393 println("int methodId = rmiObj.getMethodId();");
2394 // TODO: code the permission check here!
2395 println("switch (methodId) {");
2396 // Print methods and method Ids
2397 for (String method : methods) {
2398 String methodId = intDecl.getMethodId(method);
2399 int methodNumId = intDecl.getMethodNumId(method);
2400 print("case " + methodNumId + ": ___");
2401 String helperMethod = methodId;
2402 if (uniqueMethodIds.contains(methodId))
2403 helperMethod = helperMethod + methodNumId;
2405 uniqueMethodIds.add(methodId);
2406 print(helperMethod + "(");
2407 if (writeInputCountVarStructSkeleton(method, intDecl))
2408 println(", rmiObj); break;");
2410 println("rmiObj); break;");
2412 String method = "___initCallBack()";
2413 // Print case -9999 (callback handler) if callback exists
2414 if (callbackExist) {
2415 int methodId = intDecl.getHelperMethodNumId(method);
2416 println("case " + methodId + ": ___regCB(rmiObj); break;");
2418 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2419 println("default: ");
2420 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2427 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2429 public void generateJavaCallbackSkeletonClass() throws IOException {
2431 // Create a new directory
2432 String path = createDirectories(dir, subdir);
2433 for (String intface : mapIntfacePTH.keySet()) {
2434 // Open a new file to write into
2435 String newSkelClass = intface + "_CallbackSkeleton";
2436 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2437 pw = new PrintWriter(new BufferedWriter(fw));
2438 // Pass in set of methods and get import classes
2439 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2440 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2441 List<String> methods = intDecl.getMethods();
2442 Set<String> importClasses = getImportClasses(methods, intDecl);
2443 List<String> stdImportClasses = getStandardJavaImportClasses();
2444 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2445 printImportStatements(allImportClasses);
2446 // Find out if there are callback objects
2447 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2448 boolean callbackExist = !callbackClasses.isEmpty();
2449 // Write class header
2451 println("public class " + newSkelClass + " implements " + intface + " {\n");
2453 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2454 // Write constructor
2455 writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2457 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2458 // Write method helper
2459 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2460 // Write waitRequestInvokeMethod() - main loop
2461 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2464 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2470 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2472 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2474 for (String method : methods) {
2476 List<String> methParams = intDecl.getMethodParams(method);
2477 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2478 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2479 intDecl.getMethodId(method) + "(");
2480 for (int i = 0; i < methParams.size(); i++) {
2481 // Check for params with driver class types and exchange it
2482 // with its remote interface
2483 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2484 paramType = checkAndGetCplusType(paramType);
2485 // Check for arrays - translate into vector in C++
2486 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2487 print(paramComplete);
2488 // Check if this is the last element (don't print a comma)
2489 if (i != methParams.size() - 1) {
2499 * HELPER: writeMethodCplusInterface() writes the method of the interface
2501 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2503 for (String method : methods) {
2505 List<String> methParams = intDecl.getMethodParams(method);
2506 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2507 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2508 intDecl.getMethodId(method) + "(");
2509 for (int i = 0; i < methParams.size(); i++) {
2510 // Check for params with driver class types and exchange it
2511 // with its remote interface
2512 String paramType = methPrmTypes.get(i);
2513 paramType = checkAndGetCplusType(paramType);
2514 // Check for arrays - translate into vector in C++
2515 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2516 print(paramComplete);
2517 // Check if this is the last element (don't print a comma)
2518 if (i != methParams.size() - 1) {
2528 * HELPER: generateEnumCplus() writes the enumeration declaration
2530 public void generateEnumCplus() throws IOException {
2532 // Create a new directory
2533 createDirectory(dir);
2534 for (String intface : mapIntfacePTH.keySet()) {
2535 // Get the right StructDecl
2536 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2537 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2538 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2539 // Iterate over enum declarations
2540 for (String enType : enumTypes) {
2541 // Open a new file to write into
2542 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2543 pw = new PrintWriter(new BufferedWriter(fw));
2544 // Write file headers
2545 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2546 println("#define _" + enType.toUpperCase() + "_HPP__");
2547 println("enum " + enType + " {");
2548 List<String> enumMembers = enumDecl.getMembers(enType);
2549 for (int i = 0; i < enumMembers.size(); i++) {
2551 String member = enumMembers.get(i);
2553 // Check if this is the last element (don't print a comma)
2554 if (i != enumMembers.size() - 1)
2562 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2569 * HELPER: generateStructCplus() writes the struct declaration
2571 public void generateStructCplus() throws IOException {
2573 // Create a new directory
2574 createDirectory(dir);
2575 for (String intface : mapIntfacePTH.keySet()) {
2576 // Get the right StructDecl
2577 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2578 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2579 List<String> structTypes = structDecl.getStructTypes();
2580 // Iterate over enum declarations
2581 for (String stType : structTypes) {
2582 // Open a new file to write into
2583 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2584 pw = new PrintWriter(new BufferedWriter(fw));
2585 // Write file headers
2586 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2587 println("#define _" + stType.toUpperCase() + "_HPP__");
2588 println("using namespace std;");
2589 println("struct " + stType + " {");
2590 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2591 List<String> structMembers = structDecl.getMembers(stType);
2592 for (int i = 0; i < structMembers.size(); i++) {
2594 String memberType = structMemberTypes.get(i);
2595 String member = structMembers.get(i);
2596 String structTypeC = checkAndGetCplusType(memberType);
2597 String structComplete = checkAndGetCplusArray(structTypeC, member);
2598 println(structComplete + ";");
2603 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2610 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2612 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2613 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2614 * The local interface has to be the input parameter for the stub and the stub
2615 * interface has to be the input parameter for the local class.
2617 public void generateCplusLocalInterfaces() throws IOException {
2619 // Create a new directory
2620 createDirectory(dir);
2621 for (String intface : mapIntfacePTH.keySet()) {
2622 // Open a new file to write into
2623 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2624 pw = new PrintWriter(new BufferedWriter(fw));
2625 // Write file headers
2626 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2627 println("#define _" + intface.toUpperCase() + "_HPP__");
2628 println("#include <iostream>");
2629 // Pass in set of methods and get include classes
2630 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2631 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2632 List<String> methods = intDecl.getMethods();
2633 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2634 printIncludeStatements(includeClasses); println("");
2635 println("using namespace std;\n");
2636 //writeStructCplus(structDecl);
2637 println("class " + intface); println("{");
2640 writeMethodCplusLocalInterface(methods, intDecl);
2644 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2650 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2652 * For C++ we use virtual classe as interface
2654 public void generateCPlusInterfaces() throws IOException {
2656 // Create a new directory
2657 String path = createDirectories(dir, subdir);
2658 for (String intface : mapIntfacePTH.keySet()) {
2660 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2661 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2663 // Open a new file to write into
2664 String newIntface = intMeth.getKey();
2665 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2666 pw = new PrintWriter(new BufferedWriter(fw));
2667 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2668 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2669 // Write file headers
2670 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2671 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2672 println("#include <iostream>");
2673 // Pass in set of methods and get import classes
2674 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2675 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2676 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2677 printIncludeStatements(allIncludeClasses); println("");
2678 println("using namespace std;\n");
2679 println("class " + newIntface);
2683 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2687 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2694 * HELPER: writeMethodCplusStub() writes the methods of the stub
2696 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2698 boolean isDefined = false;
2699 for (String method : methods) {
2701 List<String> methParams = intDecl.getMethodParams(method);
2702 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2703 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2704 intDecl.getMethodId(method) + "(");
2705 boolean isCallbackMethod = false;
2706 String callbackType = null;
2707 for (int i = 0; i < methParams.size(); i++) {
2709 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2710 // Check if this has callback object
2711 if (callbackClasses.contains(paramType)) {
2712 isCallbackMethod = true;
2713 callbackType = paramType;
2714 // Even if there're 2 callback arguments, we expect them to be of the same interface
2716 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2717 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2718 print(methParamComplete);
2719 // Check if this is the last element (don't print a comma)
2720 if (i != methParams.size() - 1) {
2725 if (isCallbackMethod)
2726 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2728 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType, isCallbackMethod);
2730 // Write the init callback helper method
2731 if (isCallbackMethod && !isDefined) {
2732 writeInitCallbackCplusStub(callbackType, intDecl);
2733 writeInitCallbackSendInfoCplusStub(intDecl);
2741 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2743 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2744 List<String> methPrmTypes, String method, String callbackType) {
2746 // Check if this is single object, array, or list of objects
2747 boolean isArrayOrList = false;
2748 String callbackParam = null;
2749 for (int i = 0; i < methParams.size(); i++) {
2751 String paramType = methPrmTypes.get(i);
2752 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2753 String param = methParams.get(i);
2754 if (isArrayOrList(paramType, param)) { // Generate loop
2755 println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {");
2756 println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2757 isArrayOrList = true;
2758 callbackParam = getSimpleIdentifier(param);
2760 println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(" +
2761 getSimpleIdentifier(param) + ", objIdCnt++);");
2762 println("vecCallbackObj.push_back(skel" + i + ");");
2767 print("int ___paramCB = ");
2769 println(callbackParam + ".size();");
2774 /* private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2775 List<String> methPrmTypes, String method, String callbackType) {
2777 // Check if this is single object, array, or list of objects
2778 boolean isArrayOrList = false;
2779 String callbackParam = null;
2780 for (int i = 0; i < methParams.size(); i++) {
2782 String paramType = methPrmTypes.get(i);
2783 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2784 String param = methParams.get(i);
2785 if (isArrayOrList(paramType, param)) { // Generate loop
2786 println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {");
2787 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2788 isArrayOrList = true;
2789 callbackParam = getSimpleIdentifier(param);
2791 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2792 getSimpleIdentifier(param) + ", objIdCnt++);");
2793 println("vecCallbackObj.push_back(skel);");
2798 println("int numParam = " + methParams.size() + ";");
2799 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2800 String retType = intDecl.getMethodType(method);
2801 //String retTypeC = checkAndGetCplusType(retType);
2802 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2803 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2804 // Generate array of parameter types
2805 print("string paramCls[] = { ");
2806 for (int i = 0; i < methParams.size(); i++) {
2807 String paramType = methPrmTypes.get(i);
2808 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2810 } else { // Generate normal classes if it's not a callback object
2811 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2812 print("\"" + paramTypeC + "\"");
2814 if (i != methParams.size() - 1) // Check if this is the last element
2818 print("int ___paramCB = ");
2820 println(callbackParam + ".size();");
2823 // Generate array of parameter objects
2824 print("void* paramObj[] = { ");
2825 for (int i = 0; i < methParams.size(); i++) {
2826 String paramType = methPrmTypes.get(i);
2827 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2828 print("&___paramCB");
2830 print("&" + getSimpleIdentifier(methParams.get(i)));
2831 if (i != methParams.size() - 1)
2835 // Check if this is "void"
2836 if (retType.equals("void")) {
2837 println("void* retObj = NULL;");
2838 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2839 } else { // We do have a return value
2840 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2841 println(checkAndGetCplusType(retType) + " retVal;");
2843 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2844 println("void* retObj = &retVal;");
2845 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2846 println("return retVal;");
2852 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2854 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2856 // Iterate and find enum declarations
2857 for (int i = 0; i < methParams.size(); i++) {
2858 String paramType = methPrmTypes.get(i);
2859 String param = methParams.get(i);
2860 if (isEnumClass(getGenericType(paramType))) {
2861 // Check if this is enum type
2862 if (isArrayOrList(paramType, param)) { // An array or vector
2863 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2864 println("vector<int> paramEnum" + i + "(len" + i + ");");
2865 println("for (int i = 0; i < len" + i + "; i++) {");
2866 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2868 } else { // Just one element
2869 println("vector<int> paramEnum" + i + "(1);");
2870 println("paramEnum" + i + "[0] = (int) " + param + ";");
2878 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2880 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2882 // Strips off array "[]" for return type
2883 String pureType = getSimpleArrayType(getGenericType(retType));
2884 // Take the inner type of generic
2885 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2886 pureType = getGenericType(retType);
2887 if (isEnumClass(pureType)) {
2888 // Check if this is enum type
2889 println("vector<int> retEnumInt;");
2890 println("void* retObj = &retEnumInt;");
2891 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2892 if (isArrayOrList(retType, retType)) { // An array or vector
2893 println("int retLen = retEnumInt.size();");
2894 println("vector<" + pureType + "> retVal(retLen);");
2895 println("for (int i = 0; i < retLen; i++) {");
2896 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2898 } else { // Just one element
2899 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2901 println("return retVal;");
2907 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2909 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2910 InterfaceDecl intDecl, String method) {
2912 // Iterate and find struct declarations
2913 for (int i = 0; i < methParams.size(); i++) {
2914 String paramType = methPrmTypes.get(i);
2915 String param = methParams.get(i);
2916 String simpleType = getGenericType(paramType);
2917 if (isStructClass(simpleType)) {
2918 // Check if this is enum type
2919 println("int numParam" + i + " = 1;");
2920 int methodNumId = intDecl.getMethodNumId(method);
2921 String helperMethod = methodNumId + "struct" + i;
2922 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2923 println("string retTypeStruct" + i + " = \"void\";");
2924 println("string paramClsStruct" + i + "[] = { \"int\" };");
2925 print("int structLen" + i + " = ");
2926 if (isArrayOrList(paramType, param)) { // An array
2927 println(getSimpleArrayType(param) + ".size();");
2928 } else { // Just one element
2931 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2932 println("void* retStructLen" + i + " = NULL;");
2933 println("rmiCall->remoteCall(objectId, methodIdStruct" + i +
2934 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i +
2935 ", numParam" + i + ", retStructLen" + i + ");\n");
2942 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2944 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2946 // Iterate and find struct declarations - count number of params
2947 for (int i = 0; i < methParams.size(); i++) {
2948 String paramType = methPrmTypes.get(i);
2949 String param = methParams.get(i);
2950 String simpleType = getGenericType(paramType);
2951 if (isStructClass(simpleType)) {
2952 int members = getNumOfMembers(simpleType);
2953 if (isArrayOrList(paramType, param)) { // An array or list
2954 String structLen = getSimpleIdentifier(param) + ".size()";
2955 print(members + "*" + structLen);
2957 print(Integer.toString(members));
2960 if (i != methParams.size() - 1) {
2968 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2970 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2972 // Get the struct declaration for this struct and generate initialization code
2973 StructDecl structDecl = getStructDecl(simpleType);
2974 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2975 List<String> members = structDecl.getMembers(simpleType);
2976 if (isArrayOrList(paramType, param)) { // An array or list
2977 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
2979 if (isArrayOrList(paramType, param)) { // An array or list
2980 for (int i = 0; i < members.size(); i++) {
2981 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2982 println("paramCls[pos] = \"" + prmTypeC + "\";");
2983 print("paramObj[pos++] = &" + getSimpleIdentifier(param) + "[i].");
2984 print(getSimpleIdentifier(members.get(i)));
2988 } else { // Just one struct element
2989 for (int i = 0; i < members.size(); i++) {
2990 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2991 println("paramCls[pos] = \"" + prmTypeC + "\";");
2992 print("paramObj[pos++] = &" + param + ".");
2993 print(getSimpleIdentifier(members.get(i)));
3001 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
3003 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3005 print("int numParam = ");
3006 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
3008 println("void* paramObj[numParam];");
3009 println("string paramCls[numParam];");
3010 println("int pos = 0;");
3011 // Iterate again over the parameters
3012 for (int i = 0; i < methParams.size(); i++) {
3013 String paramType = methPrmTypes.get(i);
3014 String param = methParams.get(i);
3015 String simpleType = getGenericType(paramType);
3016 if (isStructClass(simpleType)) {
3017 writeStructMembersCplusStub(simpleType, paramType, param);
3018 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3019 println("paramCls[pos] = \"int\";");
3020 println("paramObj[pos++] = &___paramCB;");
3022 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3023 println("paramCls[pos] = \"" + prmTypeC + "\";");
3024 print("paramObj[pos++] = &");
3025 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
3034 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
3036 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
3038 // Get the struct declaration for this struct and generate initialization code
3039 StructDecl structDecl = getStructDecl(simpleType);
3040 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3041 List<String> members = structDecl.getMembers(simpleType);
3042 if (isArrayOrList(retType, retType)) { // An array or list
3043 println("for(int i = 0; i < retLen; i++) {");
3045 if (isArrayOrList(retType, retType)) { // An array or list
3046 for (int i = 0; i < members.size(); i++) {
3047 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
3048 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
3049 println(" = retParam" + i + "[i];");
3052 } else { // Just one struct element
3053 for (int i = 0; i < members.size(); i++) {
3054 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
3055 print("structRet." + getSimpleIdentifier(members.get(i)));
3056 println(" = retParam" + i + ";");
3059 println("return structRet;");
3064 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
3066 private void writeStructReturnCplusStub(String simpleType, String retType) {
3068 // Minimum retLen is 1 if this is a single struct object
3069 println("int retLen = 0;");
3070 println("void* retLenObj = { &retLen };");
3071 // Handle the returned struct!!!
3072 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
3073 int numMem = getNumOfMembers(simpleType);
3074 println("int numRet = " + numMem + "*retLen;");
3075 println("string retCls[numRet];");
3076 println("void* retObj[numRet];");
3077 StructDecl structDecl = getStructDecl(simpleType);
3078 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3079 List<String> members = structDecl.getMembers(simpleType);
3081 if (isArrayOrList(retType, retType)) { // An array or list
3082 for (int i = 0; i < members.size(); i++) {
3083 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3084 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3085 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
3087 } else { // Just one struct element
3088 for (int i = 0; i < members.size(); i++) {
3089 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3090 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3091 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
3094 println("int retPos = 0;");
3095 // Get the struct declaration for this struct and generate initialization code
3096 if (isArrayOrList(retType, retType)) { // An array or list
3097 println("for(int i = 0; i < retLen; i++) {");
3098 for (int i = 0; i < members.size(); i++) {
3099 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3100 println("retCls[retPos] = \"" + prmTypeC + "\";");
3101 println("retObj[retPos++] = &retParam" + i + "[i];");
3104 } else { // Just one struct element
3105 for (int i = 0; i < members.size(); i++) {
3106 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3107 println("retCls[retPos] = \"" + prmTypeC + "\";");
3108 println("retObj[retPos++] = &retParam" + i + ";");
3111 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
3112 if (isArrayOrList(retType, retType)) { // An array or list
3113 println("vector<" + simpleType + "> structRet(retLen);");
3115 println(simpleType + " structRet;");
3116 writeStructRetMembersCplusStub(simpleType, retType);
3121 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
3123 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
3124 List<String> methPrmTypes, String method, String callbackType, boolean isCallbackMethod) {
3126 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
3127 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
3128 String retType = intDecl.getMethodType(method);
3129 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
3130 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
3131 // Generate array of parameter types
3132 if (isStructPresent(methParams, methPrmTypes)) {
3133 writeStructParamClassCplusStub(methParams, methPrmTypes, callbackType);
3135 println("int numParam = " + methParams.size() + ";");
3136 print("string paramCls[] = { ");
3137 for (int i = 0; i < methParams.size(); i++) {
3138 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3139 if (checkCallbackType(paramType, callbackType)) {
3142 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3143 print("\"" + paramTypeC + "\"");
3145 // Check if this is the last element (don't print a comma)
3146 if (i != methParams.size() - 1) {
3151 // Generate array of parameter objects
3152 print("void* paramObj[] = { ");
3153 for (int i = 0; i < methParams.size(); i++) {
3154 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3155 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3156 print("&___paramCB");
3158 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
3159 // Check if this is the last element (don't print a comma)
3160 if (i != methParams.size() - 1) {
3166 // Check if this is "void"
3167 if (retType.equals("void")) {
3168 println("void* retObj = NULL;");
3169 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3170 } else { // We do have a return value
3171 // Generate array of parameter types
3172 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
3173 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
3175 // Check if the return value NONPRIMITIVES
3176 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
3177 checkAndWriteEnumRetTypeCplusStub(retType);
3179 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3180 if (isArrayOrList(retType,retType))
3181 println(checkAndGetCplusType(retType) + " retVal;");
3183 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3185 println("void* retObj = &retVal;");
3186 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3187 println("return retVal;");
3195 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3197 private void writePropertiesCplusPermission(String intface) {
3199 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3200 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3201 String newIntface = intMeth.getKey();
3202 int newObjectId = getNewIntfaceObjectId(newIntface);
3203 println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3204 println("static set<int> set" + newObjectId + "Allowed;");
3209 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3211 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3213 println("IoTRMICall *rmiCall;");
3214 //println("IoTRMIObject\t\t\t*rmiObj;");
3215 println("string address;");
3216 println("vector<int> ports;\n");
3217 // Get the object Id
3218 Integer objId = mapIntfaceObjId.get(intface);
3219 println("const static int objectId = " + objId + ";");
3220 mapNewIntfaceObjId.put(newIntface, objId);
3221 mapIntfaceObjId.put(intface, objId++);
3222 if (callbackExist) {
3223 // We assume that each class only has one callback interface for now
3224 Iterator it = callbackClasses.iterator();
3225 String callbackType = (String) it.next();
3226 println("// Callback properties");
3227 println("IoTRMIObject *rmiObj;");
3228 println("vector<" + callbackType + "*> vecCallbackObj;");
3229 println("static int objIdCnt;");
3230 // Generate permission stuff for callback stubs
3231 writePropertiesCplusPermission(callbackType);
3238 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3240 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3242 println(newStubClass +
3243 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3244 println("address = _address;");
3245 println("ports = _ports;");
3246 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3247 if (callbackExist) {
3248 Iterator it = callbackClasses.iterator();
3249 String callbackType = (String) it.next();
3250 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3251 println("th1.detach();");
3252 println("___regCB();");
3259 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3261 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3263 println("~" + newStubClass + "() {");
3264 println("if (rmiCall != NULL) {");
3265 println("delete rmiCall;");
3266 println("rmiCall = NULL;");
3268 if (callbackExist) {
3269 // We assume that each class only has one callback interface for now
3270 println("if (rmiObj != NULL) {");
3271 println("delete rmiObj;");
3272 println("rmiObj = NULL;");
3274 Iterator it = callbackClasses.iterator();
3275 String callbackType = (String) it.next();
3276 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3277 println("delete cb;");
3278 println("cb = NULL;");
3287 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3289 private void writeCplusMethodCallbackPermission(String intface) {
3291 println("int methodId = IoTRMIObject::getMethodId(method);");
3292 // Get all the different stubs
3293 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3294 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3295 String newIntface = intMeth.getKey();
3296 int newObjectId = getNewIntfaceObjectId(newIntface);
3297 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3298 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3306 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3308 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3310 println("void ___initCallBack() {");
3311 println("bool bResult = false;");
3312 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3313 println("while (true) {");
3314 println("char* method = rmiObj->getMethodBytes();");
3315 writeCplusMethodCallbackPermission(intface);
3316 println("int objId = IoTRMIObject::getObjectId(method);");
3317 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
3318 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
3319 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3320 println("skel->invokeMethod(rmiObj);");
3323 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3324 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3333 * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3335 private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3337 if (callbackExist) {
3338 String method = "___initCallBack()";
3339 int methodNumId = intDecl.getHelperMethodNumId(method);
3340 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3341 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3342 String newIntface = intMeth.getKey();
3343 int newObjectId = getNewIntfaceObjectId(newIntface);
3344 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3351 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3353 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3355 // Generate info sending part
3356 println("void ___regCB() {");
3357 println("int numParam = 3;");
3358 String method = "___initCallBack()";
3359 int methodNumId = intDecl.getHelperMethodNumId(method);
3360 println("int methodId = " + methodNumId + ";");
3361 //writeCplusCallbackPermission(intface, methodNumId);
3362 println("string retType = \"void\";");
3363 println("string paramCls[] = { \"int\", \"String\", \"int\" };");
3364 println("int rev = 0;");
3365 println("void* paramObj[] = { &ports[0], &address, &rev };");
3366 println("void* retObj = NULL;");
3367 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3373 * generateCPlusStubClasses() generate stubs based on the methods list in C++
3375 public void generateCPlusStubClasses() throws IOException {
3377 // Create a new directory
3378 String path = createDirectories(dir, subdir);
3379 for (String intface : mapIntfacePTH.keySet()) {
3381 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3382 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3383 // Open a new file to write into
3384 String newIntface = intMeth.getKey();
3385 String newStubClass = newIntface + "_Stub";
3386 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3387 pw = new PrintWriter(new BufferedWriter(fw));
3388 // Write file headers
3389 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3390 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3391 println("#include <iostream>");
3392 // Find out if there are callback objects
3393 Set<String> methods = intMeth.getValue();
3394 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3395 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3396 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3397 boolean callbackExist = !callbackClasses.isEmpty();
3398 if (callbackExist) // Need thread library if this has callback
3399 println("#include <thread>");
3400 println("#include \"" + newIntface + ".hpp\""); println("");
3401 println("using namespace std;"); println("");
3402 println("class " + newStubClass + " : public " + newIntface); println("{");
3403 println("private:\n");
3404 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3405 println("public:\n");
3406 // Add default constructor and destructor
3407 println(newStubClass + "() { }"); println("");
3408 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3409 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3411 writeMethodCplusStub(methods, intDecl, callbackClasses);
3412 print("}"); println(";");
3413 if (callbackExist) {
3414 Iterator it = callbackClasses.iterator();
3415 String callbackType = (String) it.next();
3416 // Generate permission stuff for callback stubs
3417 DeclarationHandler decHandlerCallback = mapIntDeclHand.get(callbackType);
3418 InterfaceDecl intDeclCallback = (InterfaceDecl) decHandlerCallback.getInterfaceDecl(callbackType);
3419 writePermissionInitializationCplus(callbackType, newStubClass, intDeclCallback);
3421 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3424 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3431 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3433 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3435 println("IoTRMICall *rmiCall;");
3436 // Get the object Id
3437 println("int objectId;");
3438 if (callbackExist) {
3439 // We assume that each class only has one callback interface for now
3440 Iterator it = callbackClasses.iterator();
3441 String callbackType = (String) it.next();
3442 println("// Callback properties");
3443 println("IoTRMIObject *rmiObj;");
3444 println("vector<" + callbackType + "*> vecCallbackObj;");
3445 println("static int objIdCnt;");
3446 // TODO: Need to initialize address and ports if we want to have callback-in-callback
3447 println("string address;");
3448 println("vector<int> ports;\n");
3449 writePropertiesCplusPermission(callbackType);
3456 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3458 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3460 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3461 println("objectId = _objectId;");
3462 println("rmiCall = _rmiCall;");
3463 if (callbackExist) {
3464 Iterator it = callbackClasses.iterator();
3465 String callbackType = (String) it.next();
3466 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3467 println("th1.detach();");
3468 println("___regCB();");
3475 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3477 public void generateCPlusCallbackStubClasses() throws IOException {
3479 // Create a new directory
3480 String path = createDirectories(dir, subdir);
3481 for (String intface : mapIntfacePTH.keySet()) {
3483 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3484 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3485 // Open a new file to write into
3486 String newIntface = intMeth.getKey();
3487 String newStubClass = newIntface + "_CallbackStub";
3488 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3489 pw = new PrintWriter(new BufferedWriter(fw));
3490 // Find out if there are callback objects
3491 Set<String> methods = intMeth.getValue();
3492 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3493 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3494 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3495 boolean callbackExist = !callbackClasses.isEmpty();
3496 // Write file headers
3497 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3498 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3499 println("#include <iostream>");
3501 println("#include <thread>");
3502 println("#include \"" + newIntface + ".hpp\""); println("");
3503 println("using namespace std;"); println("");
3504 println("class " + newStubClass + " : public " + newIntface); println("{");
3505 println("private:\n");
3506 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3507 println("public:\n");
3508 // Add default constructor and destructor
3509 println(newStubClass + "() { }"); println("");
3510 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3511 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3513 writeMethodCplusStub(methods, intDecl, callbackClasses);
3515 if (callbackExist) {
3516 Iterator it = callbackClasses.iterator();
3517 String callbackType = (String) it.next();
3518 // Generate permission stuff for callback stubs
3519 DeclarationHandler decHandlerCallback = mapIntDeclHand.get(callbackType);
3520 InterfaceDecl intDeclCallback = (InterfaceDecl) decHandlerCallback.getInterfaceDecl(callbackType);
3521 writePermissionInitializationCplus(callbackType, newStubClass, intDeclCallback);
3523 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3526 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3533 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3535 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3537 println(intface + " *mainObj;");
3539 if (callbackExist) {
3540 Iterator it = callbackClasses.iterator();
3541 String callbackType = (String) it.next();
3542 String exchangeType = checkAndGetParamClass(callbackType);
3543 println("// Callback properties");
3544 println("static int objIdCnt;");
3545 println("vector<" + exchangeType + "*> vecCallbackObj;");
3546 println("IoTRMICall *rmiCall;");
3548 println("IoTRMIObject *rmiObj;\n");
3549 // Keep track of object Ids of all stubs registered to this interface
3550 writePropertiesCplusPermission(intface);
3556 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3558 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3561 println("int " + newSkelClass + "::objIdCnt = 0;");
3566 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3568 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3570 // Keep track of object Ids of all stubs registered to this interface
3571 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3572 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3573 String newIntface = intMeth.getKey();
3574 int newObjectId = getNewIntfaceObjectId(newIntface);
3575 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed { ");
3576 Set<String> methodIds = intMeth.getValue();
3578 for (String methodId : methodIds) {
3579 int methodNumId = intDecl.getMethodNumId(methodId);
3580 print(Integer.toString(methodNumId));
3581 // Check if this is the last element (don't print a comma)
3582 if (i != methodIds.size() - 1) {
3593 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3595 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3597 // Use this set to handle two same methodIds
3598 for (String method : methods) {
3599 List<String> methParams = intDecl.getMethodParams(method);
3600 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3601 // Check for params with structs
3602 for (int i = 0; i < methParams.size(); i++) {
3603 String paramType = methPrmTypes.get(i);
3604 String param = methParams.get(i);
3605 String simpleType = getGenericType(paramType);
3606 if (isStructClass(simpleType)) {
3607 int methodNumId = intDecl.getMethodNumId(method);
3608 String helperMethod = methodNumId + "struct" + i;
3609 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3610 // Iterate over interfaces to give permissions to
3611 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3612 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3613 String newIntface = intMeth.getKey();
3614 int newObjectId = getNewIntfaceObjectId(newIntface);
3615 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3624 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3626 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3628 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3629 println("bool _bResult = false;");
3630 println("mainObj = _mainObj;");
3631 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3632 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3633 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3634 println("___waitRequestInvokeMethod();");
3640 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3642 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3644 println("~" + newSkelClass + "() {");
3645 println("if (rmiObj != NULL) {");
3646 println("delete rmiObj;");
3647 println("rmiObj = NULL;");
3649 if (callbackExist) {
3650 // We assume that each class only has one callback interface for now
3651 println("if (rmiCall != NULL) {");
3652 println("delete rmiCall;");
3653 println("rmiCall = NULL;");
3655 Iterator it = callbackClasses.iterator();
3656 String callbackType = (String) it.next();
3657 String exchangeType = checkAndGetParamClass(callbackType);
3658 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3659 println("delete cb;");
3660 println("cb = NULL;");
3669 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3671 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3673 if (methodType.equals("void"))
3674 print("mainObj->" + methodId + "(");
3676 print("return mainObj->" + methodId + "(");
3677 for (int i = 0; i < methParams.size(); i++) {
3679 print(getSimpleIdentifier(methParams.get(i)));
3680 // Check if this is the last element (don't print a comma)
3681 if (i != methParams.size() - 1) {
3690 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3692 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3694 // This is a callback skeleton generation
3695 if (callbackSkeleton)
3696 println("void ___regCB(IoTRMIObject* rmiObj) {");
3698 println("void ___regCB() {");
3699 println("int numParam = 3;");
3700 println("int param1 = 0;");
3701 println("string param2 = \"\";");
3702 println("int param3 = 0;");
3703 println("string paramCls[] = { \"int\", \"String\", \"int\" };");
3704 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
3705 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3706 println("bool bResult = false;");
3707 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3713 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3715 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3716 Set<String> callbackClasses, boolean callbackSkeleton) {
3718 boolean isDefined = false;
3719 for (String method : methods) {
3721 List<String> methParams = intDecl.getMethodParams(method);
3722 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3723 String methodId = intDecl.getMethodId(method);
3724 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3725 print(methodType + " " + methodId + "(");
3726 boolean isCallbackMethod = false;
3727 String callbackType = null;
3728 for (int i = 0; i < methParams.size(); i++) {
3730 String origParamType = methPrmTypes.get(i);
3731 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3732 isCallbackMethod = true;
3733 callbackType = origParamType;
3735 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3736 String methPrmType = checkAndGetCplusType(paramType);
3737 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3738 print(methParamComplete);
3739 // Check if this is the last element (don't print a comma)
3740 if (i != methParams.size() - 1) {
3745 // Now, write the body of skeleton!
3746 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3748 if (isCallbackMethod && !isDefined) {
3749 writeInitCallbackCplusSkeleton(callbackSkeleton);
3757 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3759 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3761 for (int i = 0; i < methParams.size(); i++) {
3762 String paramType = methPrmTypes.get(i);
3763 String param = methParams.get(i);
3764 //if (callbackType.equals(paramType)) {
3765 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3766 println("int numStubs" + i + " = 0;");
3772 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3774 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3776 // Iterate over callback objects
3777 for (int i = 0; i < methParams.size(); i++) {
3778 String paramType = methPrmTypes.get(i);
3779 String param = methParams.get(i);
3780 // Generate a loop if needed
3781 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3782 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
3783 if (isArrayOrList(paramType, param)) {
3784 println("vector<" + exchParamType + "*> stub" + i + ";");
3785 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3786 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3787 println("stub" + i + ".push_back(cb" + i + ");");
3788 println("vecCallbackObj.push_back(cb" + i + ");");
3789 println("objIdCnt++;");
3792 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3793 println("vecCallbackObj.push_back(stub" + i + ");");
3794 println("objIdCnt++;");
3802 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3804 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3806 // Iterate and find enum declarations
3807 for (int i = 0; i < methParams.size(); i++) {
3808 String paramType = methPrmTypes.get(i);
3809 String param = methParams.get(i);
3810 String simpleType = getGenericType(paramType);
3811 if (isEnumClass(simpleType)) {
3812 // Check if this is enum type
3813 if (isArrayOrList(paramType, param)) { // An array
3814 println("int len" + i + " = paramEnumInt" + i + ".size();");
3815 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3816 println("for (int i=0; i < len" + i + "; i++) {");
3817 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3819 } else { // Just one element
3820 println(simpleType + " paramEnum" + i + ";");
3821 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3829 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3831 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3833 // Strips off array "[]" for return type
3834 String pureType = getSimpleArrayType(getGenericType(retType));
3835 // Take the inner type of generic
3836 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3837 pureType = getGenericType(retType);
3838 if (isEnumClass(pureType)) {
3839 // Check if this is enum type
3841 if (isArrayOrList(retType, retType)) { // An array
3842 println("int retLen = retEnum.size();");
3843 println("vector<int> retEnumInt(retLen);");
3844 println("for (int i=0; i < retLen; i++) {");
3845 println("retEnumInt[i] = (int) retEnum[i];");
3847 } else { // Just one element
3848 println("vector<int> retEnumInt(1);");
3849 println("retEnumInt[0] = (int) retEnum;");
3856 * HELPER: writeMethodInputParameters() writes the parameter variables for C++ skeleton
3858 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3859 Set<String> callbackClasses, String methodId) {
3861 print(methodId + "(");
3862 for (int i = 0; i < methParams.size(); i++) {
3863 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3864 if (callbackClasses.contains(paramType))
3866 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3867 print("paramEnum" + i);
3868 else if (isStructClass(getGenericType(paramType))) // Struct type
3869 print("paramStruct" + i);
3871 print(getSimpleIdentifier(methParams.get(i)));
3872 if (i != methParams.size() - 1) {
3881 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3883 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3884 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3885 String methodId, Set<String> callbackClasses) {
3887 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3888 if (isCallbackMethod)
3889 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3890 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3891 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3892 // Check if this is "void"
3893 String retType = intDecl.getMethodType(method);
3894 // Check if this is "void"
3895 if (retType.equals("void")) {
3896 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3897 } else { // We do have a return value
3898 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3899 print(checkAndGetCplusType(retType) + " retEnum = ");
3900 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3901 print(checkAndGetCplusType(retType) + " retStruct = ");
3903 print(checkAndGetCplusType(retType) + " retVal = ");
3904 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3905 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3906 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3907 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3908 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3909 println("void* retObj = &retEnumInt;");
3911 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3912 println("void* retObj = &retVal;");
3913 String retTypeC = checkAndGetCplusType(retType);
3914 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3915 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3917 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3923 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3925 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3926 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3928 // Generate array of parameter types
3929 boolean isCallbackMethod = false;
3930 String callbackType = null;
3931 print("string paramCls[] = { ");
3932 for (int i = 0; i < methParams.size(); i++) {
3933 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3934 if (callbackClasses.contains(paramType)) {
3935 isCallbackMethod = true;
3936 callbackType = paramType;
3938 } else { // Generate normal classes if it's not a callback object
3939 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3940 print("\"" + paramTypeC + "\"");
3942 if (i != methParams.size() - 1) {
3947 println("int numParam = " + methParams.size() + ";");
3948 if (isCallbackMethod)
3949 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3950 // Generate parameters
3951 for (int i = 0; i < methParams.size(); i++) {
3952 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3953 if (!callbackClasses.contains(paramType)) {
3954 String methParamType = methPrmTypes.get(i);
3955 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3956 // Check if this is enum type
3957 println("vector<int> paramEnumInt" + i + ";");
3959 String methPrmType = checkAndGetCplusType(methParamType);
3960 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3961 println(methParamComplete + ";");
3965 // Generate array of parameter objects
3966 print("void* paramObj[] = { ");
3967 for (int i = 0; i < methParams.size(); i++) {
3968 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3969 if (callbackClasses.contains(paramType))
3970 print("&numStubs" + i);
3971 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3972 print("¶mEnumInt" + i);
3974 print("&" + getSimpleIdentifier(methParams.get(i)));
3975 if (i != methParams.size() - 1) {
3980 // Write the return value part
3981 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3982 callbackType, methodId, callbackClasses);
3987 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3989 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3990 String param, String method, InterfaceDecl intDecl, int iVar) {
3992 // Get the struct declaration for this struct and generate initialization code
3993 StructDecl structDecl = getStructDecl(simpleType);
3994 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3995 List<String> members = structDecl.getMembers(simpleType);
3996 int methodNumId = intDecl.getMethodNumId(method);
3997 String counter = "struct" + methodNumId + "Size" + iVar;
3999 if (isArrayOrList(paramType, param)) { // An array or list
4000 for (int i = 0; i < members.size(); i++) {
4001 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
4002 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
4003 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
4005 } else { // Just one struct element
4006 for (int i = 0; i < members.size(); i++) {
4007 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
4008 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
4009 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
4012 if (isArrayOrList(paramType, param)) { // An array or list
4013 println("for(int i = 0; i < " + counter + "; i++) {");
4015 if (isArrayOrList(paramType, param)) { // An array or list
4016 for (int i = 0; i < members.size(); i++) {
4017 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
4018 println("paramCls[pos] = \"" + prmTypeC + "\";");
4019 println("paramObj[pos++] = ¶m" + i + "[i];");
4022 } else { // Just one struct element
4023 for (int i = 0; i < members.size(); i++) {
4024 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
4025 println("paramCls[pos] = \"" + prmTypeC + "\";");
4026 println("paramObj[pos++] = ¶m" + i + ";");
4033 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
4035 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
4036 List<String> methPrmTypes, String method) {
4038 for (int i = 0; i < methParams.size(); i++) {
4039 String paramType = methPrmTypes.get(i);
4040 String param = methParams.get(i);
4041 String simpleType = getGenericType(paramType);
4042 if (isStructClass(simpleType)) {
4043 int methodNumId = intDecl.getMethodNumId(method);
4044 String counter = "struct" + methodNumId + "Size" + i;
4046 if (isArrayOrList(paramType, param)) { // An array or list
4047 println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
4049 println(simpleType + " paramStruct" + i + ";");
4050 // Initialize members
4051 StructDecl structDecl = getStructDecl(simpleType);
4052 List<String> members = structDecl.getMembers(simpleType);
4053 List<String> memTypes = structDecl.getMemberTypes(simpleType);
4054 if (isArrayOrList(paramType, param)) { // An array or list
4055 println("for(int i = 0; i < " + counter + "; i++) {");
4056 for (int j = 0; j < members.size(); j++) {
4057 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
4058 println(" = param" + j + "[i];");
4061 } else { // Just one struct element
4062 for (int j = 0; j < members.size(); j++) {
4063 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
4064 println(" = param" + j + ";");
4073 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
4075 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
4077 // Minimum retLen is 1 if this is a single struct object
4078 if (isArrayOrList(retType, retType))
4079 println("int retLen = retStruct.size();");
4080 else // Just single struct object
4081 println("int retLen = 1;");
4082 println("void* retLenObj = &retLen;");
4083 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
4084 int numMem = getNumOfMembers(simpleType);
4085 println("int numRetObj = " + numMem + "*retLen;");
4086 println("string retCls[numRetObj];");
4087 println("void* retObj[numRetObj];");
4088 println("int retPos = 0;");
4089 // Get the struct declaration for this struct and generate initialization code
4090 StructDecl structDecl = getStructDecl(simpleType);
4091 List<String> memTypes = structDecl.getMemberTypes(simpleType);
4092 List<String> members = structDecl.getMembers(simpleType);
4093 if (isArrayOrList(retType, retType)) { // An array or list
4094 println("for(int i = 0; i < retLen; i++) {");
4095 for (int i = 0; i < members.size(); i++) {
4096 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
4097 println("retCls[retPos] = \"" + prmTypeC + "\";");
4098 print("retObj[retPos++] = &retStruct[i].");
4099 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
4103 } else { // Just one struct element
4104 for (int i = 0; i < members.size(); i++) {
4105 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
4106 println("retCls[retPos] = \"" + prmTypeC + "\";");
4107 print("retObj[retPos++] = &retStruct.");
4108 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
4117 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
4119 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
4120 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
4122 // Generate array of parameter objects
4123 boolean isCallbackMethod = false;
4124 String callbackType = null;
4125 print("int numParam = ");
4126 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
4128 println("string paramCls[numParam];");
4129 println("void* paramObj[numParam];");
4130 println("int pos = 0;");
4131 // Iterate again over the parameters
4132 for (int i = 0; i < methParams.size(); i++) {
4133 String paramType = methPrmTypes.get(i);
4134 String param = methParams.get(i);
4135 String simpleType = getGenericType(paramType);
4136 if (isStructClass(simpleType)) {
4137 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
4139 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
4140 if (callbackClasses.contains(prmType)) {
4141 isCallbackMethod = true;
4142 callbackType = prmType;
4143 println("int numStubs" + i + " = 0;");
4144 println("paramCls[pos] = \"int\";");
4145 println("paramObj[pos++] = &numStubs" + i + ";");
4146 } else { // Generate normal classes if it's not a callback object
4147 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
4148 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
4149 println("vector<int> paramEnumInt" + i + ";");
4151 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
4152 println(methParamComplete + ";");
4154 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
4155 println("paramCls[pos] = \"" + prmTypeC + "\";");
4156 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
4157 println("paramObj[pos++] = ¶mEnumInt" + i + ";");
4159 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
4163 // Write the return value part
4164 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
4165 callbackType, methodId, callbackClasses);
4170 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
4172 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
4174 // Use this set to handle two same methodIds
4175 Set<String> uniqueMethodIds = new HashSet<String>();
4176 for (String method : methods) {
4178 List<String> methParams = intDecl.getMethodParams(method);
4179 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4180 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4181 String methodId = intDecl.getMethodId(method);
4183 String helperMethod = methodId;
4184 if (uniqueMethodIds.contains(methodId))
4185 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4187 uniqueMethodIds.add(methodId);
4188 String retType = intDecl.getMethodType(method);
4189 print(helperMethod + "(");
4190 boolean begin = true;
4191 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4192 String paramType = methPrmTypes.get(i);
4193 String param = methParams.get(i);
4194 String simpleType = getGenericType(paramType);
4195 if (isStructClass(simpleType)) {
4196 if (!begin) { // Generate comma for not the beginning variable
4197 print(", "); begin = false;
4199 int methodNumId = intDecl.getMethodNumId(method);
4200 print("int struct" + methodNumId + "Size" + i);
4204 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4207 String methodId = intDecl.getMethodId(method);
4209 String helperMethod = methodId;
4210 if (uniqueMethodIds.contains(methodId))
4211 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4213 uniqueMethodIds.add(methodId);
4214 // Check if this is "void"
4215 String retType = intDecl.getMethodType(method);
4216 println(helperMethod + "() {");
4217 // Now, write the helper body of skeleton!
4218 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4222 // Write method helper for structs
4223 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4228 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4230 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4231 InterfaceDecl intDecl) {
4233 // Use this set to handle two same methodIds
4234 for (String method : methods) {
4236 List<String> methParams = intDecl.getMethodParams(method);
4237 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4238 // Check for params with structs
4239 for (int i = 0; i < methParams.size(); i++) {
4240 String paramType = methPrmTypes.get(i);
4241 String param = methParams.get(i);
4242 String simpleType = getGenericType(paramType);
4243 if (isStructClass(simpleType)) {
4244 int methodNumId = intDecl.getMethodNumId(method);
4246 String helperMethod = methodNumId + "struct" + i;
4247 println(helperMethod + "() {");
4248 // Now, write the helper body of skeleton!
4249 println("string paramCls[] = { \"int\" };");
4250 println("int numParam = 1;");
4251 println("int param0 = 0;");
4252 println("void* paramObj[] = { ¶m0 };");
4253 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4254 println("return param0;");
4263 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4265 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4266 InterfaceDecl intDecl) {
4268 // Use this set to handle two same methodIds
4269 for (String method : methods) {
4271 List<String> methParams = intDecl.getMethodParams(method);
4272 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4273 // Check for params with structs
4274 for (int i = 0; i < methParams.size(); i++) {
4275 String paramType = methPrmTypes.get(i);
4276 String param = methParams.get(i);
4277 String simpleType = getGenericType(paramType);
4278 if (isStructClass(simpleType)) {
4279 int methodNumId = intDecl.getMethodNumId(method);
4281 String helperMethod = methodNumId + "struct" + i;
4282 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4283 // Now, write the helper body of skeleton!
4284 println("string paramCls[] = { \"int\" };");
4285 println("int numParam = 1;");
4286 println("int param0 = 0;");
4287 println("void* paramObj[] = { ¶m0 };");
4288 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4289 println("return param0;");
4298 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4300 private void writeCplusMethodPermission(String intface) {
4302 // Get all the different stubs
4303 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4304 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4305 String newIntface = intMeth.getKey();
4306 int newObjectId = getNewIntfaceObjectId(newIntface);
4307 println("if (_objectId == object" + newObjectId + "Id) {");
4308 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4309 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4314 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4322 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4324 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4326 // Use this set to handle two same methodIds
4327 Set<String> uniqueMethodIds = new HashSet<String>();
4328 println("void ___waitRequestInvokeMethod() {");
4329 // Write variables here if we have callbacks or enums or structs
4330 writeCountVarStructSkeleton(methods, intDecl);
4331 println("while (true) {");
4332 println("rmiObj->getMethodBytes();");
4333 println("int _objectId = rmiObj->getObjectId();");
4334 println("int methodId = rmiObj->getMethodId();");
4335 // Generate permission check
4336 writeCplusMethodPermission(intface);
4337 println("switch (methodId) {");
4338 // Print methods and method Ids
4339 for (String method : methods) {
4340 String methodId = intDecl.getMethodId(method);
4341 int methodNumId = intDecl.getMethodNumId(method);
4342 print("case " + methodNumId + ": ___");
4343 String helperMethod = methodId;
4344 if (uniqueMethodIds.contains(methodId))
4345 helperMethod = helperMethod + methodNumId;
4347 uniqueMethodIds.add(methodId);
4348 print(helperMethod + "(");
4349 writeInputCountVarStructSkeleton(method, intDecl);
4350 println("); break;");
4352 String method = "___initCallBack()";
4353 // Print case -9999 (callback handler) if callback exists
4354 if (callbackExist) {
4355 int methodId = intDecl.getHelperMethodNumId(method);
4356 println("case " + methodId + ": ___regCB(); break;");
4358 writeMethodCallStructSkeleton(methods, intDecl);
4359 println("default: ");
4360 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4361 println("throw exception();");
4369 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4371 public void generateCplusSkeletonClass() throws IOException {
4373 // Create a new directory
4374 String path = createDirectories(dir, subdir);
4375 for (String intface : mapIntfacePTH.keySet()) {
4376 // Open a new file to write into
4377 String newSkelClass = intface + "_Skeleton";
4378 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4379 pw = new PrintWriter(new BufferedWriter(fw));
4380 // Write file headers
4381 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4382 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4383 println("#include <iostream>");
4384 println("#include \"" + intface + ".hpp\"\n");
4385 // Pass in set of methods and get import classes
4386 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4387 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4388 List<String> methods = intDecl.getMethods();
4389 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4390 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4391 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4392 printIncludeStatements(allIncludeClasses); println("");
4393 println("using namespace std;\n");
4394 // Find out if there are callback objects
4395 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4396 boolean callbackExist = !callbackClasses.isEmpty();
4397 // Write class header
4398 println("class " + newSkelClass + " : public " + intface); println("{");
4399 println("private:\n");
4401 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4402 println("public:\n");
4403 // Write constructor
4404 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4405 // Write deconstructor
4406 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4408 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4409 // Write method helper
4410 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4411 // Write waitRequestInvokeMethod() - main loop
4412 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4414 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4415 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4418 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4424 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4426 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4428 println(intface + " *mainObj;");
4429 // Keep track of object Ids of all stubs registered to this interface
4430 println("int objectId;");
4432 if (callbackExist) {
4433 Iterator it = callbackClasses.iterator();
4434 String callbackType = (String) it.next();
4435 String exchangeType = checkAndGetParamClass(callbackType);
4436 println("// Callback properties");
4437 println("IoTRMICall* rmiCall;");
4438 println("vector<" + exchangeType + "*> vecCallbackObj;");
4439 println("static int objIdCnt;");
4446 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4448 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4450 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4451 println("mainObj = _mainObj;");
4452 println("objectId = _objectId;");
4458 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4460 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
4461 Set<String> callbackClasses) {
4463 println("~" + newStubClass + "() {");
4464 if (callbackExist) {
4465 // We assume that each class only has one callback interface for now
4466 println("if (rmiCall != NULL) {");
4467 println("delete rmiCall;");
4468 println("rmiCall = NULL;");
4470 Iterator it = callbackClasses.iterator();
4471 String callbackType = (String) it.next();
4472 String exchangeType = checkAndGetParamClass(callbackType);
4473 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4474 println("delete cb;");
4475 println("cb = NULL;");
4484 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4486 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4487 Set<String> callbackClasses) {
4489 // Use this set to handle two same methodIds
4490 Set<String> uniqueMethodIds = new HashSet<String>();
4491 for (String method : methods) {
4493 List<String> methParams = intDecl.getMethodParams(method);
4494 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4495 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4496 String methodId = intDecl.getMethodId(method);
4498 String helperMethod = methodId;
4499 if (uniqueMethodIds.contains(methodId))
4500 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4502 uniqueMethodIds.add(methodId);
4503 String retType = intDecl.getMethodType(method);
4504 print(helperMethod + "(");
4505 boolean begin = true;
4506 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4507 String paramType = methPrmTypes.get(i);
4508 String param = methParams.get(i);
4509 String simpleType = getGenericType(paramType);
4510 if (isStructClass(simpleType)) {
4511 if (!begin) { // Generate comma for not the beginning variable
4512 print(", "); begin = false;
4514 int methodNumId = intDecl.getMethodNumId(method);
4515 print("int struct" + methodNumId + "Size" + i);
4518 println(", IoTRMIObject* rmiObj) {");
4519 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4522 String methodId = intDecl.getMethodId(method);
4524 String helperMethod = methodId;
4525 if (uniqueMethodIds.contains(methodId))
4526 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4528 uniqueMethodIds.add(methodId);
4529 // Check if this is "void"
4530 String retType = intDecl.getMethodType(method);
4531 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4532 // Now, write the helper body of skeleton!
4533 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4537 // Write method helper for structs
4538 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4543 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4545 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4546 boolean callbackExist) {
4548 // Use this set to handle two same methodIds
4549 Set<String> uniqueMethodIds = new HashSet<String>();
4550 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4551 // Write variables here if we have callbacks or enums or structs
4552 writeCountVarStructSkeleton(methods, intDecl);
4553 // Write variables here if we have callbacks or enums or structs
4554 println("int methodId = rmiObj->getMethodId();");
4555 // TODO: code the permission check here!
4556 println("switch (methodId) {");
4557 // Print methods and method Ids
4558 for (String method : methods) {
4559 String methodId = intDecl.getMethodId(method);
4560 int methodNumId = intDecl.getMethodNumId(method);
4561 print("case " + methodNumId + ": ___");
4562 String helperMethod = methodId;
4563 if (uniqueMethodIds.contains(methodId))
4564 helperMethod = helperMethod + methodNumId;
4566 uniqueMethodIds.add(methodId);
4567 print(helperMethod + "(");
4568 if (writeInputCountVarStructSkeleton(method, intDecl))
4569 println(", rmiObj); break;");
4571 println("rmiObj); break;");
4573 String method = "___initCallBack()";
4574 // Print case -9999 (callback handler) if callback exists
4575 if (callbackExist) {
4576 int methodId = intDecl.getHelperMethodNumId(method);
4577 println("case " + methodId + ": ___regCB(rmiObj); break;");
4579 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4580 println("default: ");
4581 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4582 println("throw exception();");
4589 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4591 public void generateCplusCallbackSkeletonClass() throws IOException {
4593 // Create a new directory
4594 String path = createDirectories(dir, subdir);
4595 for (String intface : mapIntfacePTH.keySet()) {
4596 // Open a new file to write into
4597 String newSkelClass = intface + "_CallbackSkeleton";
4598 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4599 pw = new PrintWriter(new BufferedWriter(fw));
4600 // Write file headers
4601 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4602 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4603 println("#include <iostream>");
4604 println("#include \"" + intface + ".hpp\"\n");
4605 // Pass in set of methods and get import classes
4606 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4607 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4608 List<String> methods = intDecl.getMethods();
4609 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4610 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4611 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4612 printIncludeStatements(allIncludeClasses); println("");
4613 // Find out if there are callback objects
4614 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4615 boolean callbackExist = !callbackClasses.isEmpty();
4616 println("using namespace std;\n");
4617 // Write class header
4618 println("class " + newSkelClass + " : public " + intface); println("{");
4619 println("private:\n");
4621 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4622 println("public:\n");
4623 // Write constructor
4624 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4625 // Write deconstructor
4626 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4628 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4629 // Write method helper
4630 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4631 // Write waitRequestInvokeMethod() - main loop
4632 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4634 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4637 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4643 * generateInitializer() generate initializer based on type
4645 public String generateCplusInitializer(String type) {
4647 // Generate dummy returns for now
4648 if (type.equals("short")||
4649 type.equals("int") ||
4650 type.equals("long") ||
4651 type.equals("float")||
4652 type.equals("double")) {
4655 } else if ( type.equals("String") ||
4656 type.equals("string")) {
4659 } else if ( type.equals("char") ||
4660 type.equals("byte")) {
4663 } else if ( type.equals("boolean")) {
4673 * setDirectory() sets a new directory for stub files
4675 public void setDirectory(String _subdir) {
4682 * printUsage() prints the usage of this compiler
4684 public static void printUsage() {
4686 System.out.println();
4687 System.out.println("Sentinel interface and stub compiler version 1.0");
4688 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4689 System.out.println("All rights reserved.");
4690 System.out.println("Usage:");
4691 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4692 System.out.println("\t\tDisplay this help texts\n\n");
4693 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4694 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4695 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4696 System.out.println("Options:");
4697 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4698 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4699 System.out.println();
4704 * parseFile() prepares Lexer and Parser objects, then parses the file
4706 public static ParseNode parseFile(String file) {
4708 ParseNode pn = null;
4710 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4711 ScannerBuffer lexer =
4712 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4713 Parser parse = new Parser(lexer,csf);
4714 pn = (ParseNode) parse.parse().value;
4715 } catch (Exception e) {
4716 e.printStackTrace();
4717 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4725 * Basic helper functions
4728 boolean newline=true;
4731 private void print(String str) {
4734 if (str.equals("}"))
4736 for(int i=0; i<tab; i++)
4746 * This function converts Java to C++ type for compilation
4748 private String convertType(String type) {
4750 if (mapPrimitives.containsKey(type))
4751 return mapPrimitives.get(type);
4758 * A collection of methods with print-to-file functionality
4760 private void println(String str) {
4763 if (str.contains("}") && !str.contains("{"))
4765 for(int i=0; i<tab; i++)
4774 private void updatetabbing(String str) {
4776 tablevel+=count(str,'{')-count(str,'}');
4780 private int count(String str, char key) {
4781 char[] array = str.toCharArray();
4783 for(int i=0; i<array.length; i++) {
4784 if (array[i] == key)
4791 private void createDirectory(String dirName) {
4793 File file = new File(dirName);
4794 if (!file.exists()) {
4796 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4798 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4801 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4806 // Create a directory and possibly a sub directory
4807 private String createDirectories(String dir, String subdir) {
4810 createDirectory(path);
4811 if (subdir != null) {
4812 path = path + "/" + subdir;
4813 createDirectory(path);
4819 // Inserting array members into a Map object
4820 // that maps arrKey to arrVal objects
4821 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4823 for(int i = 0; i < arrKey.length; i++) {
4825 map.put(arrKey[i], arrVal[i]);
4830 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4831 // Throw an error if the new interface is not found!
4832 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4833 private int getNewIntfaceObjectId(String newIntface) {
4835 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4836 throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4837 "Please place the two files for callback class in front...\n");
4839 int retObjId = mapNewIntfaceObjId.get(newIntface);
4845 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4846 private ParamCategory getParamCategory(String paramType) {
4848 if (mapPrimitives.containsKey(paramType)) {
4849 return ParamCategory.PRIMITIVES;
4850 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4851 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4852 return ParamCategory.NONPRIMITIVES;
4853 } else if (isEnumClass(paramType)) {
4854 return ParamCategory.ENUM;
4855 } else if (isStructClass(paramType)) {
4856 return ParamCategory.STRUCT;
4858 return ParamCategory.USERDEFINED;
4862 // Return full class name for non-primitives to generate Java import statements
4863 // e.g. java.util.Set for Set
4864 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4866 return mapNonPrimitivesJava.get(paramNonPrimitives);
4870 // Return full class name for non-primitives to generate Cplus include statements
4871 // e.g. #include <set> for Set
4872 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4874 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4878 // Get simple types, e.g. HashSet for HashSet<...>
4879 // Basically strip off the "<...>"
4880 private String getSimpleType(String paramType) {
4882 // Check if this is generics
4883 if(paramType.contains("<")) {
4884 String[] type = paramType.split("<");
4891 // Generate a set of standard classes for import statements
4892 private List<String> getStandardJavaIntfaceImportClasses() {
4894 List<String> importClasses = new ArrayList<String>();
4895 // Add the standard list first
4896 importClasses.add("java.util.List");
4897 importClasses.add("java.util.ArrayList");
4899 return importClasses;
4903 // Generate a set of standard classes for import statements
4904 private List<String> getStandardJavaImportClasses() {
4906 List<String> importClasses = new ArrayList<String>();
4907 // Add the standard list first
4908 importClasses.add("java.io.IOException");
4909 importClasses.add("java.util.List");
4910 importClasses.add("java.util.ArrayList");
4911 importClasses.add("java.util.Arrays");
4912 importClasses.add("iotrmi.Java.IoTRMICall");
4913 importClasses.add("iotrmi.Java.IoTRMIObject");
4915 return importClasses;
4919 // Generate a set of standard classes for import statements
4920 private List<String> getStandardCplusIncludeClasses() {
4922 List<String> importClasses = new ArrayList<String>();
4923 // Add the standard list first
4924 importClasses.add("<vector>");
4925 importClasses.add("<set>");
4926 importClasses.add("\"IoTRMICall.hpp\"");
4927 importClasses.add("\"IoTRMIObject.hpp\"");
4929 return importClasses;
4933 // Combine all classes for import statements
4934 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4936 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4937 // Iterate over the list of import classes
4938 for (String str : libClasses) {
4939 if (!allLibClasses.contains(str)) {
4940 allLibClasses.add(str);
4943 return allLibClasses;
4948 // Generate a set of classes for import statements
4949 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4951 Set<String> importClasses = new HashSet<String>();
4952 for (String method : methods) {
4953 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4954 for (String paramType : methPrmTypes) {
4956 String simpleType = getSimpleType(paramType);
4957 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4958 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4962 return importClasses;
4966 // Handle and return the correct enum declaration
4967 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4968 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4970 // Strips off array "[]" for return type
4971 String pureType = getSimpleArrayType(type);
4972 // Take the inner type of generic
4973 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4974 pureType = getTypeOfGeneric(type)[0];
4975 if (isEnumClass(pureType)) {
4976 String enumType = intDecl.getInterface() + "." + type;
4983 // Handle and return the correct type
4984 private String getEnumParam(String type, String param, int i) {
4986 // Strips off array "[]" for return type
4987 String pureType = getSimpleArrayType(type);
4988 // Take the inner type of generic
4989 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4990 pureType = getTypeOfGeneric(type)[0];
4991 if (isEnumClass(pureType)) {
4992 String enumParam = "paramEnum" + i;
4999 // Handle and return the correct enum declaration translate into int[]
5000 private String getEnumType(String type) {
5002 // Strips off array "[]" for return type
5003 String pureType = getSimpleArrayType(type);
5004 // Take the inner type of generic
5005 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
5006 pureType = getGenericType(type);
5007 if (isEnumClass(pureType)) {
5008 String enumType = "int[]";
5014 // Handle and return the correct enum declaration translate into int* for C
5015 private String getEnumCplusClsType(String type) {
5017 // Strips off array "[]" for return type
5018 String pureType = getSimpleArrayType(type);
5019 // Take the inner type of generic
5020 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
5021 pureType = getGenericType(type);
5022 if (isEnumClass(pureType)) {
5023 String enumType = "int*";
5030 // Handle and return the correct struct declaration
5031 private String getStructType(String type) {
5033 // Strips off array "[]" for return type
5034 String pureType = getSimpleArrayType(type);
5035 // Take the inner type of generic
5036 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
5037 pureType = getGenericType(type);
5038 if (isStructClass(pureType)) {
5039 String structType = "int";
5046 // Check if this an enum declaration
5047 private boolean isEnumClass(String type) {
5049 // Just iterate over the set of interfaces
5050 for (String intface : mapIntfacePTH.keySet()) {
5051 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5052 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
5053 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
5054 if (setEnumDecl.contains(type))
5061 // Check if this an struct declaration
5062 private boolean isStructClass(String type) {
5064 // Just iterate over the set of interfaces
5065 for (String intface : mapIntfacePTH.keySet()) {
5066 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5067 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
5068 List<String> listStructDecl = structDecl.getStructTypes();
5069 if (listStructDecl.contains(type))
5076 // Return a struct declaration
5077 private StructDecl getStructDecl(String type) {
5079 // Just iterate over the set of interfaces
5080 for (String intface : mapIntfacePTH.keySet()) {
5081 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5082 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
5083 List<String> listStructDecl = structDecl.getStructTypes();
5084 if (listStructDecl.contains(type))
5091 // Return number of members (-1 if not found)
5092 private int getNumOfMembers(String type) {
5094 // Just iterate over the set of interfaces
5095 for (String intface : mapIntfacePTH.keySet()) {
5096 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5097 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
5098 List<String> listStructDecl = structDecl.getStructTypes();
5099 if (listStructDecl.contains(type))
5100 return structDecl.getNumOfMembers(type);
5106 // Generate a set of classes for include statements
5107 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
5109 Set<String> includeClasses = new HashSet<String>();
5110 for (String method : methods) {
5112 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
5113 List<String> methParams = intDecl.getMethodParams(method);
5114 for (int i = 0; i < methPrmTypes.size(); i++) {
5116 String simpleType = getSimpleType(methPrmTypes.get(i));
5117 String param = methParams.get(i);
5118 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
5119 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
5120 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
5121 // For original interface, we need it exchanged... not for stub interfaces
5123 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
5124 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
5126 includeClasses.add("\"" + simpleType + ".hpp\"");
5127 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
5129 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
5130 includeClasses.add("\"" + simpleType + ".hpp\"");
5131 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
5132 includeClasses.add("\"" + simpleType + ".hpp\"");
5133 } else if (param.contains("[]")) {
5134 // Check if this is array for C++; translate into vector
5135 includeClasses.add("<vector>");
5139 return includeClasses;
5143 // Generate a set of callback classes
5144 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
5146 Set<String> callbackClasses = new HashSet<String>();
5147 for (String method : methods) {
5149 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
5150 List<String> methParams = intDecl.getMethodParams(method);
5151 for (int i = 0; i < methPrmTypes.size(); i++) {
5153 String type = methPrmTypes.get(i);
5154 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5155 callbackClasses.add(type);
5156 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5157 // Can be a List<...> of callback objects ...
5158 String genericType = getTypeOfGeneric(type)[0];
5159 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5160 callbackClasses.add(type);
5165 return callbackClasses;
5169 // Print import statements into file
5170 private void printImportStatements(Collection<String> importClasses) {
5172 for(String cls : importClasses) {
5173 println("import " + cls + ";");
5178 // Print include statements into file
5179 private void printIncludeStatements(Collection<String> includeClasses) {
5181 for(String cls : includeClasses) {
5182 println("#include " + cls);
5187 // Get the C++ version of a non-primitive type
5188 // e.g. set for Set and map for Map
5189 // Input nonPrimitiveType has to be generics in format
5190 private String[] getTypeOfGeneric(String nonPrimitiveType) {
5192 // Handle <, >, and , for 2-type generic/template
5193 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5198 // Gets generic type inside "<" and ">"
5199 private String getGenericType(String type) {
5201 // Handle <, >, and , for 2-type generic/template
5202 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5203 String[] substr = type.split("<")[1].split(">")[0].split(",");
5210 // This helper function strips off array declaration, e.g. int[] becomes int
5211 private String getSimpleArrayType(String type) {
5213 // Handle [ for array declaration
5214 String substr = type;
5215 if (type.contains("[]")) {
5216 substr = type.split("\\[\\]")[0];
5222 // This helper function strips off array declaration, e.g. D[] becomes D
5223 private String getSimpleIdentifier(String ident) {
5225 // Handle [ for array declaration
5226 String substr = ident;
5227 if (ident.contains("[]")) {
5228 substr = ident.split("\\[\\]")[0];
5234 // Checks and gets type in C++
5235 private String checkAndGetCplusType(String paramType) {
5237 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5238 return convertType(paramType);
5239 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5241 // Check for generic/template format
5242 if (paramType.contains("<") && paramType.contains(">")) {
5244 String genericClass = getSimpleType(paramType);
5245 String genericType = getGenericType(paramType);
5246 String cplusTemplate = null;
5247 cplusTemplate = getNonPrimitiveCplusClass(genericClass);
5248 if(getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED) {
5249 cplusTemplate = cplusTemplate + "<" + genericType + "*>";
5251 cplusTemplate = cplusTemplate + "<" + convertType(genericType) + ">";
5253 return cplusTemplate;
5255 return getNonPrimitiveCplusClass(paramType);
5256 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5257 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5259 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5260 return paramType + "*";
5262 // Just return it as is if it's not non-primitives
5267 // Detect array declaration, e.g. int A[],
5268 // then generate "int A[]" in C++ as "vector<int> A"
5269 private String checkAndGetCplusArray(String paramType, String param) {
5271 String paramComplete = null;
5272 // Check for array declaration
5273 if (param.contains("[]")) {
5274 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5276 // Just return it as is if it's not an array
5277 paramComplete = paramType + " " + param;
5279 return paramComplete;
5283 // Detect array declaration, e.g. int A[],
5284 // then generate "int A[]" in C++ as "vector<int> A"
5285 // This method just returns the type
5286 private String checkAndGetCplusArrayType(String paramType) {
5288 String paramTypeRet = null;
5289 // Check for array declaration
5290 if (paramType.contains("[]")) {
5291 String type = paramType.split("\\[\\]")[0];
5292 paramTypeRet = checkAndGetCplusType(type) + "[]";
5293 } else if (paramType.contains("vector")) {
5294 // Just return it as is if it's not an array
5295 String type = paramType.split("<")[1].split(">")[0];
5296 paramTypeRet = checkAndGetCplusType(type) + "[]";
5298 paramTypeRet = paramType;
5300 return paramTypeRet;
5304 // Detect array declaration, e.g. int A[],
5305 // then generate "int A[]" in C++ as "vector<int> A"
5306 // This method just returns the type
5307 private String checkAndGetCplusArrayType(String paramType, String param) {
5309 String paramTypeRet = null;
5310 // Check for array declaration
5311 if (param.contains("[]")) {
5312 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5313 } else if (paramType.contains("vector")) {
5314 // Just return it as is if it's not an array
5315 String type = paramType.split("<")[1].split(">")[0];
5316 paramTypeRet = checkAndGetCplusType(type) + "[]";
5318 paramTypeRet = paramType;
5320 return paramTypeRet;
5324 // Return the class type for class resolution (for return value)
5325 // - Check and return C++ array class, e.g. int A[] into int*
5326 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5327 private String checkAndGetCplusRetClsType(String paramType) {
5329 String paramTypeRet = null;
5330 // Check for array declaration
5331 if (paramType.contains("[]")) {
5332 String type = paramType.split("\\[\\]")[0];
5333 paramTypeRet = getSimpleArrayType(type) + "*";
5334 } else if (paramType.contains("<") && paramType.contains(">")) {
5335 // Just return it as is if it's not an array
5336 String type = paramType.split("<")[1].split(">")[0];
5337 paramTypeRet = "vector<" + getGenericType(type) + ">";
5339 paramTypeRet = paramType;
5341 return paramTypeRet;
5345 // Return the class type for class resolution (for method arguments)
5346 // - Check and return C++ array class, e.g. int A[] into int*
5347 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5348 private String checkAndGetCplusArgClsType(String paramType, String param) {
5350 String paramTypeRet = getEnumCplusClsType(paramType);
5351 if (!paramTypeRet.equals(paramType))
5352 // Just return if it is an enum type
5353 // Type will still be the same if it's not an enum type
5354 return paramTypeRet;
5356 // Check for array declaration
5357 if (param.contains("[]")) {
5358 paramTypeRet = getSimpleArrayType(paramType) + "*";
5359 } else if (paramType.contains("<") && paramType.contains(">")) {
5360 // Just return it as is if it's not an array
5361 String type = paramType.split("<")[1].split(">")[0];
5362 paramTypeRet = "vector<" + getGenericType(type) + ">";
5364 paramTypeRet = paramType;
5366 return paramTypeRet;
5370 // Detect array declaration, e.g. int A[],
5371 // then generate type "int[]"
5372 private String checkAndGetArray(String paramType, String param) {
5374 String paramTypeRet = null;
5375 // Check for array declaration
5376 if (param.contains("[]")) {
5377 paramTypeRet = paramType + "[]";
5379 // Just return it as is if it's not an array
5380 paramTypeRet = paramType;
5382 return paramTypeRet;
5386 // Is array or list?
5387 private boolean isArrayOrList(String paramType, String param) {
5389 // Check for array declaration
5392 else if (isList(paramType))
5400 // For return type we use retType as input parameter
5401 private boolean isArray(String param) {
5403 // Check for array declaration
5404 if (param.contains("[]"))
5412 private boolean isList(String paramType) {
5414 // Check for array declaration
5415 if (paramType.contains("List"))
5422 // Get the right type for a callback object
5423 private String checkAndGetParamClass(String paramType) {
5425 // Check if this is generics
5426 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5427 return exchangeParamType(paramType);
5428 } else if (isList(paramType) &&
5429 (getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED)) {
5430 return "List<" + exchangeParamType(getGenericType(paramType)) + ">";
5436 // Returns the other interface for type-checking purposes for USERDEFINED
5437 // classes based on the information provided in multiple policy files
5438 // e.g. return CameraWithXXX instead of Camera
5439 private String exchangeParamType(String intface) {
5441 // Param type that's passed is the interface name we need to look for
5442 // in the map of interfaces, based on available policy files.
5443 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5444 if (decHandler != null) {
5445 // We've found the required interface policy files
5446 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5447 Set<String> setExchInt = reqDecl.getInterfaces();
5448 if (setExchInt.size() == 1) {
5449 Iterator iter = setExchInt.iterator();
5450 return (String) iter.next();
5452 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5453 ". Only one new interface can be declared if the object " + intface +
5454 " needs to be passed in as an input parameter!\n");
5457 // NULL value - this means policy files missing
5458 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5459 "... Please provide the necessary policy files for user-defined types." +
5460 " If this is an array please type the brackets after the variable name," +
5461 " e.g. \"String str[]\", not \"String[] str\"." +
5462 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5463 " supports List/ArrayList (Java) or list (C++).\n");
5468 public static void main(String[] args) throws Exception {
5470 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5471 if ((args[0].equals("-help") ||
5472 args[0].equals("--help")||
5473 args[0].equals("-h")) ||
5474 (args.length == 0)) {
5476 IoTCompiler.printUsage();
5478 } else if (args.length > 1) {
5480 IoTCompiler comp = new IoTCompiler();
5483 // Parse main policy file
5484 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5485 // Parse "requires" policy file
5486 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5487 // Get interface name
5488 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5489 comp.setDataStructures(intface, pnPol, pnReq);
5490 comp.getMethodsForIntface(intface);
5492 // 1) Check if this is the last option before "-java" or "-cplus"
5493 // 2) Check if this is really the last option (no "-java" or "-cplus")
5494 } while(!args[i].equals("-java") &&
5495 !args[i].equals("-cplus") &&
5498 // Generate everything if we don't see "-java" or "-cplus"
5499 if (i == args.length) {
5500 comp.generateEnumJava();
5501 comp.generateStructJava();
5502 comp.generateJavaLocalInterfaces();
5503 comp.generateJavaInterfaces();
5504 comp.generateJavaStubClasses();
5505 comp.generateJavaCallbackStubClasses();
5506 comp.generateJavaSkeletonClass();
5507 comp.generateJavaCallbackSkeletonClass();
5508 comp.generateEnumCplus();
5509 comp.generateStructCplus();
5510 comp.generateCplusLocalInterfaces();
5511 comp.generateCPlusInterfaces();
5512 comp.generateCPlusStubClasses();
5513 comp.generateCPlusCallbackStubClasses();
5514 comp.generateCplusSkeletonClass();
5515 comp.generateCplusCallbackSkeletonClass();
5517 // Check other options
5518 while(i < args.length) {
5520 if (!args[i].equals("-java") &&
5521 !args[i].equals("-cplus")) {
5522 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5524 if (i + 1 < args.length) {
5525 comp.setDirectory(args[i+1]);
5527 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5529 if (args[i].equals("-java")) {
5530 comp.generateEnumJava();
5531 comp.generateStructJava();
5532 comp.generateJavaLocalInterfaces();
5533 comp.generateJavaInterfaces();
5534 comp.generateJavaStubClasses();
5535 comp.generateJavaCallbackStubClasses();
5536 comp.generateJavaSkeletonClass();
5537 comp.generateJavaCallbackSkeletonClass();
5539 comp.generateEnumCplus();
5540 comp.generateStructCplus();
5541 comp.generateCplusLocalInterfaces();
5542 comp.generateCPlusInterfaces();
5543 comp.generateCPlusStubClasses();
5544 comp.generateCPlusCallbackStubClasses();
5545 comp.generateCplusSkeletonClass();
5546 comp.generateCplusCallbackSkeletonClass();
5553 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5554 IoTCompiler.printUsage();
5555 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");