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 = Arrays.asList(object" + newObjectId +"Permission);");
456 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
458 private void writeConstructorJavaStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
460 println("public " + newStubClass + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
461 println("address = _address;");
462 println("ports = _ports;");
463 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
465 Iterator it = callbackClasses.iterator();
466 String callbackType = (String) it.next();
467 writeConstructorJavaPermission(intface);
468 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
469 println("___initCallBack();");
476 * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
478 private void writeJavaMethodCallbackPermission(String intface) {
480 println("int methodId = IoTRMIObject.getMethodId(method);");
481 // Get all the different stubs
482 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
483 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
484 String newIntface = intMeth.getKey();
485 int newObjectId = getNewIntfaceObjectId(newIntface);
486 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
487 println("throw new Error(\"Callback object for " + intface + " is not allowed to access method: \" + methodId);");
494 * HELPER: writeJavaInitCallbackPermission() writes the permission for callback
496 private void writeJavaInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
499 String method = "___initCallBack()";
500 int methodNumId = intDecl.getHelperMethodNumId(method);
501 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
502 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
503 String newIntface = intMeth.getKey();
504 int newObjectId = getNewIntfaceObjectId(newIntface);
505 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
512 * HELPER: writeInitCallbackJavaStub() writes callback initialization in stub
514 private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
516 println("public void ___initCallBack() {");
517 // Generate main thread for callbacks
518 println("Thread thread = new Thread() {");
519 println("public void run() {");
521 println("rmiObj = new IoTRMIObject(ports[0]);");
522 println("while (true) {");
523 println("byte[] method = rmiObj.getMethodBytes();");
524 writeJavaMethodCallbackPermission(intface);
525 println("int objId = IoTRMIObject.getObjectId(method);");
526 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
527 println("if (skel != null) {");
528 println("skel.invokeMethod(rmiObj);");
531 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
535 println(" catch (Exception ex) {");
536 println("ex.printStackTrace();");
537 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
541 println("thread.start();\n");
542 // Generate info sending part
543 String method = "___initCallBack()";
544 int methodNumId = intDecl.getHelperMethodNumId(method);
545 println("int methodId = " + methodNumId + ";");
546 println("Class<?> retType = void.class;");
547 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
548 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
549 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
555 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
557 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
559 // Iterate and find enum declarations
560 for (int i = 0; i < methParams.size(); i++) {
561 String paramType = methPrmTypes.get(i);
562 String param = methParams.get(i);
563 String simpleType = getGenericType(paramType);
564 if (isEnumClass(simpleType)) {
565 // Check if this is enum type
566 if (isArray(param)) { // An array
567 println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
568 println("int paramEnum" + i + "[] = new int[len" + i + "];");
569 println("for (int i = 0; i < len" + i + "; i++) {");
570 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
572 } else if (isList(paramType)) { // A list
573 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
574 println("int paramEnum" + i + "[] = new int[len" + i + "];");
575 println("for (int i = 0; i < len" + i + "; i++) {");
576 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
578 } else { // Just one element
579 println("int paramEnum" + i + "[] = new int[1];");
580 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
588 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
590 private void checkAndWriteEnumRetTypeJavaStub(String retType) {
592 // Strips off array "[]" for return type
593 String pureType = getSimpleArrayType(getGenericType(retType));
594 // Take the inner type of generic
595 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
596 pureType = getGenericType(retType);
597 if (isEnumClass(pureType)) {
598 // Check if this is enum type
600 println("int[] retEnum = (int[]) retObj;");
601 println(pureType + "[] enumVals = " + pureType + ".values();");
602 if (isArray(retType)) { // An array
603 println("int retLen = retEnum.length;");
604 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
605 println("for (int i = 0; i < retLen; i++) {");
606 println("enumRetVal[i] = enumVals[retEnum[i]];");
608 } else if (isList(retType)) { // A list
609 println("int retLen = retEnum.length;");
610 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
611 println("for (int i = 0; i < retLen; i++) {");
612 println("enumRetVal.add(enumVals[retEnum[i]]);");
614 } else { // Just one element
615 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
617 println("return enumRetVal;");
623 * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
625 private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes,
626 InterfaceDecl intDecl, String method) {
628 // Iterate and find struct declarations
629 for (int i = 0; i < methParams.size(); i++) {
630 String paramType = methPrmTypes.get(i);
631 String param = methParams.get(i);
632 String simpleType = getSimpleType(paramType);
633 if (isStructClass(simpleType)) {
634 // Check if this is enum type
635 int methodNumId = intDecl.getMethodNumId(method);
636 String helperMethod = methodNumId + "struct" + i;
637 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
638 println("Class<?> retTypeStruct" + i + " = void.class;");
639 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
640 if (isArray(param)) { // An array
641 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
642 } else if (isList(paramType)) { // A list
643 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
644 } else { // Just one element
645 println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
647 println("rmiCall.remoteCall(objectId, methodIdStruct" + i +
648 ", retTypeStruct" + i + ", null, paramClsStruct" + i +
649 ", paramObjStruct" + i + ");\n");
656 * HELPER: isStructPresent() checks presence of struct
658 private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
660 // Iterate and find enum declarations
661 for (int i = 0; i < methParams.size(); i++) {
662 String paramType = methPrmTypes.get(i);
663 String param = methParams.get(i);
664 String simpleType = getSimpleType(paramType);
665 if (isStructClass(simpleType))
673 * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
675 private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
677 // Iterate and find struct declarations - count number of params
678 for (int i = 0; i < methParams.size(); i++) {
679 String paramType = methPrmTypes.get(i);
680 String param = methParams.get(i);
681 String simpleType = getGenericType(paramType);
682 if (isStructClass(simpleType)) {
683 int members = getNumOfMembers(simpleType);
684 if (isArray(param)) { // An array
685 String structLen = param + ".length";
686 print(members + "*" + structLen);
687 } else if (isList(paramType)) { // A list
688 String structLen = param + ".size()";
689 print(members + "*" + structLen);
691 print(Integer.toString(members));
694 if (i != methParams.size() - 1) {
702 * HELPER: writeStructMembersJavaStub() writes parameters of struct
704 private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
706 // Get the struct declaration for this struct and generate initialization code
707 StructDecl structDecl = getStructDecl(simpleType);
708 List<String> memTypes = structDecl.getMemberTypes(simpleType);
709 List<String> members = structDecl.getMembers(simpleType);
710 if (isArray(param)) { // An array
711 println("for(int i = 0; i < " + param + ".length; i++) {");
712 } else if (isList(paramType)) { // A list
713 println("for(int i = 0; i < " + param + ".size(); i++) {");
715 if (isArrayOrList(param, paramType)) { // An array or list
716 for (int i = 0; i < members.size(); i++) {
717 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
718 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
719 print("paramObj[pos++] = " + param + "[i].");
720 print(getSimpleIdentifier(members.get(i)));
724 } else { // Just one struct element
725 for (int i = 0; i < members.size(); i++) {
726 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
727 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
728 print("paramObj[pos++] = " + param + ".");
729 print(getSimpleIdentifier(members.get(i)));
737 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
739 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
741 print("int paramLen = ");
742 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
744 println("Object[] paramObj = new Object[paramLen];");
745 println("Class<?>[] paramCls = new Class<?>[paramLen];");
746 println("int pos = 0;");
747 // Iterate again over the parameters
748 for (int i = 0; i < methParams.size(); i++) {
749 String paramType = methPrmTypes.get(i);
750 String param = methParams.get(i);
751 String simpleType = getGenericType(paramType);
752 if (isStructClass(simpleType)) {
753 writeStructMembersJavaStub(simpleType, paramType, param);
755 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
756 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
757 print("paramObj[pos++] = ");
758 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
767 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
769 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
771 // Get the struct declaration for this struct and generate initialization code
772 StructDecl structDecl = getStructDecl(simpleType);
773 List<String> memTypes = structDecl.getMemberTypes(simpleType);
774 List<String> members = structDecl.getMembers(simpleType);
775 if (isArrayOrList(retType, retType)) { // An array or list
776 println("for(int i = 0; i < retLen; i++) {");
778 if (isArray(retType)) { // An array
779 for (int i = 0; i < members.size(); i++) {
780 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
781 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
782 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
785 } else if (isList(retType)) { // A list
786 println(simpleType + " structRetMem = new " + simpleType + "();");
787 for (int i = 0; i < members.size(); i++) {
788 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
789 print("structRetMem." + getSimpleIdentifier(members.get(i)));
790 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
792 println("structRet.add(structRetMem);");
794 } else { // Just one struct element
795 for (int i = 0; i < members.size(); i++) {
796 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
797 print("structRet." + getSimpleIdentifier(members.get(i)));
798 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
801 println("return structRet;");
806 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
808 private void writeStructReturnJavaStub(String simpleType, String retType) {
810 // Handle the returned struct!!!
811 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
812 // Minimum retLen is 1 if this is a single struct object
813 println("int retLen = (int) retLenObj;");
814 int numMem = getNumOfMembers(simpleType);
815 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
816 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
817 println("int retPos = 0;");
818 // Get the struct declaration for this struct and generate initialization code
819 StructDecl structDecl = getStructDecl(simpleType);
820 List<String> memTypes = structDecl.getMemberTypes(simpleType);
821 List<String> members = structDecl.getMembers(simpleType);
822 if (isArrayOrList(retType, retType)) { // An array or list
823 println("for(int i = 0; i < retLen; i++) {");
824 for (int i = 0; i < members.size(); i++) {
825 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
826 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
827 println("retClsVal[retPos++] = null;");
830 } else { // Just one struct element
831 for (int i = 0; i < members.size(); i++) {
832 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
833 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
834 println("retClsVal[retPos++] = null;");
837 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
838 if (isArray(retType)) { // An array
839 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
840 println("for(int i = 0; i < retLen; i++) {");
841 println("structRet[i] = new " + simpleType + "();");
843 } else if (isList(retType)) { // A list
844 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
846 println(simpleType + " structRet = new " + simpleType + "();");
847 println("int retObjPos = 0;");
848 writeStructRetMembersJavaStub(simpleType, retType);
853 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
855 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
856 List<String> methPrmTypes, String method) {
858 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
859 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
860 String retType = intDecl.getMethodType(method);
861 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
862 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
863 // Generate array of parameter types
864 if (isStructPresent(methParams, methPrmTypes)) {
865 writeStructParamClassJavaStub(methParams, methPrmTypes);
867 print("Class<?>[] paramCls = new Class<?>[] { ");
868 for (int i = 0; i < methParams.size(); i++) {
869 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
870 print(getSimpleType(getEnumType(paramType)) + ".class");
871 // Check if this is the last element (don't print a comma)
872 if (i != methParams.size() - 1) {
877 // Generate array of parameter objects
878 print("Object[] paramObj = new Object[] { ");
879 for (int i = 0; i < methParams.size(); i++) {
880 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
881 // Check if this is the last element (don't print a comma)
882 if (i != methParams.size() - 1) {
888 // Check if this is "void"
889 if (retType.equals("void")) {
890 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
891 } else { // We do have a return value
892 // Generate array of parameter types
893 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
894 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
896 // This is an enum type
897 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
898 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
899 checkAndWriteEnumRetTypeJavaStub(retType);
900 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
901 // Check if the return value NONPRIMITIVES
902 String retGenValType = getGenericType(retType);
903 println("Class<?> retGenValType = " + retGenValType + ".class;");
904 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
905 println("return (" + retType + ")retObj;");
907 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
908 println("return (" + retType + ")retObj;");
916 * HELPER: returnGenericCallbackType() returns the callback type
918 private String returnGenericCallbackType(String paramType) {
920 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
921 return getTypeOfGeneric(paramType)[0];
928 * HELPER: checkCallbackType() checks the callback type
930 private boolean checkCallbackType(String paramType, String callbackType) {
932 String prmType = returnGenericCallbackType(paramType);
933 return callbackType.equals(prmType);
938 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
940 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
941 List<String> methPrmTypes, String method, String callbackType) {
944 // Check if this is single object, array, or list of objects
945 for (int i = 0; i < methParams.size(); i++) {
946 String paramType = methPrmTypes.get(i);
947 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
948 String param = methParams.get(i);
949 if (isArrayOrList(paramType, param)) { // Generate loop
950 println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
951 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
953 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
954 getSimpleIdentifier(param) + ", objIdCnt++);");
955 println("listCallbackObj.add(skel);");
956 if (isArrayOrList(paramType, param))
961 println(" catch (Exception ex) {");
962 println("ex.printStackTrace();");
963 println("throw new Error(\"Exception when generating skeleton objects!\");");
965 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
966 String retType = intDecl.getMethodType(method);
967 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
968 // Generate array of parameter types
969 print("Class<?>[] paramCls = new Class<?>[] { ");
970 for (int i = 0; i < methParams.size(); i++) {
971 String paramType = methPrmTypes.get(i);
972 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
974 } else { // Generate normal classes if it's not a callback object
975 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
976 print(getSimpleType(prmType) + ".class");
978 if (i != methParams.size() - 1) // Check if this is the last element
982 // Generate array of parameter objects
983 print("Object[] paramObj = new Object[] { ");
984 for (int i = 0; i < methParams.size(); i++) {
985 String paramType = methPrmTypes.get(i);
986 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
987 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
988 if (isArray(methParams.get(i)))
989 print(getSimpleIdentifier(methParams.get(i)) + ".length");
990 else if (isList(methPrmTypes.get(i)))
991 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
993 print("new Integer(1)");
995 print(getSimpleIdentifier(methParams.get(i)));
996 if (i != methParams.size() - 1)
1000 // Check if this is "void"
1001 if (retType.equals("void")) {
1002 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1003 } else { // We do have a return value
1004 // Check if the return value NONPRIMITIVES
1005 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
1006 String[] retGenValType = getTypeOfGeneric(retType);
1007 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
1008 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
1009 println("return (" + retType + ")retObj;");
1011 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1012 println("return (" + retType + ")retObj;");
1019 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1021 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1023 for (String method : methods) {
1025 List<String> methParams = intDecl.getMethodParams(method);
1026 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1027 print("public " + intDecl.getMethodType(method) + " " +
1028 intDecl.getMethodId(method) + "(");
1029 boolean isCallbackMethod = false;
1030 String callbackType = null;
1031 for (int i = 0; i < methParams.size(); i++) {
1033 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1034 // Check if this has callback object
1035 if (callbackClasses.contains(paramType)) {
1036 isCallbackMethod = true;
1037 callbackType = paramType;
1038 // Even if there're 2 callback arguments, we expect them to be of the same interface
1040 print(methPrmTypes.get(i) + " " + methParams.get(i));
1041 // Check if this is the last element (don't print a comma)
1042 if (i != methParams.size() - 1) {
1047 // Now, write the body of stub!
1048 if (isCallbackMethod)
1049 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1051 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1053 // Write the init callback helper method
1054 if (isCallbackMethod)
1055 writeInitCallbackJavaStub(callbackType, intDecl);
1061 * generateJavaStubClasses() generate stubs based on the methods list in Java
1063 public void generateJavaStubClasses() throws IOException {
1065 // Create a new directory
1066 String path = createDirectories(dir, subdir);
1067 for (String intface : mapIntfacePTH.keySet()) {
1069 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1070 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1072 // Open a new file to write into
1073 String newIntface = intMeth.getKey();
1074 String newStubClass = newIntface + "_Stub";
1075 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1076 pw = new PrintWriter(new BufferedWriter(fw));
1077 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1078 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1079 // Pass in set of methods and get import classes
1080 Set<String> methods = intMeth.getValue();
1081 Set<String> importClasses = getImportClasses(methods, intDecl);
1082 List<String> stdImportClasses = getStandardJavaImportClasses();
1083 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1084 printImportStatements(allImportClasses); println("");
1085 // Find out if there are callback objects
1086 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1087 boolean callbackExist = !callbackClasses.isEmpty();
1088 // Write class header
1089 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1091 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1092 // Write constructor
1093 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1095 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1098 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1105 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1107 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1109 println("private IoTRMICall rmiCall;");
1110 println("private String address;");
1111 println("private int[] ports;\n");
1112 // Get the object Id
1113 println("private static int objectId = 0;");
1114 if (callbackExist) {
1115 // We assume that each class only has one callback interface for now
1116 Iterator it = callbackClasses.iterator();
1117 String callbackType = (String) it.next();
1118 println("// Callback properties");
1119 println("private IoTRMIObject rmiObj;");
1120 println("List<" + callbackType + "> listCallbackObj;");
1121 println("private static int objIdCnt = 0;");
1122 // Generate permission stuff for callback stubs
1123 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1124 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1125 writePropertiesJavaPermission(callbackType, intDecl);
1132 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1134 private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1136 // TODO: If we want callback in callback, then we need to add address and port initializations
1137 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1138 println("objectId = _objectId;");
1139 println("rmiCall = _rmiCall;");
1140 if (callbackExist) {
1141 Iterator it = callbackClasses.iterator();
1142 String callbackType = (String) it.next();
1143 writeConstructorJavaPermission(intface);
1144 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1145 println("___initCallBack();");
1146 println("// TODO: Add address and port initialization here if we want callback in callback!");
1153 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1155 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1156 * because all these stubs are populated by the class that takes in this object as a callback
1157 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1159 public void generateJavaCallbackStubClasses() throws IOException {
1161 // Create a new directory
1162 String path = createDirectories(dir, subdir);
1163 for (String intface : mapIntfacePTH.keySet()) {
1165 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1166 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1168 // Open a new file to write into
1169 String newIntface = intMeth.getKey();
1170 String newStubClass = newIntface + "_CallbackStub";
1171 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1172 pw = new PrintWriter(new BufferedWriter(fw));
1173 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1174 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1175 // Pass in set of methods and get import classes
1176 Set<String> methods = intMeth.getValue();
1177 Set<String> importClasses = getImportClasses(methods, intDecl);
1178 List<String> stdImportClasses = getStandardJavaImportClasses();
1179 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1180 printImportStatements(allImportClasses); println("");
1181 // Find out if there are callback objects
1182 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1183 boolean callbackExist = !callbackClasses.isEmpty();
1184 // Write class header
1185 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1187 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1188 // Write constructor
1189 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1191 // TODO: perhaps need to generate callback for callback
1192 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1195 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1202 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1204 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1206 println("private " + intface + " mainObj;");
1207 //println("private int ports;");
1208 println("private IoTRMIObject rmiObj;\n");
1210 if (callbackExist) {
1211 println("private static int objIdCnt = 0;");
1212 println("private IoTRMICall rmiCall;");
1214 writePropertiesJavaPermission(intface, intDecl);
1220 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1222 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1224 // Use this set to handle two same methodIds
1225 for (String method : methods) {
1226 List<String> methParams = intDecl.getMethodParams(method);
1227 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1228 // Check for params with structs
1229 for (int i = 0; i < methParams.size(); i++) {
1230 String paramType = methPrmTypes.get(i);
1231 String param = methParams.get(i);
1232 String simpleType = getSimpleType(paramType);
1233 if (isStructClass(simpleType)) {
1234 int methodNumId = intDecl.getMethodNumId(method);
1235 // Iterate over interfaces to give permissions to
1236 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1237 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1238 String newIntface = intMeth.getKey();
1239 int newObjectId = getNewIntfaceObjectId(newIntface);
1240 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
1249 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1251 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1253 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1254 println("mainObj = _mainObj;");
1255 println("rmiObj = new IoTRMIObject(_port);");
1256 // Generate permission control initialization
1257 writeConstructorJavaPermission(intface);
1258 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1259 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1260 println("___waitRequestInvokeMethod();");
1266 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1268 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1270 if (methodType.equals("void"))
1271 print("mainObj." + methodId + "(");
1273 print("return mainObj." + methodId + "(");
1274 for (int i = 0; i < methParams.size(); i++) {
1276 print(getSimpleIdentifier(methParams.get(i)));
1277 // Check if this is the last element (don't print a comma)
1278 if (i != methParams.size() - 1) {
1287 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1289 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1291 // This is a callback skeleton generation
1292 if (callbackSkeleton)
1293 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1295 println("public void ___regCB() throws IOException {");
1296 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1297 println("\tnew Class<?>[] { null, null, null });");
1298 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1304 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1306 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1307 boolean callbackSkeleton) {
1309 for (String method : methods) {
1311 List<String> methParams = intDecl.getMethodParams(method);
1312 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1313 String methodId = intDecl.getMethodId(method);
1314 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1315 boolean isCallbackMethod = false;
1316 String callbackType = null;
1317 for (int i = 0; i < methParams.size(); i++) {
1319 String origParamType = methPrmTypes.get(i);
1320 String paramType = checkAndGetParamClass(origParamType);
1321 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1322 isCallbackMethod = true;
1323 callbackType = origParamType;
1325 print(paramType + " " + methParams.get(i));
1326 // Check if this is the last element (don't print a comma)
1327 if (i != methParams.size() - 1) {
1332 // Now, write the body of skeleton!
1333 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1335 if (isCallbackMethod)
1336 writeInitCallbackJavaSkeleton(callbackSkeleton);
1342 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1344 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1345 String callbackType) {
1347 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1348 // Iterate over callback objects
1349 for (int i = 0; i < methParams.size(); i++) {
1350 String paramType = methPrmTypes.get(i);
1351 String param = methParams.get(i);
1352 //if (callbackType.equals(paramType)) {
1353 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1355 String exchParamType = checkAndGetParamClass(paramType);
1356 // Print array if this is array or list if this is a list of callback objects
1357 if (isArray(param)) {
1358 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1359 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1360 } else if (isList(paramType)) {
1361 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1362 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1364 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1365 println("objIdCnt++;");
1368 // Generate a loop if needed
1369 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1370 String exchParamType = checkAndGetParamClass(paramType);
1371 if (isArray(param)) {
1372 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1373 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1374 println("objIdCnt++;");
1376 } else if (isList(paramType)) {
1377 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1378 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1379 println("objIdCnt++;");
1382 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1385 return mapStubParam;
1390 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1392 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1394 // Iterate and find enum declarations
1395 for (int i = 0; i < methParams.size(); i++) {
1396 String paramType = methPrmTypes.get(i);
1397 String param = methParams.get(i);
1398 String simpleType = getGenericType(paramType);
1399 if (isEnumClass(simpleType)) {
1400 // Check if this is enum type
1401 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1402 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1403 if (isArray(param)) { // An array
1404 println("int len" + i + " = paramInt" + i + ".length;");
1405 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1406 println("for (int i = 0; i < len" + i + "; i++) {");
1407 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1409 } else if (isList(paramType)) { // A list
1410 println("int len" + i + " = paramInt" + i + ".length;");
1411 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1412 println("for (int i = 0; i < len" + i + "; i++) {");
1413 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1415 } else { // Just one element
1416 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1424 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1426 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1428 // Strips off array "[]" for return type
1429 String pureType = getSimpleArrayType(getGenericType(retType));
1430 // Take the inner type of generic
1431 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1432 pureType = getGenericType(retType);
1433 if (isEnumClass(pureType)) {
1434 // Check if this is enum type
1436 if (isArray(retType)) { // An array
1437 print(pureType + "[] retEnum = " + methodId + "(");
1438 } else if (isList(retType)) { // A list
1439 print("List<" + pureType + "> retEnum = " + methodId + "(");
1440 } else { // Just one element
1441 print(pureType + " retEnum = " + methodId + "(");
1448 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1450 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1452 // Strips off array "[]" for return type
1453 String pureType = getSimpleArrayType(getGenericType(retType));
1454 // Take the inner type of generic
1455 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1456 pureType = getGenericType(retType);
1457 if (isEnumClass(pureType)) {
1458 // Check if this is enum type
1459 if (isArray(retType)) { // An array
1460 println("int retLen = retEnum.length;");
1461 println("int[] retEnumVal = new int[retLen];");
1462 println("for (int i = 0; i < retLen; i++) {");
1463 println("retEnumVal[i] = retEnum[i].ordinal();");
1465 } else if (isList(retType)) { // A list
1466 println("int retLen = retEnum.size();");
1467 println("int[] retEnumVal = new int[retLen];");
1468 println("for (int i = 0; i < retLen; i++) {");
1469 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1471 } else { // Just one element
1472 println("int[] retEnumVal = new int[1];");
1473 println("retEnumVal[0] = retEnum.ordinal();");
1475 println("Object retObj = retEnumVal;");
1481 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1483 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1484 String method, InterfaceDecl intDecl) {
1486 // Iterate and find struct declarations - count number of params
1487 for (int i = 0; i < methParams.size(); i++) {
1488 String paramType = methPrmTypes.get(i);
1489 String param = methParams.get(i);
1490 String simpleType = getGenericType(paramType);
1491 if (isStructClass(simpleType)) {
1492 int members = getNumOfMembers(simpleType);
1493 print(Integer.toString(members) + "*");
1494 int methodNumId = intDecl.getMethodNumId(method);
1495 print("struct" + methodNumId + "Size" + i);
1498 if (i != methParams.size() - 1) {
1506 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1508 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1509 String param, String method, InterfaceDecl intDecl, int iVar) {
1511 // Get the struct declaration for this struct and generate initialization code
1512 StructDecl structDecl = getStructDecl(simpleType);
1513 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1514 List<String> members = structDecl.getMembers(simpleType);
1515 if (isArrayOrList(param, paramType)) { // An array or list
1516 int methodNumId = intDecl.getMethodNumId(method);
1517 String counter = "struct" + methodNumId + "Size" + iVar;
1518 println("for(int i = 0; i < " + counter + "; i++) {");
1520 println("int pos = 0;");
1521 if (isArrayOrList(param, paramType)) { // An array or list
1522 println("for(int i = 0; i < retLen; i++) {");
1523 for (int i = 0; i < members.size(); i++) {
1524 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1525 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1526 println("paramClsGen[pos++] = null;");
1529 } else { // Just one struct element
1530 for (int i = 0; i < members.size(); i++) {
1531 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1532 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1533 println("paramClsGen[pos++] = null;");
1540 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1542 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1543 List<String> methPrmTypes, String method) {
1545 for (int i = 0; i < methParams.size(); i++) {
1546 String paramType = methPrmTypes.get(i);
1547 String param = methParams.get(i);
1548 String simpleType = getGenericType(paramType);
1549 if (isStructClass(simpleType)) {
1550 int methodNumId = intDecl.getMethodNumId(method);
1551 String counter = "struct" + methodNumId + "Size" + i;
1553 if (isArray(param)) { // An array
1554 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1555 println("for(int i = 0; i < " + counter + "; i++) {");
1556 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1558 } else if (isList(paramType)) { // A list
1559 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1561 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1562 println("int objPos = 0;");
1563 // Initialize members
1564 StructDecl structDecl = getStructDecl(simpleType);
1565 List<String> members = structDecl.getMembers(simpleType);
1566 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1567 if (isArrayOrList(param, paramType)) { // An array or list
1568 println("for(int i = 0; i < " + counter + "; i++) {");
1570 if (isArray(param)) { // An array
1571 for (int j = 0; j < members.size(); j++) {
1572 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1573 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1574 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1577 } else if (isList(paramType)) { // A list
1578 println(simpleType + " paramStructMem = new " + simpleType + "();");
1579 for (int j = 0; j < members.size(); j++) {
1580 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1581 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1582 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1584 println("paramStruct" + i + ".add(paramStructMem);");
1586 } else { // Just one struct element
1587 for (int j = 0; j < members.size(); j++) {
1588 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1589 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1590 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1594 // Take offsets of parameters
1595 println("int offset" + i +" = objPos;");
1602 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1604 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1606 // Minimum retLen is 1 if this is a single struct object
1607 if (isArray(retType))
1608 println("int retLen = retStruct.length;");
1609 else if (isList(retType))
1610 println("int retLen = retStruct.size();");
1611 else // Just single struct object
1612 println("int retLen = 1;");
1613 println("Object retLenObj = retLen;");
1614 println("rmiObj.sendReturnObj(retLenObj);");
1615 int numMem = getNumOfMembers(simpleType);
1616 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1617 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1618 println("int retPos = 0;");
1619 // Get the struct declaration for this struct and generate initialization code
1620 StructDecl structDecl = getStructDecl(simpleType);
1621 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1622 List<String> members = structDecl.getMembers(simpleType);
1623 if (isArrayOrList(retType, retType)) { // An array or list
1624 println("for(int i = 0; i < retLen; i++) {");
1625 for (int i = 0; i < members.size(); i++) {
1626 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1627 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1628 print("retObj[retPos++] = retStruct[i].");
1629 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1633 } else { // Just one struct element
1634 for (int i = 0; i < members.size(); i++) {
1635 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1636 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1637 print("retObj[retPos++] = retStruct.");
1638 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1647 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1649 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1650 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1651 boolean isStructMethod) {
1653 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1654 Map<Integer,String> mapStubParam = null;
1655 if (isCallbackMethod)
1656 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1657 // Check if this is "void"
1658 String retType = intDecl.getMethodType(method);
1659 if (retType.equals("void")) {
1660 print(intDecl.getMethodId(method) + "(");
1661 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1662 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1663 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1664 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1665 } else { // We do have a return value
1666 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1668 for (int i = 0; i < methParams.size(); i++) {
1670 if (isCallbackMethod) {
1671 print(mapStubParam.get(i)); // Get the callback parameter
1672 } else if (isEnumClass(getGenericType(methPrmTypes.get(i)))) { // Enum class
1673 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1674 } else if (isStructClass(getGenericType(methPrmTypes.get(i)))) {
1675 print("paramStruct" + i);
1677 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1679 print("(" + prmType + ") paramObj[offset" + i + "]");
1681 print("(" + prmType + ") paramObj[" + i + "]");
1683 if (i != methParams.size() - 1)
1687 if (!retType.equals("void")) {
1688 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1689 checkAndWriteEnumRetConvJavaSkeleton(retType);
1690 println("rmiObj.sendReturnObj(retObj);");
1691 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1692 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1693 println("rmiObj.sendReturnObj(retCls, retObj);");
1695 println("rmiObj.sendReturnObj(retObj);");
1697 if (isCallbackMethod) { // Catch exception if this is callback
1699 println(" catch(Exception ex) {");
1700 println("ex.printStackTrace();");
1701 println("throw new Error(\"Exception from callback object instantiation!\");");
1708 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1710 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1711 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1713 // Generate array of parameter objects
1714 boolean isCallbackMethod = false;
1715 String callbackType = null;
1716 print("int paramLen = ");
1717 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1719 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1720 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1721 // Iterate again over the parameters
1722 for (int i = 0; i < methParams.size(); i++) {
1723 String paramType = methPrmTypes.get(i);
1724 String param = methParams.get(i);
1725 String simpleType = getGenericType(paramType);
1726 if (isStructClass(simpleType)) {
1727 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1729 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1730 if (callbackClasses.contains(prmType)) {
1731 isCallbackMethod = true;
1732 callbackType = prmType;
1733 println("paramCls[pos] = int.class;");
1734 println("paramClsGen[pos++] = null;");
1735 } else { // Generate normal classes if it's not a callback object
1736 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1737 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1738 print("paramClsGen[pos++] = ");
1739 String prmTypeOth = methPrmTypes.get(i);
1740 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1741 println(getTypeOfGeneric(prmType)[0] + ".class;");
1747 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1748 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1749 // Write the return value part
1750 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1755 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1757 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1758 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1760 // Generate array of parameter objects
1761 boolean isCallbackMethod = false;
1762 String callbackType = null;
1763 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1764 for (int i = 0; i < methParams.size(); i++) {
1766 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1767 if (callbackClasses.contains(paramType)) {
1768 isCallbackMethod = true;
1769 callbackType = paramType;
1771 } else { // Generate normal classes if it's not a callback object
1772 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1773 print(getSimpleType(getEnumType(prmType)) + ".class");
1775 if (i != methParams.size() - 1)
1779 // Generate generic class if it's a generic type.. null otherwise
1780 print("new Class<?>[] { ");
1781 for (int i = 0; i < methParams.size(); i++) {
1782 String prmType = methPrmTypes.get(i);
1783 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1784 !isEnumClass(getGenericType(prmType)))
1785 print(getGenericType(prmType) + ".class");
1788 if (i != methParams.size() - 1)
1792 // Write the return value part
1793 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1798 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1800 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1802 // Use this set to handle two same methodIds
1803 Set<String> uniqueMethodIds = new HashSet<String>();
1804 for (String method : methods) {
1806 List<String> methParams = intDecl.getMethodParams(method);
1807 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1808 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1809 String methodId = intDecl.getMethodId(method);
1810 print("public void ___");
1811 String helperMethod = methodId;
1812 if (uniqueMethodIds.contains(methodId))
1813 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1815 uniqueMethodIds.add(methodId);
1816 String retType = intDecl.getMethodType(method);
1817 print(helperMethod + "(");
1818 boolean begin = true;
1819 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1820 String paramType = methPrmTypes.get(i);
1821 String param = methParams.get(i);
1822 String simpleType = getSimpleType(paramType);
1823 if (isStructClass(simpleType)) {
1824 if (!begin) { // Generate comma for not the beginning variable
1825 print(", "); begin = false;
1827 int methodNumId = intDecl.getMethodNumId(method);
1828 print("int struct" + methodNumId + "Size" + i);
1831 // Check if this is "void"
1832 if (retType.equals("void"))
1835 println(") throws IOException {");
1836 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1839 String methodId = intDecl.getMethodId(method);
1840 print("public void ___");
1841 String helperMethod = methodId;
1842 if (uniqueMethodIds.contains(methodId))
1843 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1845 uniqueMethodIds.add(methodId);
1846 // Check if this is "void"
1847 String retType = intDecl.getMethodType(method);
1848 if (retType.equals("void"))
1849 println(helperMethod + "() {");
1851 println(helperMethod + "() throws IOException {");
1852 // Now, write the helper body of skeleton!
1853 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1857 // Write method helper for structs
1858 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1863 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1865 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1866 InterfaceDecl intDecl) {
1868 // Use this set to handle two same methodIds
1869 for (String method : methods) {
1871 List<String> methParams = intDecl.getMethodParams(method);
1872 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1873 // Check for params with structs
1874 for (int i = 0; i < methParams.size(); i++) {
1875 String paramType = methPrmTypes.get(i);
1876 String param = methParams.get(i);
1877 String simpleType = getSimpleType(paramType);
1878 if (isStructClass(simpleType)) {
1879 int methodNumId = intDecl.getMethodNumId(method);
1880 print("public int ___");
1881 String helperMethod = methodNumId + "struct" + i;
1882 println(helperMethod + "() {");
1883 // Now, write the helper body of skeleton!
1884 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1885 println("return (int) paramObj[0];");
1894 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1896 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1897 InterfaceDecl intDecl) {
1899 // Use this set to handle two same methodIds
1900 for (String method : methods) {
1902 List<String> methParams = intDecl.getMethodParams(method);
1903 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1904 // Check for params with structs
1905 for (int i = 0; i < methParams.size(); i++) {
1906 String paramType = methPrmTypes.get(i);
1907 String param = methParams.get(i);
1908 String simpleType = getSimpleType(paramType);
1909 if (isStructClass(simpleType)) {
1910 int methodNumId = intDecl.getMethodNumId(method);
1911 print("public int ___");
1912 String helperMethod = methodNumId + "struct" + i;
1913 println(helperMethod + "(IoTRMIObject rmiObj) {");
1914 // Now, write the helper body of skeleton!
1915 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1916 println("return (int) paramObj[0];");
1925 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1927 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1929 // Use this set to handle two same methodIds
1930 for (String method : methods) {
1932 List<String> methParams = intDecl.getMethodParams(method);
1933 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1934 // Check for params with structs
1935 for (int i = 0; i < methParams.size(); i++) {
1936 String paramType = methPrmTypes.get(i);
1937 String param = methParams.get(i);
1938 String simpleType = getSimpleType(paramType);
1939 if (isStructClass(simpleType)) {
1940 int methodNumId = intDecl.getMethodNumId(method);
1941 println("int struct" + methodNumId + "Size" + i + " = 0;");
1949 * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1951 private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1953 List<String> methParams = intDecl.getMethodParams(method);
1954 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1955 boolean structExist = false;
1956 // Check for params with structs
1957 for (int i = 0; i < methParams.size(); i++) {
1958 String paramType = methPrmTypes.get(i);
1959 String param = methParams.get(i);
1960 String simpleType = getSimpleType(paramType);
1961 boolean begin = true;
1962 if (isStructClass(simpleType)) {
1965 print(", "); begin = false;
1967 int methodNumId = intDecl.getMethodNumId(method);
1968 print("struct" + methodNumId + "Size" + i);
1976 * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1978 private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1980 // Use this set to handle two same methodIds
1981 for (String method : methods) {
1983 List<String> methParams = intDecl.getMethodParams(method);
1984 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1985 // Check for params with structs
1986 for (int i = 0; i < methParams.size(); i++) {
1987 String paramType = methPrmTypes.get(i);
1988 String param = methParams.get(i);
1989 String simpleType = getSimpleType(paramType);
1990 if (isStructClass(simpleType)) {
1991 int methodNumId = intDecl.getMethodNumId(method);
1993 String helperMethod = methodNumId + "struct" + i;
1994 String tempVar = "struct" + methodNumId + "Size" + i;
1995 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1996 print(tempVar + " = ___");
1997 println(helperMethod + "(); break;");
2005 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2007 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2009 // Use this set to handle two same methodIds
2010 for (String method : methods) {
2012 List<String> methParams = intDecl.getMethodParams(method);
2013 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2014 // Check for params with structs
2015 for (int i = 0; i < methParams.size(); i++) {
2016 String paramType = methPrmTypes.get(i);
2017 String param = methParams.get(i);
2018 String simpleType = getSimpleType(paramType);
2019 if (isStructClass(simpleType)) {
2020 int methodNumId = intDecl.getMethodNumId(method);
2022 String helperMethod = methodNumId + "struct" + i;
2023 String tempVar = "struct" + methodNumId + "Size" + i;
2024 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2025 print(tempVar + " = ___");
2026 println(helperMethod + "(rmiObj); break;");
2034 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2036 private void writeJavaMethodPermission(String intface) {
2038 // Get all the different stubs
2039 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2040 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2041 String newIntface = intMeth.getKey();
2042 int newObjectId = getNewIntfaceObjectId(newIntface);
2043 println("if (_objectId == object" + newObjectId + "Id) {");
2044 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2045 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2049 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2056 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2058 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2060 // Use this set to handle two same methodIds
2061 Set<String> uniqueMethodIds = new HashSet<String>();
2062 println("private void ___waitRequestInvokeMethod() throws IOException {");
2063 // Write variables here if we have callbacks or enums or structs
2064 writeCountVarStructSkeleton(methods, intDecl);
2065 println("while (true) {");
2066 println("rmiObj.getMethodBytes();");
2067 println("int _objectId = rmiObj.getObjectId();");
2068 println("int methodId = rmiObj.getMethodId();");
2069 // Generate permission check
2070 writeJavaMethodPermission(intface);
2071 println("switch (methodId) {");
2072 // Print methods and method Ids
2073 for (String method : methods) {
2074 String methodId = intDecl.getMethodId(method);
2075 int methodNumId = intDecl.getMethodNumId(method);
2076 print("case " + methodNumId + ": ___");
2077 String helperMethod = methodId;
2078 if (uniqueMethodIds.contains(methodId))
2079 helperMethod = helperMethod + methodNumId;
2081 uniqueMethodIds.add(methodId);
2082 print(helperMethod + "(");
2083 writeInputCountVarStructSkeleton(method, intDecl);
2084 println("); break;");
2086 String method = "___initCallBack()";
2087 // Print case -9999 (callback handler) if callback exists
2088 if (callbackExist) {
2089 int methodId = intDecl.getHelperMethodNumId(method);
2090 println("case " + methodId + ": ___regCB(); break;");
2092 writeMethodCallStructSkeleton(methods, intDecl);
2093 println("default: ");
2094 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2102 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2104 public void generateJavaSkeletonClass() throws IOException {
2106 // Create a new directory
2107 String path = createDirectories(dir, subdir);
2108 for (String intface : mapIntfacePTH.keySet()) {
2109 // Open a new file to write into
2110 String newSkelClass = intface + "_Skeleton";
2111 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2112 pw = new PrintWriter(new BufferedWriter(fw));
2113 // Pass in set of methods and get import classes
2114 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2115 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2116 List<String> methods = intDecl.getMethods();
2117 Set<String> importClasses = getImportClasses(methods, intDecl);
2118 List<String> stdImportClasses = getStandardJavaImportClasses();
2119 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2120 printImportStatements(allImportClasses);
2121 // Find out if there are callback objects
2122 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2123 boolean callbackExist = !callbackClasses.isEmpty();
2124 // Write class header
2126 println("public class " + newSkelClass + " implements " + intface + " {\n");
2128 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2129 // Write constructor
2130 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2132 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2133 // Write method helper
2134 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2135 // Write waitRequestInvokeMethod() - main loop
2136 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2139 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2145 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2147 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2149 println("private " + intface + " mainObj;");
2150 // For callback skeletons, this is its own object Id
2151 println("private static int objectId = 0;");
2153 if (callbackExist) {
2154 println("private static int objIdCnt = 0;");
2155 println("private IoTRMICall rmiCall;");
2162 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2164 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2166 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2167 println("mainObj = _mainObj;");
2168 println("objectId = _objectId;");
2169 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
2175 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2177 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2179 // Use this set to handle two same methodIds
2180 Set<String> uniqueMethodIds = new HashSet<String>();
2181 for (String method : methods) {
2183 List<String> methParams = intDecl.getMethodParams(method);
2184 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2185 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
2186 String methodId = intDecl.getMethodId(method);
2187 print("public void ___");
2188 String helperMethod = methodId;
2189 if (uniqueMethodIds.contains(methodId))
2190 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2192 uniqueMethodIds.add(methodId);
2193 String retType = intDecl.getMethodType(method);
2194 print(helperMethod + "(");
2195 boolean begin = true;
2196 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2197 String paramType = methPrmTypes.get(i);
2198 String param = methParams.get(i);
2199 String simpleType = getSimpleType(paramType);
2200 if (isStructClass(simpleType)) {
2201 if (!begin) { // Generate comma for not the beginning variable
2202 print(", "); begin = false;
2204 int methodNumId = intDecl.getMethodNumId(method);
2205 print("int struct" + methodNumId + "Size" + i);
2208 // Check if this is "void"
2209 if (retType.equals("void"))
2210 println(", IoTRMIObject rmiObj) {");
2212 println(", IoTRMIObject rmiObj) throws IOException {");
2213 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2216 String methodId = intDecl.getMethodId(method);
2217 print("public void ___");
2218 String helperMethod = methodId;
2219 if (uniqueMethodIds.contains(methodId))
2220 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2222 uniqueMethodIds.add(methodId);
2223 // Check if this is "void"
2224 String retType = intDecl.getMethodType(method);
2225 if (retType.equals("void"))
2226 println(helperMethod + "(IoTRMIObject rmiObj) {");
2228 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2229 // Now, write the helper body of skeleton!
2230 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2234 // Write method helper for structs
2235 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2240 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2242 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2244 // Use this set to handle two same methodIds
2245 Set<String> uniqueMethodIds = new HashSet<String>();
2246 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2247 // Write variables here if we have callbacks or enums or structs
2248 writeCountVarStructSkeleton(methods, intDecl);
2249 // Write variables here if we have callbacks or enums or structs
2250 println("int methodId = rmiObj.getMethodId();");
2251 // TODO: code the permission check here!
2252 println("switch (methodId) {");
2253 // Print methods and method Ids
2254 for (String method : methods) {
2255 String methodId = intDecl.getMethodId(method);
2256 int methodNumId = intDecl.getMethodNumId(method);
2257 print("case " + methodNumId + ": ___");
2258 String helperMethod = methodId;
2259 if (uniqueMethodIds.contains(methodId))
2260 helperMethod = helperMethod + methodNumId;
2262 uniqueMethodIds.add(methodId);
2263 print(helperMethod + "(");
2264 if (writeInputCountVarStructSkeleton(method, intDecl))
2265 println(", rmiObj); break;");
2267 println("rmiObj); break;");
2269 String method = "___initCallBack()";
2270 // Print case -9999 (callback handler) if callback exists
2271 if (callbackExist) {
2272 int methodId = intDecl.getHelperMethodNumId(method);
2273 println("case " + methodId + ": ___regCB(rmiObj); break;");
2275 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2276 println("default: ");
2277 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2284 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2286 public void generateJavaCallbackSkeletonClass() throws IOException {
2288 // Create a new directory
2289 String path = createDirectories(dir, subdir);
2290 for (String intface : mapIntfacePTH.keySet()) {
2291 // Open a new file to write into
2292 String newSkelClass = intface + "_CallbackSkeleton";
2293 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2294 pw = new PrintWriter(new BufferedWriter(fw));
2295 // Pass in set of methods and get import classes
2296 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2297 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2298 List<String> methods = intDecl.getMethods();
2299 Set<String> importClasses = getImportClasses(methods, intDecl);
2300 List<String> stdImportClasses = getStandardJavaImportClasses();
2301 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2302 printImportStatements(allImportClasses);
2303 // Find out if there are callback objects
2304 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2305 boolean callbackExist = !callbackClasses.isEmpty();
2306 // Write class header
2308 println("public class " + newSkelClass + " implements " + intface + " {\n");
2310 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2311 // Write constructor
2312 writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2314 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2315 // Write method helper
2316 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2317 // Write waitRequestInvokeMethod() - main loop
2318 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2321 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2327 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2329 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2331 for (String method : methods) {
2333 List<String> methParams = intDecl.getMethodParams(method);
2334 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2335 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2336 intDecl.getMethodId(method) + "(");
2337 for (int i = 0; i < methParams.size(); i++) {
2338 // Check for params with driver class types and exchange it
2339 // with its remote interface
2340 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2341 paramType = checkAndGetCplusType(paramType);
2342 // Check for arrays - translate into vector in C++
2343 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2344 print(paramComplete);
2345 // Check if this is the last element (don't print a comma)
2346 if (i != methParams.size() - 1) {
2356 * HELPER: writeMethodCplusInterface() writes the method of the interface
2358 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2360 for (String method : methods) {
2362 List<String> methParams = intDecl.getMethodParams(method);
2363 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2364 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2365 intDecl.getMethodId(method) + "(");
2366 for (int i = 0; i < methParams.size(); i++) {
2367 // Check for params with driver class types and exchange it
2368 // with its remote interface
2369 String paramType = methPrmTypes.get(i);
2370 paramType = checkAndGetCplusType(paramType);
2371 // Check for arrays - translate into vector in C++
2372 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2373 print(paramComplete);
2374 // Check if this is the last element (don't print a comma)
2375 if (i != methParams.size() - 1) {
2385 * HELPER: generateEnumCplus() writes the enumeration declaration
2387 public void generateEnumCplus() throws IOException {
2389 // Create a new directory
2390 createDirectory(dir);
2391 for (String intface : mapIntfacePTH.keySet()) {
2392 // Get the right StructDecl
2393 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2394 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2395 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2396 // Iterate over enum declarations
2397 for (String enType : enumTypes) {
2398 // Open a new file to write into
2399 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2400 pw = new PrintWriter(new BufferedWriter(fw));
2401 // Write file headers
2402 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2403 println("#define _" + enType.toUpperCase() + "_HPP__");
2404 println("enum " + enType + " {");
2405 List<String> enumMembers = enumDecl.getMembers(enType);
2406 for (int i = 0; i < enumMembers.size(); i++) {
2408 String member = enumMembers.get(i);
2410 // Check if this is the last element (don't print a comma)
2411 if (i != enumMembers.size() - 1)
2419 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2426 * HELPER: generateStructCplus() writes the struct declaration
2428 public void generateStructCplus() throws IOException {
2430 // Create a new directory
2431 createDirectory(dir);
2432 for (String intface : mapIntfacePTH.keySet()) {
2433 // Get the right StructDecl
2434 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2435 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2436 List<String> structTypes = structDecl.getStructTypes();
2437 // Iterate over enum declarations
2438 for (String stType : structTypes) {
2439 // Open a new file to write into
2440 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2441 pw = new PrintWriter(new BufferedWriter(fw));
2442 // Write file headers
2443 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2444 println("#define _" + stType.toUpperCase() + "_HPP__");
2445 println("struct " + stType + " {");
2446 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2447 List<String> structMembers = structDecl.getMembers(stType);
2448 for (int i = 0; i < structMembers.size(); i++) {
2450 String memberType = structMemberTypes.get(i);
2451 String member = structMembers.get(i);
2452 String structTypeC = checkAndGetCplusType(memberType);
2453 String structComplete = checkAndGetCplusArray(structTypeC, member);
2454 println(structComplete + ";");
2459 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2466 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2468 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2469 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2470 * The local interface has to be the input parameter for the stub and the stub
2471 * interface has to be the input parameter for the local class.
2473 public void generateCplusLocalInterfaces() throws IOException {
2475 // Create a new directory
2476 createDirectory(dir);
2477 for (String intface : mapIntfacePTH.keySet()) {
2478 // Open a new file to write into
2479 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2480 pw = new PrintWriter(new BufferedWriter(fw));
2481 // Write file headers
2482 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2483 println("#define _" + intface.toUpperCase() + "_HPP__");
2484 println("#include <iostream>");
2485 // Pass in set of methods and get include classes
2486 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2487 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2488 List<String> methods = intDecl.getMethods();
2489 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2490 printIncludeStatements(includeClasses); println("");
2491 println("using namespace std;\n");
2492 //writeStructCplus(structDecl);
2493 println("class " + intface); println("{");
2496 writeMethodCplusLocalInterface(methods, intDecl);
2500 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2506 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2508 * For C++ we use virtual classe as interface
2510 public void generateCPlusInterfaces() throws IOException {
2512 // Create a new directory
2513 String path = createDirectories(dir, subdir);
2514 for (String intface : mapIntfacePTH.keySet()) {
2516 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2517 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2519 // Open a new file to write into
2520 String newIntface = intMeth.getKey();
2521 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2522 pw = new PrintWriter(new BufferedWriter(fw));
2523 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2524 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2525 // Write file headers
2526 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2527 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2528 println("#include <iostream>");
2529 // Pass in set of methods and get import classes
2530 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2531 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2532 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2533 printIncludeStatements(allIncludeClasses); println("");
2534 println("using namespace std;\n");
2535 println("class " + newIntface);
2539 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2543 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2550 * HELPER: writeMethodCplusStub() writes the methods of the stub
2552 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2554 for (String method : methods) {
2556 List<String> methParams = intDecl.getMethodParams(method);
2557 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2558 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2559 intDecl.getMethodId(method) + "(");
2560 boolean isCallbackMethod = false;
2561 String callbackType = null;
2562 for (int i = 0; i < methParams.size(); i++) {
2564 String paramType = methPrmTypes.get(i);
2565 // Check if this has callback object
2566 if (callbackClasses.contains(paramType)) {
2567 isCallbackMethod = true;
2568 callbackType = paramType;
2569 // Even if there're 2 callback arguments, we expect them to be of the same interface
2571 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2572 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2573 print(methParamComplete);
2574 // Check if this is the last element (don't print a comma)
2575 if (i != methParams.size() - 1) {
2580 if (isCallbackMethod)
2581 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2583 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2585 // Write the init callback helper method
2586 if (isCallbackMethod) {
2587 writeInitCallbackCplusStub(callbackType, intDecl);
2588 writeInitCallbackSendInfoCplusStub(intDecl);
2595 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2597 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2598 List<String> methPrmTypes, String method, String callbackType) {
2600 // Check if this is single object, array, or list of objects
2601 boolean isArrayOrList = false;
2602 String callbackParam = null;
2603 for (int i = 0; i < methParams.size(); i++) {
2605 String paramType = methPrmTypes.get(i);
2606 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2607 String param = methParams.get(i);
2608 if (isArrayOrList(paramType, param)) { // Generate loop
2609 println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2610 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2611 isArrayOrList = true;
2612 callbackParam = getSimpleIdentifier(param);
2614 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2615 getSimpleIdentifier(param) + ", objIdCnt++);");
2616 println("vecCallbackObj.push_back(skel);");
2617 if (isArrayOrList(paramType, param))
2621 println("int numParam = " + methParams.size() + ";");
2622 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2623 String retType = intDecl.getMethodType(method);
2624 //String retTypeC = checkAndGetCplusType(retType);
2625 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2626 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2627 // Generate array of parameter types
2628 print("string paramCls[] = { ");
2629 for (int i = 0; i < methParams.size(); i++) {
2630 String paramType = methPrmTypes.get(i);
2631 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2633 } else { // Generate normal classes if it's not a callback object
2634 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2635 print("\"" + paramTypeC + "\"");
2637 if (i != methParams.size() - 1) // Check if this is the last element
2641 print("int ___paramCB = ");
2643 println(callbackParam + ".size();");
2646 // Generate array of parameter objects
2647 print("void* paramObj[] = { ");
2648 for (int i = 0; i < methParams.size(); i++) {
2649 String paramType = methPrmTypes.get(i);
2650 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2651 print("&___paramCB");
2653 print(getSimpleIdentifier(methParams.get(i)));
2654 if (i != methParams.size() - 1)
2658 // Check if this is "void"
2659 if (retType.equals("void")) {
2660 println("void* retObj = NULL;");
2661 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2662 } else { // We do have a return value
2663 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2664 println(checkAndGetCplusType(retType) + " retVal;");
2666 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2667 println("void* retObj = &retVal;");
2668 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2669 println("return retVal;");
2675 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2677 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2679 // Iterate and find enum declarations
2680 for (int i = 0; i < methParams.size(); i++) {
2681 String paramType = methPrmTypes.get(i);
2682 String param = methParams.get(i);
2683 if (isEnumClass(getGenericType(paramType))) {
2684 // Check if this is enum type
2685 if (isArrayOrList(paramType, param)) { // An array or vector
2686 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2687 println("vector<int> paramEnum" + i + "(len" + i + ");");
2688 println("for (int i = 0; i < len" + i + "; i++) {");
2689 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2691 } else { // Just one element
2692 println("vector<int> paramEnum" + i + "(1);");
2693 println("paramEnum" + i + "[0] = (int) " + param + ";");
2701 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2703 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2705 // Strips off array "[]" for return type
2706 String pureType = getSimpleArrayType(getGenericType(retType));
2707 // Take the inner type of generic
2708 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2709 pureType = getGenericType(retType);
2710 if (isEnumClass(pureType)) {
2711 // Check if this is enum type
2712 println("vector<int> retEnumInt;");
2713 println("void* retObj = &retEnumInt;");
2714 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2715 if (isArrayOrList(retType, retType)) { // An array or vector
2716 println("int retLen = retEnumInt.size();");
2717 println("vector<" + pureType + "> retVal(retLen);");
2718 println("for (int i = 0; i < retLen; i++) {");
2719 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2721 } else { // Just one element
2722 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2724 println("return retVal;");
2730 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2732 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2733 InterfaceDecl intDecl, String method) {
2735 // Iterate and find struct declarations
2736 for (int i = 0; i < methParams.size(); i++) {
2737 String paramType = methPrmTypes.get(i);
2738 String param = methParams.get(i);
2739 String simpleType = getSimpleType(paramType);
2740 if (isStructClass(simpleType)) {
2741 // Check if this is enum type
2742 println("int numParam" + i + " = 1;");
2743 int methodNumId = intDecl.getMethodNumId(method);
2744 String helperMethod = methodNumId + "struct" + i;
2745 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2746 println("string retTypeStruct" + i + " = \"void\";");
2747 println("string paramClsStruct" + i + "[] = { \"int\" };");
2748 print("int structLen" + i + " = ");
2749 if (isArrayOrList(param, paramType)) { // An array
2750 println(getSimpleArrayType(param) + ".size();");
2751 } else { // Just one element
2754 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2755 println("void* retStructLen" + i + " = NULL;");
2756 println("rmiCall->remoteCall(objectId, methodIdStruct" + i +
2757 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i +
2758 ", numParam" + i + ", retStructLen" + i + ");\n");
2765 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2767 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2769 // Iterate and find struct declarations - count number of params
2770 for (int i = 0; i < methParams.size(); i++) {
2771 String paramType = methPrmTypes.get(i);
2772 String param = methParams.get(i);
2773 String simpleType = getGenericType(paramType);
2774 if (isStructClass(simpleType)) {
2775 int members = getNumOfMembers(simpleType);
2776 if (isArrayOrList(param, paramType)) { // An array
2777 String structLen = param + ".size()";
2778 print(members + "*" + structLen);
2780 print(Integer.toString(members));
2783 if (i != methParams.size() - 1) {
2791 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2793 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2795 // Get the struct declaration for this struct and generate initialization code
2796 StructDecl structDecl = getStructDecl(simpleType);
2797 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2798 List<String> members = structDecl.getMembers(simpleType);
2799 if (isArrayOrList(param, paramType)) { // An array or list
2800 println("for(int i = 0; i < " + param + ".size(); i++) {");
2802 if (isArrayOrList(param, paramType)) { // An array or list
2803 for (int i = 0; i < members.size(); i++) {
2804 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2805 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2806 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2807 print("paramObj[pos++] = &" + param + "[i].");
2808 print(getSimpleIdentifier(members.get(i)));
2812 } else { // Just one struct element
2813 for (int i = 0; i < members.size(); i++) {
2814 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2815 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2816 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2817 print("paramObj[pos++] = &" + param + ".");
2818 print(getSimpleIdentifier(members.get(i)));
2826 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2828 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2830 print("int numParam = ");
2831 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2833 println("void* paramObj[numParam];");
2834 println("string paramCls[numParam];");
2835 println("int pos = 0;");
2836 // Iterate again over the parameters
2837 for (int i = 0; i < methParams.size(); i++) {
2838 String paramType = methPrmTypes.get(i);
2839 String param = methParams.get(i);
2840 String simpleType = getGenericType(paramType);
2841 if (isStructClass(simpleType)) {
2842 writeStructMembersCplusStub(simpleType, paramType, param);
2844 String prmTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2845 String prmType = checkAndGetCplusArrayType(prmTypeC, methParams.get(i));
2846 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2847 print("paramObj[pos++] = &");
2848 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2857 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2859 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2861 // Get the struct declaration for this struct and generate initialization code
2862 StructDecl structDecl = getStructDecl(simpleType);
2863 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2864 List<String> members = structDecl.getMembers(simpleType);
2865 if (isArrayOrList(retType, retType)) { // An array or list
2866 println("for(int i = 0; i < retLen; i++) {");
2868 if (isArrayOrList(retType, retType)) { // An array or list
2869 for (int i = 0; i < members.size(); i++) {
2870 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2871 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2872 println(" = retParam" + i + "[i];");
2875 } else { // Just one struct element
2876 for (int i = 0; i < members.size(); i++) {
2877 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2878 print("structRet." + getSimpleIdentifier(members.get(i)));
2879 println(" = retParam" + i + ";");
2882 println("return structRet;");
2887 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2889 private void writeStructReturnCplusStub(String simpleType, String retType) {
2891 // Minimum retLen is 1 if this is a single struct object
2892 println("int retLen = 0;");
2893 println("void* retLenObj = { &retLen };");
2894 // Handle the returned struct!!!
2895 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2896 int numMem = getNumOfMembers(simpleType);
2897 println("int numRet = " + numMem + "*retLen;");
2898 println("string retCls[numRet];");
2899 println("void* retObj[numRet];");
2900 StructDecl structDecl = getStructDecl(simpleType);
2901 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2902 List<String> members = structDecl.getMembers(simpleType);
2904 if (isArrayOrList(retType, retType)) { // An array or list
2905 for (int i = 0; i < members.size(); i++) {
2906 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2907 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2908 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2910 } else { // Just one struct element
2911 for (int i = 0; i < members.size(); i++) {
2912 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2913 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2914 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2917 println("int retPos = 0;");
2918 // Get the struct declaration for this struct and generate initialization code
2919 if (isArrayOrList(retType, retType)) { // An array or list
2920 println("for(int i = 0; i < retLen; i++) {");
2921 for (int i = 0; i < members.size(); i++) {
2922 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2923 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2924 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2925 println("retObj[retPos++] = &retParam" + i + "[i];");
2928 } else { // Just one struct element
2929 for (int i = 0; i < members.size(); i++) {
2930 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2931 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2932 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2933 println("retObj[retPos++] = &retParam" + i + ";");
2936 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2937 if (isArrayOrList(retType, retType)) { // An array or list
2938 println("vector<" + simpleType + "> structRet(retLen);");
2940 println(simpleType + " structRet;");
2941 writeStructRetMembersCplusStub(simpleType, retType);
2946 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2948 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2949 List<String> methPrmTypes, String method) {
2951 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2952 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2953 String retType = intDecl.getMethodType(method);
2954 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2955 // Generate array of parameter types
2956 if (isStructPresent(methParams, methPrmTypes)) {
2957 writeStructParamClassCplusStub(methParams, methPrmTypes);
2959 println("int numParam = " + methParams.size() + ";");
2960 print("string paramCls[] = { ");
2961 for (int i = 0; i < methParams.size(); i++) {
2962 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2963 print("\"" + paramTypeC + "\"");
2964 // Check if this is the last element (don't print a comma)
2965 if (i != methParams.size() - 1) {
2970 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2971 // Generate array of parameter objects
2972 print("void* paramObj[] = { ");
2973 for (int i = 0; i < methParams.size(); i++) {
2974 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2975 // Check if this is the last element (don't print a comma)
2976 if (i != methParams.size() - 1) {
2982 // Check if this is "void"
2983 if (retType.equals("void")) {
2984 println("void* retObj = NULL;");
2985 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2986 } else { // We do have a return value
2987 // Generate array of parameter types
2988 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
2989 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
2991 // Check if the return value NONPRIMITIVES
2992 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
2993 checkAndWriteEnumRetTypeCplusStub(retType);
2995 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2996 if (isArrayOrList(retType,retType))
2997 println(checkAndGetCplusType(retType) + " retVal;");
2999 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3001 println("void* retObj = &retVal;");
3002 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3003 println("return retVal;");
3011 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3013 private void writePropertiesCplusPermission(String intface) {
3015 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3016 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3017 String newIntface = intMeth.getKey();
3018 int newObjectId = getNewIntfaceObjectId(newIntface);
3019 println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3020 println("static set<int> set" + newObjectId + "Allowed;");
3025 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3027 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3029 println("IoTRMICall *rmiCall;");
3030 //println("IoTRMIObject\t\t\t*rmiObj;");
3031 println("string address;");
3032 println("vector<int> ports;\n");
3033 // Get the object Id
3034 Integer objId = mapIntfaceObjId.get(intface);
3035 println("const static int objectId = " + objId + ";");
3036 mapNewIntfaceObjId.put(newIntface, objId);
3037 mapIntfaceObjId.put(intface, objId++);
3038 if (callbackExist) {
3039 // We assume that each class only has one callback interface for now
3040 Iterator it = callbackClasses.iterator();
3041 String callbackType = (String) it.next();
3042 println("// Callback properties");
3043 println("IoTRMIObject *rmiObj;");
3044 println("vector<" + callbackType + "*> vecCallbackObj;");
3045 println("static int objIdCnt;");
3046 // Generate permission stuff for callback stubs
3047 writePropertiesCplusPermission(callbackType);
3054 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3056 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3058 println(newStubClass +
3059 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3060 println("address = _address;");
3061 println("ports = _ports;");
3062 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3063 if (callbackExist) {
3064 Iterator it = callbackClasses.iterator();
3065 String callbackType = (String) it.next();
3066 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3067 println("th1.detach();");
3068 println("___regCB();");
3075 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3077 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3079 println("~" + newStubClass + "() {");
3080 println("if (rmiCall != NULL) {");
3081 println("delete rmiCall;");
3082 println("rmiCall = NULL;");
3084 if (callbackExist) {
3085 // We assume that each class only has one callback interface for now
3086 println("if (rmiObj != NULL) {");
3087 println("delete rmiObj;");
3088 println("rmiObj = NULL;");
3090 Iterator it = callbackClasses.iterator();
3091 String callbackType = (String) it.next();
3092 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3093 println("delete cb;");
3094 println("cb = NULL;");
3103 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3105 private void writeCplusMethodCallbackPermission(String intface) {
3107 println("int methodId = IoTRMIObject::getMethodId(method);");
3108 // Get all the different stubs
3109 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3110 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3111 String newIntface = intMeth.getKey();
3112 int newObjectId = getNewIntfaceObjectId(newIntface);
3113 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3114 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3115 println("exit(-1);");
3122 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3124 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3126 println("void ___initCallBack() {");
3127 println("bool bResult = false;");
3128 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3129 println("while (true) {");
3130 println("char* method = rmiObj->getMethodBytes();");
3131 writeCplusMethodCallbackPermission(intface);
3132 println("int objId = IoTRMIObject::getObjectId(method);");
3133 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
3134 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
3135 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3136 println("skel->invokeMethod(rmiObj);");
3139 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3140 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3141 println("exit(-1);");
3149 * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3151 private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl) {
3153 String method = "___initCallBack()";
3154 int methodNumId = intDecl.getHelperMethodNumId(method);
3155 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3156 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3157 String newIntface = intMeth.getKey();
3158 int newObjectId = getNewIntfaceObjectId(newIntface);
3159 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3165 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3167 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3169 // Generate info sending part
3170 println("void ___regCB() {");
3171 println("int numParam = 3;");
3172 String method = "___initCallBack()";
3173 int methodNumId = intDecl.getHelperMethodNumId(method);
3174 println("int methodId = " + methodNumId + ";");
3175 //writeCplusCallbackPermission(intface, methodNumId);
3176 println("string retType = \"void\";");
3177 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3178 println("int rev = 0;");
3179 println("void* paramObj[] = { &ports[0], &address, &rev };");
3180 println("void* retObj = NULL;");
3181 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3187 * generateCPlusStubClasses() generate stubs based on the methods list in C++
3189 public void generateCPlusStubClasses() throws IOException {
3191 // Create a new directory
3192 String path = createDirectories(dir, subdir);
3193 for (String intface : mapIntfacePTH.keySet()) {
3195 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3196 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3197 // Open a new file to write into
3198 String newIntface = intMeth.getKey();
3199 String newStubClass = newIntface + "_Stub";
3200 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3201 pw = new PrintWriter(new BufferedWriter(fw));
3202 // Write file headers
3203 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3204 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3205 println("#include <iostream>");
3206 // Find out if there are callback objects
3207 Set<String> methods = intMeth.getValue();
3208 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3209 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3210 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3211 boolean callbackExist = !callbackClasses.isEmpty();
3212 if (callbackExist) // Need thread library if this has callback
3213 println("#include <thread>");
3214 println("#include \"" + newIntface + ".hpp\""); println("");
3215 println("using namespace std;"); println("");
3216 println("class " + newStubClass + " : public " + newIntface); println("{");
3217 println("private:\n");
3218 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3219 println("public:\n");
3220 // Add default constructor and destructor
3221 println(newStubClass + "() { }"); println("");
3222 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3223 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3225 writeMethodCplusStub(methods, intDecl, callbackClasses);
3226 print("}"); println(";");
3228 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3229 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3232 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3239 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3241 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3243 println("IoTRMICall *rmiCall;");
3244 // Get the object Id
3245 println("int objectId;");
3246 if (callbackExist) {
3247 // We assume that each class only has one callback interface for now
3248 Iterator it = callbackClasses.iterator();
3249 String callbackType = (String) it.next();
3250 println("// Callback properties");
3251 println("IoTRMIObject *rmiObj;");
3252 println("vector<" + callbackType + "*> vecCallbackObj;");
3253 println("static int objIdCnt;");
3254 // TODO: Need to initialize address and ports if we want to have callback-in-callback
3255 println("string address;");
3256 println("vector<int> ports;\n");
3257 writePropertiesCplusPermission(callbackType);
3264 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3266 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3268 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3269 println("objectId = _objectId;");
3270 println("rmiCall = _rmiCall;");
3271 if (callbackExist) {
3272 Iterator it = callbackClasses.iterator();
3273 String callbackType = (String) it.next();
3274 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3275 println("th1.detach();");
3276 println("___regCB();");
3283 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3285 public void generateCPlusCallbackStubClasses() throws IOException {
3287 // Create a new directory
3288 String path = createDirectories(dir, subdir);
3289 for (String intface : mapIntfacePTH.keySet()) {
3291 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3292 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3293 // Open a new file to write into
3294 String newIntface = intMeth.getKey();
3295 String newStubClass = newIntface + "_CallbackStub";
3296 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3297 pw = new PrintWriter(new BufferedWriter(fw));
3298 // Find out if there are callback objects
3299 Set<String> methods = intMeth.getValue();
3300 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3301 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3302 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3303 boolean callbackExist = !callbackClasses.isEmpty();
3304 // Write file headers
3305 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3306 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3307 println("#include <iostream>");
3309 println("#include <thread>");
3310 println("#include \"" + newIntface + ".hpp\""); println("");
3311 println("using namespace std;"); println("");
3312 println("class " + newStubClass + " : public " + newIntface); println("{");
3313 println("private:\n");
3314 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3315 println("public:\n");
3316 // Add default constructor and destructor
3317 println(newStubClass + "() { }"); println("");
3318 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3319 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3321 writeMethodCplusStub(methods, intDecl, callbackClasses);
3324 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3325 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3328 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3335 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3337 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3339 println(intface + " *mainObj;");
3341 if (callbackExist) {
3342 Iterator it = callbackClasses.iterator();
3343 String callbackType = (String) it.next();
3344 String exchangeType = checkAndGetParamClass(callbackType);
3345 println("// Callback properties");
3346 println("static int objIdCnt;");
3347 println("vector<" + exchangeType + "*> vecCallbackObj;");
3348 println("IoTRMICall *rmiCall;");
3350 println("IoTRMIObject *rmiObj;\n");
3351 // Keep track of object Ids of all stubs registered to this interface
3352 writePropertiesCplusPermission(intface);
3358 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3360 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3363 println("int " + newSkelClass + "::objIdCnt = 0;");
3368 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3370 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3372 // Keep track of object Ids of all stubs registered to this interface
3373 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3374 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3375 String newIntface = intMeth.getKey();
3376 int newObjectId = getNewIntfaceObjectId(newIntface);
3377 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
3378 Set<String> methodIds = intMeth.getValue();
3380 for (String methodId : methodIds) {
3381 int methodNumId = intDecl.getMethodNumId(methodId);
3382 print(Integer.toString(methodNumId));
3383 // Check if this is the last element (don't print a comma)
3384 if (i != methodIds.size() - 1) {
3395 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3397 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3399 // Use this set to handle two same methodIds
3400 for (String method : methods) {
3401 List<String> methParams = intDecl.getMethodParams(method);
3402 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3403 // Check for params with structs
3404 for (int i = 0; i < methParams.size(); i++) {
3405 String paramType = methPrmTypes.get(i);
3406 String param = methParams.get(i);
3407 String simpleType = getSimpleType(paramType);
3408 if (isStructClass(simpleType)) {
3409 int methodNumId = intDecl.getMethodNumId(method);
3410 // Iterate over interfaces to give permissions to
3411 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3412 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3413 String newIntface = intMeth.getKey();
3414 int newObjectId = getNewIntfaceObjectId(newIntface);
3415 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3424 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3426 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3428 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3429 println("bool _bResult = false;");
3430 println("mainObj = _mainObj;");
3431 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3432 writeCplusInitCallbackPermission(intface, intDecl);
3433 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3434 println("___waitRequestInvokeMethod();");
3440 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3442 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3444 println("~" + newSkelClass + "() {");
3445 println("if (rmiObj != NULL) {");
3446 println("delete rmiObj;");
3447 println("rmiObj = NULL;");
3449 if (callbackExist) {
3450 // We assume that each class only has one callback interface for now
3451 println("if (rmiCall != NULL) {");
3452 println("delete rmiCall;");
3453 println("rmiCall = NULL;");
3455 Iterator it = callbackClasses.iterator();
3456 String callbackType = (String) it.next();
3457 String exchangeType = checkAndGetParamClass(callbackType);
3458 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3459 println("delete cb;");
3460 println("cb = NULL;");
3469 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3471 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3473 if (methodType.equals("void"))
3474 print("mainObj->" + methodId + "(");
3476 print("return mainObj->" + methodId + "(");
3477 for (int i = 0; i < methParams.size(); i++) {
3479 print(getSimpleIdentifier(methParams.get(i)));
3480 // Check if this is the last element (don't print a comma)
3481 if (i != methParams.size() - 1) {
3490 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3492 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3494 // This is a callback skeleton generation
3495 if (callbackSkeleton)
3496 println("void ___regCB(IoTRMIObject* rmiObj) {");
3498 println("void ___regCB() {");
3499 println("int numParam = 3;");
3500 println("int param1 = 0;");
3501 println("string param2 = \"\";");
3502 println("int param3 = 0;");
3503 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3504 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
3505 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3506 println("bool bResult = false;");
3507 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3513 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3515 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3516 Set<String> callbackClasses, boolean callbackSkeleton) {
3518 for (String method : methods) {
3520 List<String> methParams = intDecl.getMethodParams(method);
3521 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3522 String methodId = intDecl.getMethodId(method);
3523 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3524 print(methodType + " " + methodId + "(");
3525 boolean isCallbackMethod = false;
3526 String callbackType = null;
3527 for (int i = 0; i < methParams.size(); i++) {
3529 String origParamType = methPrmTypes.get(i);
3530 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3531 isCallbackMethod = true;
3532 callbackType = origParamType;
3534 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3535 String methPrmType = checkAndGetCplusType(paramType);
3536 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3537 print(methParamComplete);
3538 // Check if this is the last element (don't print a comma)
3539 if (i != methParams.size() - 1) {
3544 // Now, write the body of skeleton!
3545 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3547 if (isCallbackMethod)
3548 writeInitCallbackCplusSkeleton(callbackSkeleton);
3554 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3556 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3558 for (int i = 0; i < methParams.size(); i++) {
3559 String paramType = methPrmTypes.get(i);
3560 String param = methParams.get(i);
3561 //if (callbackType.equals(paramType)) {
3562 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3563 String exchParamType = checkAndGetParamClass(paramType);
3564 // Print array if this is array or list if this is a list of callback objects
3565 println("int numStubs" + i + " = 0;");
3572 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3574 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3576 // Iterate over callback objects
3577 for (int i = 0; i < methParams.size(); i++) {
3578 String paramType = methPrmTypes.get(i);
3579 String param = methParams.get(i);
3580 // Generate a loop if needed
3581 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3582 String exchParamType = checkAndGetParamClass(paramType);
3583 if (isArrayOrList(paramType, param)) {
3584 println("vector<" + exchParamType + "> stub;");
3585 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3586 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3587 println("stub" + i + ".push_back(cb);");
3588 println("vecCallbackObj.push_back(cb);");
3589 println("objIdCnt++;");
3592 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3593 println("vecCallbackObj.push_back(stub" + i + ");");
3594 println("objIdCnt++;");
3602 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3604 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3606 // Iterate and find enum declarations
3607 for (int i = 0; i < methParams.size(); i++) {
3608 String paramType = methPrmTypes.get(i);
3609 String param = methParams.get(i);
3610 String simpleType = getGenericType(paramType);
3611 if (isEnumClass(simpleType)) {
3612 // Check if this is enum type
3613 if (isArrayOrList(paramType, param)) { // An array
3614 println("int len" + i + " = paramEnumInt" + i + ".size();");
3615 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3616 println("for (int i=0; i < len" + i + "; i++) {");
3617 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3619 } else { // Just one element
3620 println(simpleType + " paramEnum" + i + ";");
3621 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3629 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3631 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3633 // Strips off array "[]" for return type
3634 String pureType = getSimpleArrayType(getGenericType(retType));
3635 // Take the inner type of generic
3636 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3637 pureType = getTypeOfGeneric(retType)[0];
3638 if (isEnumClass(pureType)) {
3639 // Check if this is enum type
3641 if (isArrayOrList(retType, retType)) { // An array
3642 println("int retLen = retEnum.size();");
3643 println("vector<int> retEnumInt(retLen);");
3644 println("for (int i=0; i < retLen; i++) {");
3645 println("retEnumInt[i] = (int) retEnum[i];");
3647 } else { // Just one element
3648 println("vector<int> retEnumInt(1);");
3649 println("retEnumInt[0] = (int) retEnum;");
3656 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3658 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3659 Set<String> callbackClasses, String methodId) {
3661 print(methodId + "(");
3662 for (int i = 0; i < methParams.size(); i++) {
3663 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3664 if (callbackClasses.contains(paramType))
3666 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3667 print("paramEnum" + i);
3668 else if (isStructClass(getGenericType(paramType))) // Struct type
3669 print("paramStruct" + i);
3671 print(getSimpleIdentifier(methParams.get(i)));
3672 if (i != methParams.size() - 1) {
3681 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3683 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3684 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3685 String methodId, Set<String> callbackClasses) {
3687 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3688 if (isCallbackMethod)
3689 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3690 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3691 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3692 // Check if this is "void"
3693 String retType = intDecl.getMethodType(method);
3694 // Check if this is "void"
3695 if (retType.equals("void")) {
3696 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3697 } else { // We do have a return value
3698 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3699 print(checkAndGetCplusType(retType) + " retEnum = ");
3700 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3701 print(checkAndGetCplusType(retType) + " retStruct = ");
3703 print(checkAndGetCplusType(retType) + " retVal = ");
3704 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3705 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3706 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3707 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3708 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3709 println("void* retObj = &retEnumInt;");
3711 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3712 println("void* retObj = &retVal;");
3713 String retTypeC = checkAndGetCplusType(retType);
3714 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3715 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3717 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3723 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3725 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3726 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3728 // Generate array of parameter types
3729 boolean isCallbackMethod = false;
3730 String callbackType = null;
3731 print("string paramCls[] = { ");
3732 for (int i = 0; i < methParams.size(); i++) {
3733 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3734 if (callbackClasses.contains(paramType)) {
3735 isCallbackMethod = true;
3736 callbackType = paramType;
3738 } else { // Generate normal classes if it's not a callback object
3739 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3740 print("\"" + paramTypeC + "\"");
3742 if (i != methParams.size() - 1) {
3747 println("int numParam = " + methParams.size() + ";");
3748 if (isCallbackMethod)
3749 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3750 // Generate parameters
3751 for (int i = 0; i < methParams.size(); i++) {
3752 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3753 if (!callbackClasses.contains(paramType)) {
3754 String methParamType = methPrmTypes.get(i);
3755 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3756 // Check if this is enum type
3757 println("vector<int> paramEnumInt" + i + ";");
3759 String methPrmType = checkAndGetCplusType(methParamType);
3760 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3761 println(methParamComplete + ";");
3765 // Generate array of parameter objects
3766 print("void* paramObj[] = { ");
3767 for (int i = 0; i < methParams.size(); i++) {
3768 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3769 if (callbackClasses.contains(paramType))
3770 print("&numStubs" + i);
3771 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3772 print("¶mEnumInt" + i);
3774 print("&" + getSimpleIdentifier(methParams.get(i)));
3775 if (i != methParams.size() - 1) {
3780 // Write the return value part
3781 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3782 callbackType, methodId, callbackClasses);
3787 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3789 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3790 String param, String method, InterfaceDecl intDecl, int iVar) {
3792 // Get the struct declaration for this struct and generate initialization code
3793 StructDecl structDecl = getStructDecl(simpleType);
3794 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3795 List<String> members = structDecl.getMembers(simpleType);
3796 int methodNumId = intDecl.getMethodNumId(method);
3797 String counter = "struct" + methodNumId + "Size" + iVar;
3798 if (isArrayOrList(param, paramType)) { // An array or list
3799 println("for(int i = 0; i < " + counter + "; i++) {");
3802 if (isArrayOrList(param, paramType)) { // An array or list
3803 for (int i = 0; i < members.size(); i++) {
3804 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3805 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3806 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
3808 } else { // Just one struct element
3809 for (int i = 0; i < members.size(); i++) {
3810 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3811 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3812 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
3815 println("int pos = 0;");
3816 if (isArrayOrList(param, paramType)) { // An array or list
3817 println("for(int i = 0; i < retLen; i++) {");
3818 for (int i = 0; i < members.size(); i++) {
3819 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3820 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3821 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3822 println("paramObj[pos++] = ¶m" + i + "[i];");
3825 } else { // Just one struct element
3826 for (int i = 0; i < members.size(); i++) {
3827 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3828 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3829 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3830 println("paramObj[pos++] = ¶m" + i + ";");
3837 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3839 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3840 List<String> methPrmTypes, String method) {
3842 for (int i = 0; i < methParams.size(); i++) {
3843 String paramType = methPrmTypes.get(i);
3844 String param = methParams.get(i);
3845 String simpleType = getGenericType(paramType);
3846 if (isStructClass(simpleType)) {
3847 int methodNumId = intDecl.getMethodNumId(method);
3848 String counter = "struct" + methodNumId + "Size" + i;
3850 if (isArrayOrList(param, paramType)) { // An array or list
3851 println("vector<" + simpleType + "> paramStruct" + i + ";");
3853 println(simpleType + " paramStruct" + i + ";");
3854 // Initialize members
3855 StructDecl structDecl = getStructDecl(simpleType);
3856 List<String> members = structDecl.getMembers(simpleType);
3857 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3858 if (isArrayOrList(param, paramType)) { // An array or list
3859 println("for(int i = 0; i < " + counter + "; i++) {");
3860 for (int j = 0; j < members.size(); j++) {
3861 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3862 println(" = param" + j + "[i];");
3865 } else { // Just one struct element
3866 for (int j = 0; j < members.size(); j++) {
3867 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3868 println(" = param" + j + ";");
3877 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3879 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3881 // Minimum retLen is 1 if this is a single struct object
3882 if (isArrayOrList(retType, retType))
3883 println("int retLen = retStruct.size();");
3884 else // Just single struct object
3885 println("int retLen = 1;");
3886 println("void* retLenObj = &retLen;");
3887 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3888 int numMem = getNumOfMembers(simpleType);
3889 println("int numRetObj = " + numMem + "*retLen;");
3890 println("string retCls[numRetObj];");
3891 println("void* retObj[numRetObj];");
3892 println("int retPos = 0;");
3893 // Get the struct declaration for this struct and generate initialization code
3894 StructDecl structDecl = getStructDecl(simpleType);
3895 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3896 List<String> members = structDecl.getMembers(simpleType);
3897 if (isArrayOrList(retType, retType)) { // An array or list
3898 println("for(int i = 0; i < retLen; i++) {");
3899 for (int i = 0; i < members.size(); i++) {
3900 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3901 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3902 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3903 print("retObj[retPos++] = &retStruct[i].");
3904 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3908 } else { // Just one struct element
3909 for (int i = 0; i < members.size(); i++) {
3910 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3911 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3912 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3913 print("retObj[retPos++] = &retStruct.");
3914 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3923 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3925 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3926 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3928 // Generate array of parameter objects
3929 boolean isCallbackMethod = false;
3930 String callbackType = null;
3931 print("int numParam = ");
3932 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3934 println("string paramCls[numParam];");
3935 println("void* paramObj[numParam];");
3936 // Iterate again over the parameters
3937 for (int i = 0; i < methParams.size(); i++) {
3938 String paramType = methPrmTypes.get(i);
3939 String param = methParams.get(i);
3940 String simpleType = getGenericType(paramType);
3941 if (isStructClass(simpleType)) {
3942 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3944 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3945 if (callbackClasses.contains(prmType)) {
3946 isCallbackMethod = true;
3947 callbackType = paramType;
3948 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3949 println("paramCls[pos] = \"int\";");
3950 println("paramObj[pos++] = &numStubs" + i + ";");
3951 } else { // Generate normal classes if it's not a callback object
3952 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3953 String prmTypeC = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
3954 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3955 println("vector<int> paramEnumInt" + i + ";");
3957 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3958 println(methParamComplete + ";");
3960 println("paramCls[pos] = \"" + getEnumType(prmTypeC) + "\";");
3961 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3962 println("paramObj[pos++] = ¶mEnumInt" + i);
3964 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3968 // Write the return value part
3969 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3970 callbackType, methodId, callbackClasses);
3975 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3977 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3979 // Use this set to handle two same methodIds
3980 Set<String> uniqueMethodIds = new HashSet<String>();
3981 for (String method : methods) {
3983 List<String> methParams = intDecl.getMethodParams(method);
3984 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3985 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
3986 String methodId = intDecl.getMethodId(method);
3988 String helperMethod = methodId;
3989 if (uniqueMethodIds.contains(methodId))
3990 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3992 uniqueMethodIds.add(methodId);
3993 String retType = intDecl.getMethodType(method);
3994 print(helperMethod + "(");
3995 boolean begin = true;
3996 for (int i = 0; i < methParams.size(); i++) { // Print size variables
3997 String paramType = methPrmTypes.get(i);
3998 String param = methParams.get(i);
3999 String simpleType = getSimpleType(paramType);
4000 if (isStructClass(simpleType)) {
4001 if (!begin) { // Generate comma for not the beginning variable
4002 print(", "); begin = false;
4004 int methodNumId = intDecl.getMethodNumId(method);
4005 print("int struct" + methodNumId + "Size" + i);
4009 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4012 String methodId = intDecl.getMethodId(method);
4014 String helperMethod = methodId;
4015 if (uniqueMethodIds.contains(methodId))
4016 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4018 uniqueMethodIds.add(methodId);
4019 // Check if this is "void"
4020 String retType = intDecl.getMethodType(method);
4021 println(helperMethod + "() {");
4022 // Now, write the helper body of skeleton!
4023 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4027 // Write method helper for structs
4028 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4033 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4035 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4036 InterfaceDecl intDecl) {
4038 // Use this set to handle two same methodIds
4039 for (String method : methods) {
4041 List<String> methParams = intDecl.getMethodParams(method);
4042 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4043 // Check for params with structs
4044 for (int i = 0; i < methParams.size(); i++) {
4045 String paramType = methPrmTypes.get(i);
4046 String param = methParams.get(i);
4047 String simpleType = getSimpleType(paramType);
4048 if (isStructClass(simpleType)) {
4049 int methodNumId = intDecl.getMethodNumId(method);
4051 String helperMethod = methodNumId + "struct" + i;
4052 println(helperMethod + "() {");
4053 // Now, write the helper body of skeleton!
4054 println("string paramCls[] = { \"int\" };");
4055 println("int numParam = 1;");
4056 println("int param0 = 0;");
4057 println("void* paramObj[] = { ¶m0 };");
4058 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4059 println("return param0;");
4068 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4070 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4071 InterfaceDecl intDecl) {
4073 // Use this set to handle two same methodIds
4074 for (String method : methods) {
4076 List<String> methParams = intDecl.getMethodParams(method);
4077 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4078 // Check for params with structs
4079 for (int i = 0; i < methParams.size(); i++) {
4080 String paramType = methPrmTypes.get(i);
4081 String param = methParams.get(i);
4082 String simpleType = getSimpleType(paramType);
4083 if (isStructClass(simpleType)) {
4084 int methodNumId = intDecl.getMethodNumId(method);
4086 String helperMethod = methodNumId + "struct" + i;
4087 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4088 // Now, write the helper body of skeleton!
4089 println("string paramCls[] = { \"int\" };");
4090 println("int numParam = 1;");
4091 println("int param0 = 0;");
4092 println("void* paramObj[] = { ¶m0 };");
4093 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4094 println("return param0;");
4103 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4105 private void writeCplusMethodPermission(String intface) {
4107 // Get all the different stubs
4108 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4109 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4110 String newIntface = intMeth.getKey();
4111 int newObjectId = getNewIntfaceObjectId(newIntface);
4112 println("if (_objectId == object" + newObjectId + "Id) {");
4113 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4114 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4115 println("exit(-1);");
4119 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4120 println("exit(-1);");
4127 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4129 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4131 // Use this set to handle two same methodIds
4132 Set<String> uniqueMethodIds = new HashSet<String>();
4133 println("void ___waitRequestInvokeMethod() {");
4134 // Write variables here if we have callbacks or enums or structs
4135 writeCountVarStructSkeleton(methods, intDecl);
4136 println("while (true) {");
4137 println("rmiObj->getMethodBytes();");
4138 println("int _objectId = rmiObj->getObjectId();");
4139 println("int methodId = rmiObj->getMethodId();");
4140 // Generate permission check
4141 writeCplusMethodPermission(intface);
4142 println("switch (methodId) {");
4143 // Print methods and method Ids
4144 for (String method : methods) {
4145 String methodId = intDecl.getMethodId(method);
4146 int methodNumId = intDecl.getMethodNumId(method);
4147 print("case " + methodNumId + ": ___");
4148 String helperMethod = methodId;
4149 if (uniqueMethodIds.contains(methodId))
4150 helperMethod = helperMethod + methodNumId;
4152 uniqueMethodIds.add(methodId);
4153 print(helperMethod + "(");
4154 writeInputCountVarStructSkeleton(method, intDecl);
4155 println("); break;");
4157 String method = "___initCallBack()";
4158 // Print case -9999 (callback handler) if callback exists
4159 if (callbackExist) {
4160 int methodId = intDecl.getHelperMethodNumId(method);
4161 println("case " + methodId + ": ___regCB(); break;");
4163 writeMethodCallStructSkeleton(methods, intDecl);
4164 println("default: ");
4165 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4166 println("throw exception();");
4174 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4176 public void generateCplusSkeletonClass() throws IOException {
4178 // Create a new directory
4179 String path = createDirectories(dir, subdir);
4180 for (String intface : mapIntfacePTH.keySet()) {
4181 // Open a new file to write into
4182 String newSkelClass = intface + "_Skeleton";
4183 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4184 pw = new PrintWriter(new BufferedWriter(fw));
4185 // Write file headers
4186 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4187 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4188 println("#include <iostream>");
4189 println("#include \"" + intface + ".hpp\"\n");
4190 // Pass in set of methods and get import classes
4191 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4192 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4193 List<String> methods = intDecl.getMethods();
4194 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4195 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4196 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4197 printIncludeStatements(allIncludeClasses); println("");
4198 println("using namespace std;\n");
4199 // Find out if there are callback objects
4200 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4201 boolean callbackExist = !callbackClasses.isEmpty();
4202 // Write class header
4203 println("class " + newSkelClass + " : public " + intface); println("{");
4204 println("private:\n");
4206 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4207 println("public:\n");
4208 // Write constructor
4209 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4210 // Write deconstructor
4211 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4213 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4214 // Write method helper
4215 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4216 // Write waitRequestInvokeMethod() - main loop
4217 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4219 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4220 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4223 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4229 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4231 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4233 println(intface + " *mainObj;");
4234 // Keep track of object Ids of all stubs registered to this interface
4235 println("int objectId;");
4237 if (callbackExist) {
4238 Iterator it = callbackClasses.iterator();
4239 String callbackType = (String) it.next();
4240 String exchangeType = checkAndGetParamClass(callbackType);
4241 println("// Callback properties");
4242 println("IoTRMICall* rmiCall;");
4243 println("vector<" + exchangeType + "*> vecCallbackObj;");
4244 println("static int objIdCnt;");
4251 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4253 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4255 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4256 println("mainObj = _mainObj;");
4257 println("objectId = _objectId;");
4258 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
4264 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4266 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
4267 Set<String> callbackClasses) {
4269 println("~" + newStubClass + "() {");
4270 if (callbackExist) {
4271 // We assume that each class only has one callback interface for now
4272 println("if (rmiCall != NULL) {");
4273 println("delete rmiCall;");
4274 println("rmiCall = NULL;");
4276 Iterator it = callbackClasses.iterator();
4277 String callbackType = (String) it.next();
4278 String exchangeType = checkAndGetParamClass(callbackType);
4279 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4280 println("delete cb;");
4281 println("cb = NULL;");
4290 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4292 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4293 Set<String> callbackClasses) {
4295 // Use this set to handle two same methodIds
4296 Set<String> uniqueMethodIds = new HashSet<String>();
4297 for (String method : methods) {
4299 List<String> methParams = intDecl.getMethodParams(method);
4300 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4301 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4302 String methodId = intDecl.getMethodId(method);
4304 String helperMethod = methodId;
4305 if (uniqueMethodIds.contains(methodId))
4306 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4308 uniqueMethodIds.add(methodId);
4309 String retType = intDecl.getMethodType(method);
4310 print(helperMethod + "(");
4311 boolean begin = true;
4312 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4313 String paramType = methPrmTypes.get(i);
4314 String param = methParams.get(i);
4315 String simpleType = getSimpleType(paramType);
4316 if (isStructClass(simpleType)) {
4317 if (!begin) { // Generate comma for not the beginning variable
4318 print(", "); begin = false;
4320 int methodNumId = intDecl.getMethodNumId(method);
4321 print("int struct" + methodNumId + "Size" + i);
4324 println(", IoTRMIObject* rmiObj) {");
4325 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4328 String methodId = intDecl.getMethodId(method);
4330 String helperMethod = methodId;
4331 if (uniqueMethodIds.contains(methodId))
4332 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4334 uniqueMethodIds.add(methodId);
4335 // Check if this is "void"
4336 String retType = intDecl.getMethodType(method);
4337 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4338 // Now, write the helper body of skeleton!
4339 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4343 // Write method helper for structs
4344 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4349 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4351 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4352 boolean callbackExist) {
4354 // Use this set to handle two same methodIds
4355 Set<String> uniqueMethodIds = new HashSet<String>();
4356 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4357 // Write variables here if we have callbacks or enums or structs
4358 writeCountVarStructSkeleton(methods, intDecl);
4359 // Write variables here if we have callbacks or enums or structs
4360 println("int methodId = rmiObj->getMethodId();");
4361 // TODO: code the permission check here!
4362 println("switch (methodId) {");
4363 // Print methods and method Ids
4364 for (String method : methods) {
4365 String methodId = intDecl.getMethodId(method);
4366 int methodNumId = intDecl.getMethodNumId(method);
4367 print("case " + methodNumId + ": ___");
4368 String helperMethod = methodId;
4369 if (uniqueMethodIds.contains(methodId))
4370 helperMethod = helperMethod + methodNumId;
4372 uniqueMethodIds.add(methodId);
4373 print(helperMethod + "(");
4374 if (writeInputCountVarStructSkeleton(method, intDecl))
4375 println(", rmiObj); break;");
4377 println("rmiObj); break;");
4379 String method = "___initCallBack()";
4380 // Print case -9999 (callback handler) if callback exists
4381 if (callbackExist) {
4382 int methodId = intDecl.getHelperMethodNumId(method);
4383 println("case " + methodId + ": ___regCB(rmiObj); break;");
4385 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4386 println("default: ");
4387 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4388 println("throw exception();");
4395 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4397 public void generateCplusCallbackSkeletonClass() throws IOException {
4399 // Create a new directory
4400 String path = createDirectories(dir, subdir);
4401 for (String intface : mapIntfacePTH.keySet()) {
4402 // Open a new file to write into
4403 String newSkelClass = intface + "_CallbackSkeleton";
4404 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4405 pw = new PrintWriter(new BufferedWriter(fw));
4406 // Write file headers
4407 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4408 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4409 println("#include <iostream>");
4410 println("#include \"" + intface + ".hpp\"\n");
4411 // Pass in set of methods and get import classes
4412 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4413 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4414 List<String> methods = intDecl.getMethods();
4415 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4416 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4417 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4418 printIncludeStatements(allIncludeClasses); println("");
4419 // Find out if there are callback objects
4420 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4421 boolean callbackExist = !callbackClasses.isEmpty();
4422 println("using namespace std;\n");
4423 // Write class header
4424 println("class " + newSkelClass + " : public " + intface); println("{");
4425 println("private:\n");
4427 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4428 println("public:\n");
4429 // Write constructor
4430 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4431 // Write deconstructor
4432 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4434 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4435 // Write method helper
4436 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4437 // Write waitRequestInvokeMethod() - main loop
4438 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4440 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4443 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4449 * generateInitializer() generate initializer based on type
4451 public String generateCplusInitializer(String type) {
4453 // Generate dummy returns for now
4454 if (type.equals("short")||
4455 type.equals("int") ||
4456 type.equals("long") ||
4457 type.equals("float")||
4458 type.equals("double")) {
4461 } else if ( type.equals("String") ||
4462 type.equals("string")) {
4465 } else if ( type.equals("char") ||
4466 type.equals("byte")) {
4469 } else if ( type.equals("boolean")) {
4479 * setDirectory() sets a new directory for stub files
4481 public void setDirectory(String _subdir) {
4488 * printUsage() prints the usage of this compiler
4490 public static void printUsage() {
4492 System.out.println();
4493 System.out.println("Sentinel interface and stub compiler version 1.0");
4494 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4495 System.out.println("All rights reserved.");
4496 System.out.println("Usage:");
4497 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4498 System.out.println("\t\tDisplay this help texts\n\n");
4499 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4500 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4501 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4502 System.out.println("Options:");
4503 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4504 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4505 System.out.println();
4510 * parseFile() prepares Lexer and Parser objects, then parses the file
4512 public static ParseNode parseFile(String file) {
4514 ParseNode pn = null;
4516 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4517 ScannerBuffer lexer =
4518 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4519 Parser parse = new Parser(lexer,csf);
4520 pn = (ParseNode) parse.parse().value;
4521 } catch (Exception e) {
4522 e.printStackTrace();
4523 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4531 * Basic helper functions
4534 boolean newline=true;
4537 private void print(String str) {
4540 if (str.equals("}"))
4542 for(int i=0; i<tab; i++)
4552 * This function converts Java to C++ type for compilation
4554 private String convertType(String type) {
4556 if (mapPrimitives.containsKey(type))
4557 return mapPrimitives.get(type);
4564 * A collection of methods with print-to-file functionality
4566 private void println(String str) {
4569 if (str.contains("}") && !str.contains("{"))
4571 for(int i=0; i<tab; i++)
4580 private void updatetabbing(String str) {
4582 tablevel+=count(str,'{')-count(str,'}');
4586 private int count(String str, char key) {
4587 char[] array = str.toCharArray();
4589 for(int i=0; i<array.length; i++) {
4590 if (array[i] == key)
4597 private void createDirectory(String dirName) {
4599 File file = new File(dirName);
4600 if (!file.exists()) {
4602 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4604 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4607 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4612 // Create a directory and possibly a sub directory
4613 private String createDirectories(String dir, String subdir) {
4616 createDirectory(path);
4617 if (subdir != null) {
4618 path = path + "/" + subdir;
4619 createDirectory(path);
4625 // Inserting array members into a Map object
4626 // that maps arrKey to arrVal objects
4627 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4629 for(int i = 0; i < arrKey.length; i++) {
4631 map.put(arrKey[i], arrVal[i]);
4636 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4637 // Throw an error if the new interface is not found!
4638 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4639 private int getNewIntfaceObjectId(String newIntface) {
4641 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4642 throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4643 "Please place the two files for callback class in front...\n");
4645 int retObjId = mapNewIntfaceObjId.get(newIntface);
4651 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4652 private ParamCategory getParamCategory(String paramType) {
4654 if (mapPrimitives.containsKey(paramType)) {
4655 return ParamCategory.PRIMITIVES;
4656 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4657 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4658 return ParamCategory.NONPRIMITIVES;
4659 } else if (isEnumClass(paramType)) {
4660 return ParamCategory.ENUM;
4661 } else if (isStructClass(paramType)) {
4662 return ParamCategory.STRUCT;
4664 return ParamCategory.USERDEFINED;
4668 // Return full class name for non-primitives to generate Java import statements
4669 // e.g. java.util.Set for Set
4670 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4672 return mapNonPrimitivesJava.get(paramNonPrimitives);
4676 // Return full class name for non-primitives to generate Cplus include statements
4677 // e.g. #include <set> for Set
4678 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4680 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4684 // Get simple types, e.g. HashSet for HashSet<...>
4685 // Basically strip off the "<...>"
4686 private String getSimpleType(String paramType) {
4688 // Check if this is generics
4689 if(paramType.contains("<")) {
4690 String[] type = paramType.split("<");
4697 // Generate a set of standard classes for import statements
4698 private List<String> getStandardJavaIntfaceImportClasses() {
4700 List<String> importClasses = new ArrayList<String>();
4701 // Add the standard list first
4702 importClasses.add("java.util.List");
4703 importClasses.add("java.util.ArrayList");
4705 return importClasses;
4709 // Generate a set of standard classes for import statements
4710 private List<String> getStandardJavaImportClasses() {
4712 List<String> importClasses = new ArrayList<String>();
4713 // Add the standard list first
4714 importClasses.add("java.io.IOException");
4715 importClasses.add("java.util.List");
4716 importClasses.add("java.util.ArrayList");
4717 importClasses.add("java.util.Arrays");
4718 importClasses.add("iotrmi.Java.IoTRMICall");
4719 importClasses.add("iotrmi.Java.IoTRMIObject");
4721 return importClasses;
4725 // Generate a set of standard classes for import statements
4726 private List<String> getStandardCplusIncludeClasses() {
4728 List<String> importClasses = new ArrayList<String>();
4729 // Add the standard list first
4730 importClasses.add("<vector>");
4731 importClasses.add("<set>");
4732 importClasses.add("\"IoTRMICall.hpp\"");
4733 importClasses.add("\"IoTRMIObject.hpp\"");
4735 return importClasses;
4739 // Combine all classes for import statements
4740 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4742 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4743 // Iterate over the list of import classes
4744 for (String str : libClasses) {
4745 if (!allLibClasses.contains(str)) {
4746 allLibClasses.add(str);
4749 return allLibClasses;
4754 // Generate a set of classes for import statements
4755 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4757 Set<String> importClasses = new HashSet<String>();
4758 for (String method : methods) {
4759 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4760 for (String paramType : methPrmTypes) {
4762 String simpleType = getSimpleType(paramType);
4763 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4764 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4768 return importClasses;
4772 // Handle and return the correct enum declaration
4773 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4774 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4776 // Strips off array "[]" for return type
4777 String pureType = getSimpleArrayType(type);
4778 // Take the inner type of generic
4779 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4780 pureType = getTypeOfGeneric(type)[0];
4781 if (isEnumClass(pureType)) {
4782 String enumType = intDecl.getInterface() + "." + type;
4789 // Handle and return the correct type
4790 private String getEnumParam(String type, String param, int i) {
4792 // Strips off array "[]" for return type
4793 String pureType = getSimpleArrayType(type);
4794 // Take the inner type of generic
4795 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4796 pureType = getTypeOfGeneric(type)[0];
4797 if (isEnumClass(pureType)) {
4798 String enumParam = "paramEnum" + i;
4805 // Handle and return the correct enum declaration translate into int[]
4806 private String getEnumType(String type) {
4808 // Strips off array "[]" for return type
4809 String pureType = getSimpleArrayType(type);
4810 // Take the inner type of generic
4811 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4812 pureType = getGenericType(type);
4813 if (isEnumClass(pureType)) {
4814 String enumType = "int[]";
4820 // Handle and return the correct enum declaration translate into int* for C
4821 private String getEnumCplusClsType(String type) {
4823 // Strips off array "[]" for return type
4824 String pureType = getSimpleArrayType(type);
4825 // Take the inner type of generic
4826 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4827 pureType = getGenericType(type);
4828 if (isEnumClass(pureType)) {
4829 String enumType = "int*";
4836 // Handle and return the correct struct declaration
4837 private String getStructType(String type) {
4839 // Strips off array "[]" for return type
4840 String pureType = getSimpleArrayType(type);
4841 // Take the inner type of generic
4842 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4843 pureType = getGenericType(type);
4844 if (isStructClass(pureType)) {
4845 String structType = "int";
4852 // Check if this an enum declaration
4853 private boolean isEnumClass(String type) {
4855 // Just iterate over the set of interfaces
4856 for (String intface : mapIntfacePTH.keySet()) {
4857 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4858 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4859 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4860 if (setEnumDecl.contains(type))
4867 // Check if this an struct declaration
4868 private boolean isStructClass(String type) {
4870 // Just iterate over the set of interfaces
4871 for (String intface : mapIntfacePTH.keySet()) {
4872 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4873 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4874 List<String> listStructDecl = structDecl.getStructTypes();
4875 if (listStructDecl.contains(type))
4882 // Return a struct declaration
4883 private StructDecl getStructDecl(String type) {
4885 // Just iterate over the set of interfaces
4886 for (String intface : mapIntfacePTH.keySet()) {
4887 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4888 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4889 List<String> listStructDecl = structDecl.getStructTypes();
4890 if (listStructDecl.contains(type))
4897 // Return number of members (-1 if not found)
4898 private int getNumOfMembers(String type) {
4900 // Just iterate over the set of interfaces
4901 for (String intface : mapIntfacePTH.keySet()) {
4902 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4903 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4904 List<String> listStructDecl = structDecl.getStructTypes();
4905 if (listStructDecl.contains(type))
4906 return structDecl.getNumOfMembers(type);
4912 // Generate a set of classes for include statements
4913 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4915 Set<String> includeClasses = new HashSet<String>();
4916 for (String method : methods) {
4918 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4919 List<String> methParams = intDecl.getMethodParams(method);
4920 for (int i = 0; i < methPrmTypes.size(); i++) {
4922 String simpleType = getSimpleType(methPrmTypes.get(i));
4923 String param = methParams.get(i);
4924 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4925 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4926 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4927 // For original interface, we need it exchanged... not for stub interfaces
4929 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4930 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4932 includeClasses.add("\"" + simpleType + ".hpp\"");
4933 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4935 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4936 includeClasses.add("\"" + simpleType + ".hpp\"");
4937 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
4938 includeClasses.add("\"" + simpleType + ".hpp\"");
4939 } else if (param.contains("[]")) {
4940 // Check if this is array for C++; translate into vector
4941 includeClasses.add("<vector>");
4945 return includeClasses;
4949 // Generate a set of callback classes
4950 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4952 Set<String> callbackClasses = new HashSet<String>();
4953 for (String method : methods) {
4955 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4956 List<String> methParams = intDecl.getMethodParams(method);
4957 for (int i = 0; i < methPrmTypes.size(); i++) {
4959 String type = methPrmTypes.get(i);
4960 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4961 callbackClasses.add(type);
4962 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4963 // Can be a List<...> of callback objects ...
4964 String genericType = getTypeOfGeneric(type)[0];
4965 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4966 callbackClasses.add(type);
4971 return callbackClasses;
4975 // Print import statements into file
4976 private void printImportStatements(Collection<String> importClasses) {
4978 for(String cls : importClasses) {
4979 println("import " + cls + ";");
4984 // Print include statements into file
4985 private void printIncludeStatements(Collection<String> includeClasses) {
4987 for(String cls : includeClasses) {
4988 println("#include " + cls);
4993 // Get the C++ version of a non-primitive type
4994 // e.g. set for Set and map for Map
4995 // Input nonPrimitiveType has to be generics in format
4996 private String[] getTypeOfGeneric(String nonPrimitiveType) {
4998 // Handle <, >, and , for 2-type generic/template
4999 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5004 // Gets generic type inside "<" and ">"
5005 private String getGenericType(String type) {
5007 // Handle <, >, and , for 2-type generic/template
5008 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5009 String[] substr = type.split("<")[1].split(">")[0].split(",");
5016 // This helper function strips off array declaration, e.g. int[] becomes int
5017 private String getSimpleArrayType(String type) {
5019 // Handle [ for array declaration
5020 String substr = type;
5021 if (type.contains("[]")) {
5022 substr = type.split("\\[\\]")[0];
5028 // This helper function strips off array declaration, e.g. D[] becomes D
5029 private String getSimpleIdentifier(String ident) {
5031 // Handle [ for array declaration
5032 String substr = ident;
5033 if (ident.contains("[]")) {
5034 substr = ident.split("\\[\\]")[0];
5040 // Checks and gets type in C++
5041 private String checkAndGetCplusType(String paramType) {
5043 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5044 return convertType(paramType);
5045 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5047 // Check for generic/template format
5048 if (paramType.contains("<") && paramType.contains(">")) {
5050 String genericClass = getSimpleType(paramType);
5051 String[] genericType = getTypeOfGeneric(paramType);
5052 String cplusTemplate = null;
5053 if (genericType.length == 1) // Generic/template with one type
5054 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5055 "<" + convertType(genericType[0]) + ">";
5056 else // Generic/template with two types
5057 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5058 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
5059 return cplusTemplate;
5061 return getNonPrimitiveCplusClass(paramType);
5062 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5063 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5065 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5066 return paramType + "*";
5068 // Just return it as is if it's not non-primitives
5070 //return checkAndGetParamClass(paramType, true);
5074 // Detect array declaration, e.g. int A[],
5075 // then generate "int A[]" in C++ as "vector<int> A"
5076 private String checkAndGetCplusArray(String paramType, String param) {
5078 String paramComplete = null;
5079 // Check for array declaration
5080 if (param.contains("[]")) {
5081 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5083 // Just return it as is if it's not an array
5084 paramComplete = paramType + " " + param;
5086 return paramComplete;
5090 // Detect array declaration, e.g. int A[],
5091 // then generate "int A[]" in C++ as "vector<int> A"
5092 // This method just returns the type
5093 private String checkAndGetCplusArrayType(String paramType) {
5095 String paramTypeRet = null;
5096 // Check for array declaration
5097 if (paramType.contains("[]")) {
5098 String type = paramType.split("\\[\\]")[0];
5099 paramTypeRet = checkAndGetCplusType(type) + "[]";
5100 } else if (paramType.contains("vector")) {
5101 // Just return it as is if it's not an array
5102 String type = paramType.split("<")[1].split(">")[0];
5103 paramTypeRet = checkAndGetCplusType(type) + "[]";
5105 paramTypeRet = paramType;
5107 return paramTypeRet;
5111 // Detect array declaration, e.g. int A[],
5112 // then generate "int A[]" in C++ as "vector<int> A"
5113 // This method just returns the type
5114 private String checkAndGetCplusArrayType(String paramType, String param) {
5116 String paramTypeRet = null;
5117 // Check for array declaration
5118 if (param.contains("[]")) {
5119 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5120 } else if (paramType.contains("vector")) {
5121 // Just return it as is if it's not an array
5122 String type = paramType.split("<")[1].split(">")[0];
5123 paramTypeRet = checkAndGetCplusType(type) + "[]";
5125 paramTypeRet = paramType;
5127 return paramTypeRet;
5131 // Return the class type for class resolution (for return value)
5132 // - Check and return C++ array class, e.g. int A[] into int*
5133 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5134 private String checkAndGetCplusRetClsType(String paramType) {
5136 String paramTypeRet = null;
5137 // Check for array declaration
5138 if (paramType.contains("[]")) {
5139 String type = paramType.split("\\[\\]")[0];
5140 paramTypeRet = getSimpleArrayType(type) + "*";
5141 } else if (paramType.contains("<") && paramType.contains(">")) {
5142 // Just return it as is if it's not an array
5143 String type = paramType.split("<")[1].split(">")[0];
5144 paramTypeRet = "vector<" + getGenericType(type) + ">";
5146 paramTypeRet = paramType;
5148 return paramTypeRet;
5152 // Return the class type for class resolution (for method arguments)
5153 // - Check and return C++ array class, e.g. int A[] into int*
5154 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5155 private String checkAndGetCplusArgClsType(String paramType, String param) {
5157 String paramTypeRet = getEnumCplusClsType(paramType);
5158 if (!paramTypeRet.equals(paramType))
5159 // Just return if it is an enum type
5160 // Type will still be the same if it's not an enum type
5161 return paramTypeRet;
5163 // Check for array declaration
5164 if (param.contains("[]")) {
5165 paramTypeRet = getSimpleArrayType(paramType) + "*";
5166 } else if (paramType.contains("<") && paramType.contains(">")) {
5167 // Just return it as is if it's not an array
5168 String type = paramType.split("<")[1].split(">")[0];
5169 paramTypeRet = "vector<" + getGenericType(type) + ">";
5171 paramTypeRet = paramType;
5173 return paramTypeRet;
5177 // Detect array declaration, e.g. int A[],
5178 // then generate type "int[]"
5179 private String checkAndGetArray(String paramType, String param) {
5181 String paramTypeRet = null;
5182 // Check for array declaration
5183 if (param.contains("[]")) {
5184 paramTypeRet = paramType + "[]";
5186 // Just return it as is if it's not an array
5187 paramTypeRet = paramType;
5189 return paramTypeRet;
5193 // Is array or list?
5194 private boolean isArrayOrList(String paramType, String param) {
5196 // Check for array declaration
5199 else if (isList(paramType))
5207 // For return type we use retType as input parameter
5208 private boolean isArray(String param) {
5210 // Check for array declaration
5211 if (param.contains("[]"))
5219 private boolean isList(String paramType) {
5221 // Check for array declaration
5222 if (paramType.contains("List"))
5229 // Get the right type for a callback object
5230 private String checkAndGetParamClass(String paramType) {
5232 // Check if this is generics
5233 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5234 return exchangeParamType(paramType);
5240 // Returns the other interface for type-checking purposes for USERDEFINED
5241 // classes based on the information provided in multiple policy files
5242 // e.g. return CameraWithXXX instead of Camera
5243 private String exchangeParamType(String intface) {
5245 // Param type that's passed is the interface name we need to look for
5246 // in the map of interfaces, based on available policy files.
5247 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5248 if (decHandler != null) {
5249 // We've found the required interface policy files
5250 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5251 Set<String> setExchInt = reqDecl.getInterfaces();
5252 if (setExchInt.size() == 1) {
5253 Iterator iter = setExchInt.iterator();
5254 return (String) iter.next();
5256 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5257 ". Only one new interface can be declared if the object " + intface +
5258 " needs to be passed in as an input parameter!\n");
5261 // NULL value - this means policy files missing
5262 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5263 "... Please provide the necessary policy files for user-defined types." +
5264 " If this is an array please type the brackets after the variable name," +
5265 " e.g. \"String str[]\", not \"String[] str\"." +
5266 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5267 " supports List/ArrayList (Java) or list (C++).\n");
5272 public static void main(String[] args) throws Exception {
5274 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5275 if ((args[0].equals("-help") ||
5276 args[0].equals("--help")||
5277 args[0].equals("-h")) ||
5278 (args.length == 0)) {
5280 IoTCompiler.printUsage();
5282 } else if (args.length > 1) {
5284 IoTCompiler comp = new IoTCompiler();
5287 // Parse main policy file
5288 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5289 // Parse "requires" policy file
5290 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5291 // Get interface name
5292 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5293 comp.setDataStructures(intface, pnPol, pnReq);
5294 comp.getMethodsForIntface(intface);
5296 // 1) Check if this is the last option before "-java" or "-cplus"
5297 // 2) Check if this is really the last option (no "-java" or "-cplus")
5298 } while(!args[i].equals("-java") &&
5299 !args[i].equals("-cplus") &&
5302 // Generate everything if we don't see "-java" or "-cplus"
5303 if (i == args.length) {
5304 comp.generateEnumJava();
5305 comp.generateStructJava();
5306 comp.generateJavaLocalInterfaces();
5307 comp.generateJavaInterfaces();
5308 comp.generateJavaStubClasses();
5309 comp.generateJavaCallbackStubClasses();
5310 comp.generateJavaSkeletonClass();
5311 comp.generateJavaCallbackSkeletonClass();
5312 comp.generateEnumCplus();
5313 comp.generateStructCplus();
5314 comp.generateCplusLocalInterfaces();
5315 comp.generateCPlusInterfaces();
5316 comp.generateCPlusStubClasses();
5317 comp.generateCPlusCallbackStubClasses();
5318 comp.generateCplusSkeletonClass();
5319 comp.generateCplusCallbackSkeletonClass();
5321 // Check other options
5322 while(i < args.length) {
5324 if (!args[i].equals("-java") &&
5325 !args[i].equals("-cplus")) {
5326 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5328 if (i + 1 < args.length) {
5329 comp.setDirectory(args[i+1]);
5331 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5333 if (args[i].equals("-java")) {
5334 comp.generateEnumJava();
5335 comp.generateStructJava();
5336 comp.generateJavaLocalInterfaces();
5337 comp.generateJavaInterfaces();
5338 comp.generateJavaStubClasses();
5339 comp.generateJavaCallbackStubClasses();
5340 comp.generateJavaSkeletonClass();
5341 comp.generateJavaCallbackSkeletonClass();
5343 comp.generateEnumCplus();
5344 comp.generateStructCplus();
5345 comp.generateCplusLocalInterfaces();
5346 comp.generateCPlusInterfaces();
5347 comp.generateCPlusStubClasses();
5348 comp.generateCPlusCallbackStubClasses();
5349 comp.generateCplusSkeletonClass();
5350 comp.generateCplusCallbackSkeletonClass();
5357 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5358 IoTCompiler.printUsage();
5359 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");