3ce672d7c07f7eb3bda5e24df11b46bf18723c18
[iot2.git] / iotjava / iotruntime / master / IoTMaster.java
1 package iotruntime.master;
2
3 import iotruntime.*;
4 import iotruntime.slave.IoTAddress;
5 import iotruntime.slave.IoTDeviceAddress;
6 import iotruntime.messages.*;
7
8 // ASM packages
9 import org.objectweb.asm.ClassReader;
10 import org.objectweb.asm.ClassWriter;
11 import org.objectweb.asm.ClassVisitor;
12
13 // Java packages
14 import java.io.*;
15 import java.util.*;
16 import java.io.BufferedReader;
17 import java.io.InputStream;
18 import java.io.InputStreamReader;
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.OutputStream;
23 import java.io.ObjectInputStream;
24 import java.io.ObjectOutputStream;
25 import java.io.IOException;
26 import java.lang.ClassNotFoundException;
27 import java.lang.Class;
28 import java.lang.reflect.*;
29 import java.net.Socket;
30 import java.net.ServerSocket;
31 import java.nio.ByteBuffer;
32 import java.util.*;
33 import static java.lang.Math.toIntExact;
34
35 /** Class IoTMaster is responsible to use ClassRuntimeInstrumenterMaster
36  *  to instrument the controller/device bytecode and starts multiple
37  *  IoTSlave running on different JVM's in a distributed fashion.
38  *
39  * @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
40  * @version     1.0
41  * @since       2016-06-16
42  */
43 public final class IoTMaster {
44
45         /**
46          * IoTMaster class properties
47          * <p>
48          * CommunicationHandler maintains the data structure for hostnames and ports
49          * LoadBalancer assigns a job onto a host based on certain metrics
50          */
51         private CommunicationHandler commHan;
52         private LoadBalancer lbIoT;
53         private RouterConfig routerConfig;
54         private ProcessJailConfig processJailConfig;
55         private ObjectInitHandler objInitHand;
56         private ObjectAddressInitHandler objAddInitHand;
57         private String[] strObjectNames;
58         // Now this can be either ClassRuntimeInstrumenterMaster or CRuntimeInstrumenterMaster
59         private Map<String,Object> mapClassNameToCrim;
60
61         /**
62          * These properties hold information of a certain object
63          * at a certain time
64          */
65         private String strObjName;
66         private String strObjClassName;
67         private String strObjClassInterfaceName;
68         private String strObjStubClsIntfaceName;
69         private String strIoTMasterHostAdd;
70         private String strIoTSlaveControllerHostAdd;
71         private String strIoTSlaveObjectHostAdd;
72         private Class[] arrFieldClasses;
73         private Object[] arrFieldValues;
74         private Socket filesocket;
75
76         /**
77          * For connection with C++ IoTSlave
78          */
79         private ServerSocket serverSocketCpp;
80         private Socket socketCpp;
81         private BufferedInputStream inputCpp;
82         private BufferedOutputStream outputCpp;
83
84         // Constants that are to be extracted from config file
85         private static String STR_MASTER_MAC_ADD;
86         private static String STR_IOT_CODE_PATH;
87         private static String STR_CONT_PATH;
88         private static String STR_RUNTIME_DIR;
89         private static String STR_SLAVE_DIR;
90         private static String STR_CLS_PATH;
91         private static String STR_RMI_PATH;
92         private static String STR_RMI_HOSTNAME;
93         private static String STR_LOG_FILE_PATH;
94         private static String STR_USERNAME;
95         private static String STR_ROUTER_ADD;
96         private static String STR_MONITORING_HOST;
97         private static String STR_ZB_GATEWAY_ADDRESS;
98         private static String STR_ZB_GATEWAY_PORT;
99         private static String STR_ZB_IOTMASTER_PORT;
100         private static String STR_JVM_INIT_HEAP_SIZE;
101         private static String STR_JVM_MAX_HEAP_SIZE;
102         private static String STR_LANGUAGE_CONTROLLER;
103         private static String STR_SKEL_CLASS_SUFFIX;
104         private static String STR_STUB_CLASS_SUFFIX;
105         private static String STR_ACTIVATE_SANDBOXING;
106         private static boolean BOOL_VERBOSE;
107
108         /**
109          * IoTMaster class constants
110          * <p>
111          * Name constants - not to be configured by users
112          */
113         private static final String STR_IOT_MASTER_NAME = "IoTMaster";
114         private static final String STR_CFG_FILE_EXT = ".config";
115         private static final String STR_CLS_FILE_EXT = ".class";
116         private static final String STR_JAR_FILE_EXT = ".jar";
117         private static final String STR_MAC_POLICY_EXT = ".tomoyo.pol"; 
118         private static final String STR_SHELL_FILE_EXT = ".sh";
119         private static final String STR_SO_FILE_EXT = ".so";
120         private static final String STR_ZIP_FILE_EXT = ".zip";
121         private static final String STR_TCP_PROTOCOL = "tcp";
122         private static final String STR_UDP_PROTOCOL = "udp";
123         private static final String STR_TCPGW_PROTOCOL = "tcpgw";
124         private static final String STR_NO_PROTOCOL = "nopro";
125         private static final String STR_SELF_MAC_ADD = "00:00:00:00:00:00";
126         private static final String STR_INTERFACE_CLS_CFG = "INTERFACE_CLASS";
127         private static final String STR_INT_STUB_CLS_CFG = "INTERFACE_STUB_CLASS";
128         private static final String STR_FILE_TRF_CFG = "ADDITIONAL_ZIP_FILE";
129         private static final String STR_LANGUAGE = "LANGUAGE";
130         private static final String STR_YES = "Yes";
131         private static final String STR_NO = "No";
132         private static final String STR_JAVA = "Java";
133         private static final String STR_CPP = "C++";
134         private static final String STR_SSH = "ssh";
135         private static final String STR_SCP = "scp";
136         private static final String STR_IOTSLAVE_CPP = "./IoTSlave.o";
137         private static final String STR_SHELL_HEADER = "#!/bin/sh";
138         private static final String STR_JAVA_PATH = "/usr/bin/java";
139         private static final String STR_MAC_POL_PATH = "tomoyo/";
140
141         private static int INT_SIZE = 4;        // send length in the size of integer (4 bytes)
142         private static final int INT_DNS_PORT = 53;
143
144         /**
145          * Runtime class name constants - not to be configured by users
146          */
147         private static final String STR_REL_INSTRUMENTER_CLS = "iotruntime.master.RelationInstrumenter";
148         private static final String STR_SET_INSTRUMENTER_CLS = "iotruntime.master.SetInstrumenter";
149         private static final String STR_IOT_SLAVE_CLS = "iotruntime.slave.IoTSlave";
150         private static final String STR_IOT_DEV_ADD_CLS = "IoTDeviceAddress";
151         private static final String STR_IOT_ZB_ADD_CLS = "IoTZigbeeAddress";
152         private static final String STR_IOT_ADD_CLS = "IoTAddress";
153         
154         /**
155          * Class constructor
156          *
157          */
158         public IoTMaster(String[] argObjNms) {
159
160                 commHan = null;
161                 lbIoT = null;
162                 routerConfig = null;
163                 processJailConfig = null;
164                 objInitHand = null;
165                 objAddInitHand = null;
166                 strObjectNames = argObjNms;
167                 strObjName = null;
168                 strObjClassName = null;
169                 strObjClassInterfaceName = null;
170                 strObjStubClsIntfaceName = null;
171                 strIoTMasterHostAdd = null;
172                 strIoTSlaveControllerHostAdd = null;
173                 strIoTSlaveObjectHostAdd = null;
174                 arrFieldClasses = null;
175                 arrFieldValues = null;
176                 filesocket = null;
177                 mapClassNameToCrim = null;
178                 // Connection with C++ IoTSlave
179                 serverSocketCpp = null;
180                 socketCpp = null;
181                 inputCpp = null;
182                 outputCpp = null;
183
184                 STR_MASTER_MAC_ADD = null;
185                 STR_IOT_CODE_PATH = null;
186                 STR_CONT_PATH = null;
187                 STR_RUNTIME_DIR = null;
188                 STR_SLAVE_DIR = null;
189                 STR_CLS_PATH = null;
190                 STR_RMI_PATH = null;
191                 STR_RMI_HOSTNAME = null;
192                 STR_LOG_FILE_PATH = null;
193                 STR_USERNAME = null;
194                 STR_ROUTER_ADD = null;
195                 STR_MONITORING_HOST = null;
196                 STR_ZB_GATEWAY_ADDRESS = null;
197                 STR_ZB_GATEWAY_PORT = null;
198                 STR_ZB_IOTMASTER_PORT = null;
199                 STR_JVM_INIT_HEAP_SIZE = null;
200                 STR_JVM_MAX_HEAP_SIZE = null;
201                 STR_LANGUAGE_CONTROLLER = null;
202                 STR_ACTIVATE_SANDBOXING = null;
203                 BOOL_VERBOSE = false;
204         }
205
206         /**
207          * A method to initialize CommunicationHandler, LoadBalancer, RouterConfig and ObjectInitHandler
208          *
209          * @return void
210          */
211         private void initLiveDataStructure() {
212
213                 commHan = new CommunicationHandler(BOOL_VERBOSE);
214                 lbIoT = new LoadBalancer(BOOL_VERBOSE);
215                 lbIoT.setupLoadBalancer();
216                 routerConfig = new RouterConfig();
217                 routerConfig.getAddressList(STR_ROUTER_ADD);
218                 processJailConfig = new ProcessJailConfig();
219                 //processJailConfig.setAddressListObject(routerConfig.getAddressListObject());
220                 objInitHand = new ObjectInitHandler(BOOL_VERBOSE);
221                 objAddInitHand = new ObjectAddressInitHandler(BOOL_VERBOSE);
222                 mapClassNameToCrim = new HashMap<String,Object>();
223         }
224
225         /**
226          * getPrintWriter() gets a new PrintWriter for a new object
227          *
228          * @param   strObjectName       String object name
229          * @return  PrintWriter
230          */
231         private PrintWriter getPrintWriter(String strObjectName) {
232
233                 FileWriter fw = null;
234                 try {
235                         fw = new FileWriter(strObjectName);
236                 } catch (IOException ex) {
237                         ex.printStackTrace();
238                 }
239                 PrintWriter printWriter = new PrintWriter(new BufferedWriter(fw));
240                 return printWriter;
241         }
242
243         /**
244          * A method to initialize constants from config file
245          *
246          * @return void
247          */
248         private void parseIoTMasterConfigFile() {
249                 // Parse configuration file
250                 Properties prop = new Properties();
251                 String strCfgFileName = STR_IOT_MASTER_NAME + STR_CFG_FILE_EXT;
252                 File file = new File(strCfgFileName);
253                 FileInputStream fis = null;
254                 try {
255                         fis = new FileInputStream(file);
256                         prop.load(fis);
257                         fis.close();
258                 } catch (IOException ex) {
259                         System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
260                         ex.printStackTrace();
261                 }
262                 // Initialize constants from config file
263                 STR_MASTER_MAC_ADD = prop.getProperty("MAC_ADDRESS");
264                 STR_IOT_CODE_PATH = prop.getProperty("IOT_CODE_PATH");
265                 STR_CONT_PATH = prop.getProperty("CONTROLLERS_CODE_PATH");
266                 STR_RUNTIME_DIR = prop.getProperty("RUNTIME_DIR");
267                 STR_SLAVE_DIR = prop.getProperty("SLAVE_DIR");
268                 STR_CLS_PATH = prop.getProperty("CLASS_PATH");
269                 STR_RMI_PATH = prop.getProperty("RMI_PATH");
270                 STR_RMI_HOSTNAME = prop.getProperty("RMI_HOSTNAME");
271                 STR_LOG_FILE_PATH = prop.getProperty("LOG_FILE_PATH");
272                 STR_USERNAME = prop.getProperty("USERNAME");
273                 STR_ROUTER_ADD = prop.getProperty("ROUTER_ADD");
274                 STR_MONITORING_HOST = prop.getProperty("MONITORING_HOST");
275                 STR_ZB_GATEWAY_ADDRESS = prop.getProperty("ZIGBEE_GATEWAY_ADDRESS");
276                 STR_ZB_GATEWAY_PORT = prop.getProperty("ZIGBEE_GATEWAY_PORT");
277                 STR_ZB_IOTMASTER_PORT = prop.getProperty("ZIGBEE_IOTMASTER_PORT");
278                 STR_JVM_INIT_HEAP_SIZE = prop.getProperty("JVM_INIT_HEAP_SIZE");
279                 STR_JVM_MAX_HEAP_SIZE = prop.getProperty("JVM_MAX_HEAP_SIZE");
280                 STR_SKEL_CLASS_SUFFIX = prop.getProperty("SKEL_CLASS_SUFFIX");
281                 STR_STUB_CLASS_SUFFIX = prop.getProperty("STUB_CLASS_SUFFIX");
282                 STR_ACTIVATE_SANDBOXING = prop.getProperty("ACTIVATE_SANDBOXING");
283                 if(prop.getProperty("VERBOSE").equals(STR_YES)) {
284                         BOOL_VERBOSE = true;
285                 }
286
287                 RuntimeOutput.print("IoTMaster: Extracting information from config file: " + strCfgFileName, BOOL_VERBOSE);
288                 RuntimeOutput.print("STR_MASTER_MAC_ADD=" + STR_MASTER_MAC_ADD, BOOL_VERBOSE);
289                 RuntimeOutput.print("STR_IOT_CODE_PATH=" + STR_IOT_CODE_PATH, BOOL_VERBOSE);
290                 RuntimeOutput.print("STR_CONT_PATH=" + STR_CONT_PATH, BOOL_VERBOSE);
291                 RuntimeOutput.print("STR_RUNTIME_DIR=" + STR_RUNTIME_DIR, BOOL_VERBOSE);
292                 RuntimeOutput.print("STR_SLAVE_DIR=" + STR_SLAVE_DIR, BOOL_VERBOSE);
293                 RuntimeOutput.print("STR_CLS_PATH=" + STR_CLS_PATH, BOOL_VERBOSE);
294                 RuntimeOutput.print("STR_RMI_PATH=" + STR_RMI_PATH, BOOL_VERBOSE);
295                 RuntimeOutput.print("STR_RMI_HOSTNAME=" + STR_RMI_HOSTNAME, BOOL_VERBOSE);
296                 RuntimeOutput.print("STR_LOG_FILE_PATH=" + STR_LOG_FILE_PATH, BOOL_VERBOSE);
297                 RuntimeOutput.print("STR_USERNAME=" + STR_USERNAME, BOOL_VERBOSE);
298                 RuntimeOutput.print("STR_ROUTER_ADD=" + STR_ROUTER_ADD, BOOL_VERBOSE);
299                 RuntimeOutput.print("STR_MONITORING_HOST=" + STR_MONITORING_HOST, BOOL_VERBOSE);
300                 RuntimeOutput.print("STR_ZB_GATEWAY_ADDRESS=" + STR_ZB_GATEWAY_ADDRESS, BOOL_VERBOSE);
301                 RuntimeOutput.print("STR_ZB_GATEWAY_PORT=" + STR_ZB_GATEWAY_PORT, BOOL_VERBOSE);
302                 RuntimeOutput.print("STR_ZB_IOTMASTER_PORT=" + STR_ZB_IOTMASTER_PORT, BOOL_VERBOSE);
303                 RuntimeOutput.print("STR_JVM_INIT_HEAP_SIZE=" + STR_JVM_INIT_HEAP_SIZE, BOOL_VERBOSE);
304                 RuntimeOutput.print("STR_JVM_MAX_HEAP_SIZE=" + STR_JVM_MAX_HEAP_SIZE, BOOL_VERBOSE);
305                 RuntimeOutput.print("STR_SKEL_CLASS_SUFFIX=" + STR_SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
306                 RuntimeOutput.print("STR_STUB_CLASS_SUFFIX=" + STR_STUB_CLASS_SUFFIX, BOOL_VERBOSE);
307                 RuntimeOutput.print("STR_ACTIVATE_SANDBOXING=" + STR_ACTIVATE_SANDBOXING, BOOL_VERBOSE);
308                 RuntimeOutput.print("BOOL_VERBOSE=" + BOOL_VERBOSE, BOOL_VERBOSE);
309                 RuntimeOutput.print("IoTMaster: Information extracted successfully!", BOOL_VERBOSE);
310         }
311
312         /**
313          * A method to parse information from a config file
314          *
315          * @param       strCfgFileName  Config file name
316          * @param       strCfgField             Config file field name
317          * @return      String
318          */
319         private String parseConfigFile(String strCfgFileName, String strCfgField) {
320                 // Parse configuration file
321                 Properties prop = new Properties();
322                 File file = new File(strCfgFileName);
323                 FileInputStream fis = null;
324                 try {
325                         fis = new FileInputStream(file);
326                         prop.load(fis);
327                         fis.close();
328                 } catch (IOException ex) {
329                         System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
330                         ex.printStackTrace();
331                 }
332                 System.out.println("IoTMaster: Reading " + strCfgField +
333                         " from config file: " + strCfgFileName + " with value: " + 
334                         prop.getProperty(strCfgField, null));
335                 // NULL is returned if the property isn't found
336                 return prop.getProperty(strCfgField, null);
337         }
338
339         /**
340          * A method to send files from IoTMaster
341          *
342          * @param  filesocket File socket object
343          * @param  sFileName  File name
344          * @param  lFLength   File length
345          * @return            void
346          */
347         private void sendFile(Socket filesocket, String sFileName, long lFLength) throws IOException {
348
349                 File file = new File(sFileName);
350                 byte[] bytFile = new byte[toIntExact(lFLength)];
351                 InputStream inFileStream = new FileInputStream(file);
352
353                 OutputStream outFileStream = filesocket.getOutputStream();
354                 int iCount;
355                 while ((iCount = inFileStream.read(bytFile)) > 0) {
356                         outFileStream.write(bytFile, 0, iCount);
357                 }
358                 filesocket.close();
359                 RuntimeOutput.print("IoTMaster: File sent!", BOOL_VERBOSE);
360         }
361
362         /**
363          * A method to create a thread
364          *
365          * @param  sSSHCmd    SSH command
366          * @return            void
367          */
368         private void createThread(String sSSHCmd) throws IOException {
369
370                 // Start a new thread to start a new JVM
371                 new Thread() {
372                         Runtime runtime = Runtime.getRuntime();
373                         Process process = runtime.exec(sSSHCmd);
374                 }.start();
375                 RuntimeOutput.print("Executing: " + sSSHCmd, BOOL_VERBOSE);
376         }
377
378         /**
379          * A method to send command from master and receive reply from slave
380          *
381          * @params  msgSend     Message object
382          * @params  strPurpose  String that prints purpose message
383          * @params  inStream    Input stream
384          * @params  outStream   Output stream
385          * @return  void
386          */
387         private void commMasterToSlave(Message msgSend, String strPurpose,
388                 InputStream _inStream, OutputStream _outStream)  
389                         throws IOException, ClassNotFoundException {
390
391                 // Send message/command from master
392                 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
393                 outStream.writeObject(msgSend);
394                 RuntimeOutput.print("IoTMaster: Send message: " + strPurpose, BOOL_VERBOSE);
395
396                 // Get reply from slave as acknowledgment
397                 ObjectInputStream inStream = (ObjectInputStream) _inStream;
398                 Message msgReply = (Message) inStream.readObject();
399                 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
400         }
401
402         /**
403          * A private method to instrument IoTSet device
404          *
405          * @params  strFieldIdentifier        String field name + object ID
406          * @params  strFieldName              String field name
407          * @params  strIoTSlaveObjectHostAdd  String slave host address
408          * @params  inStream                  ObjectInputStream communication
409          * @params  inStream                  ObjectOutputStream communication
410          * @params  strLanguage                           String language
411          * @return  void
412          */
413         private void instrumentIoTSetDevice(String strFieldIdentifier, String strObjName, String strFieldName, String strIoTSlaveObjectHostAdd,
414                 InputStream inStream, OutputStream outStream, String strLanguage)  
415                         throws IOException, ClassNotFoundException, InterruptedException {
416
417                 // Get information from the set
418                 List<Object[]> listObject = objAddInitHand.getFields(strFieldIdentifier);
419         RuntimeOutput.print("IoTMaster: DEBUG: Getting into instrumentIoTSetDevice!", BOOL_VERBOSE);
420                 // Create a new IoTSet
421                 if(strLanguage.equals(STR_JAVA)) {
422                         Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
423                         commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTDeviceAddress!", inStream, outStream);
424                 } else
425                         createNewIoTSetCpp(strFieldName, outStream, inStream);
426                 int iRows = listObject.size();
427                 RuntimeOutput.print("IoTMaster: Number of rows for IoTDeviceAddress: " + iRows, BOOL_VERBOSE);
428                 // Transfer the address
429                 for(int iRow=0; iRow<iRows; iRow++) {
430                         arrFieldValues = listObject.get(iRow);
431                         // Get device address - if 00:00:00:00:00:00 that means it needs the driver object address (self)
432                         String strDeviceAddress = null;
433                         String strDeviceAddressKey = null;
434                         if (arrFieldValues[0].equals(STR_SELF_MAC_ADD)) {
435                                 strDeviceAddress = strIoTSlaveObjectHostAdd;
436                                 strDeviceAddressKey = strObjName + "-" + strIoTSlaveObjectHostAdd;
437                         } else {
438                                 strDeviceAddress = routerConfig.getIPFromMACAddress((String) arrFieldValues[0]);
439                                 strDeviceAddressKey = strObjName + "-" + strDeviceAddress;
440                         }
441                         int iDestDeviceDriverPort = (int) arrFieldValues[1];
442                         String strProtocol = (String) arrFieldValues[2];
443                         // Check for wildcard feature                   
444                         boolean bSrcPortWildCard = false;
445                         boolean bDstPortWildCard = false;
446                         if (arrFieldValues.length > 3) {
447                                 bSrcPortWildCard = (boolean) arrFieldValues[3];
448                                 bDstPortWildCard = (boolean) arrFieldValues[4];
449                         }
450                         // Add the port connection into communication handler - if it's not assigned yet
451                         if (commHan.getComPort(strDeviceAddressKey) == null) {
452                                 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
453                         }
454
455                         // TODO: DEBUG!!!
456                         System.out.println("\n\n DEBUG: InstrumentSetDevice: Object Name: " + strObjName);
457                         System.out.println("DEBUG: InstrumentSetDevice: Port number: " + commHan.getComPort(strDeviceAddressKey));
458                         System.out.println("DEBUG: InstrumentSetDevice: Device address: " + strDeviceAddressKey + "\n\n");
459
460                         // Send address one by one
461                         if(strLanguage.equals(STR_JAVA)) {
462                                 Message msgGetIoTSetObj = null;
463                                 if (bDstPortWildCard) {
464                                         String strUniqueDev = strDeviceAddressKey + ":" + iRow;
465                                         msgGetIoTSetObj = new MessageGetDeviceObject(IoTCommCode.GET_DEVICE_IOTSET_OBJECT,
466                                                 strDeviceAddress, commHan.getAdditionalPort(strUniqueDev), iDestDeviceDriverPort, bSrcPortWildCard, bDstPortWildCard);
467                                 } else
468                                         msgGetIoTSetObj = new MessageGetDeviceObject(IoTCommCode.GET_DEVICE_IOTSET_OBJECT,
469                                                 strDeviceAddress, commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort, bSrcPortWildCard, bDstPortWildCard);
470                                 commMasterToSlave(msgGetIoTSetObj, "Get IoTSet objects!", inStream, outStream);
471                         } else
472                                 getDeviceIoTSetObjectCpp(outStream, inStream, strDeviceAddress, commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort, 
473                                         bSrcPortWildCard, bDstPortWildCard);
474                 }
475                 // Reinitialize IoTSet on device object
476                 if(strLanguage.equals(STR_JAVA))
477                         commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD), "Reinitialize IoTSet fields!", inStream, outStream);
478                 else
479                         reinitializeIoTSetFieldCpp(outStream, inStream);
480         }
481
482
483         /**
484          * A private method to instrument IoTSet Zigbee device
485          *
486          * @params  Map.Entry<String,Object>  Entry of map IoTSet instrumentation
487          * @params  strFieldName              String field name
488          * @params  strIoTSlaveObjectHostAdd  String slave host address
489          * @params  inStream                  ObjectInputStream communication
490          * @params  inStream                  ObjectOutputStream communication
491          * @params  strLanguage                           String language
492          * @return  void
493          */
494         private void instrumentIoTSetZBDevice(Map.Entry<String,Object> map, String strObjName, String strFieldName, String strIoTSlaveObjectHostAdd,
495                 InputStream inStream, OutputStream outStream, String strLanguage)  
496                         throws IOException, ClassNotFoundException, InterruptedException {
497
498                 // Get information from the set
499                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
500                 // Create a new IoTSet
501                 if(strLanguage.equals(STR_JAVA)) {
502                         Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
503                         commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTZigbeeAddress!", inStream, outStream);
504                 } else  // TODO: will need to implement IoTSet Zigbee for C++ later
505                         ;
506                 // Prepare ZigbeeConfig
507                 String strZigbeeGWAddress = routerConfig.getIPFromMACAddress(STR_ZB_GATEWAY_ADDRESS);
508                 String strZigbeeGWAddressKey = strObjName + "-" + strZigbeeGWAddress;
509                 int iZigbeeGWPort = Integer.parseInt(STR_ZB_GATEWAY_PORT);
510                 int iZigbeeIoTMasterPort = Integer.parseInt(STR_ZB_IOTMASTER_PORT);
511                 commHan.addDevicePort(iZigbeeIoTMasterPort);
512                 ZigbeeConfig zbConfig = new ZigbeeConfig(strZigbeeGWAddress, iZigbeeGWPort, iZigbeeIoTMasterPort, 
513                         BOOL_VERBOSE);
514                 // Add the port connection into communication handler - if it's not assigned yet
515                 if (commHan.getComPort(strZigbeeGWAddressKey) == null) {
516                         commHan.addPortConnection(strIoTSlaveObjectHostAdd, strZigbeeGWAddressKey);
517                 }               
518                 int iRows = setInstrumenter.numberOfRows();
519                 RuntimeOutput.print("IoTMaster: Number of rows for IoTZigbeeAddress: " + iRows, BOOL_VERBOSE);
520
521                 // TODO: DEBUG!!!
522                 System.out.println("\n\nDEBUG: InstrumentZigbeeDevice: Object Name: " + strObjName);
523                 System.out.println("DEBUG: InstrumentZigbeeDevice: Port number: " + commHan.getComPort(strZigbeeGWAddressKey));
524                 System.out.println("DEBUG: InstrumentZigbeeDevice: Device address: " + strZigbeeGWAddress + "\n\n");
525
526                 // Transfer the address
527                 for(int iRow=0; iRow<iRows; iRow++) {
528                         arrFieldValues = setInstrumenter.fieldValues(iRow);
529                         // Get device address
530                         String strZBDevAddress = (String) arrFieldValues[0];
531                         // Send policy to Zigbee gateway - TODO: Need to clear policy first?
532                         zbConfig.setPolicy(strIoTSlaveObjectHostAdd, commHan.getComPort(strZigbeeGWAddressKey), strZBDevAddress);
533                         // Send address one by one
534                         if(strLanguage.equals(STR_JAVA)) {
535                                 Message msgGetIoTSetZBObj = new MessageGetSimpleDeviceObject(IoTCommCode.GET_ZB_DEV_IOTSET_OBJECT, strZBDevAddress);
536                                 commMasterToSlave(msgGetIoTSetZBObj, "Get IoTSet objects!", inStream, outStream);
537                         } else  // TODO: Implement IoTSet Zigbee for C++
538                                 ;
539                 }
540                 zbConfig.closeConnection();
541                 // Reinitialize IoTSet on device object
542                 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD), "Reinitialize IoTSet fields!", inStream, outStream);
543         }
544
545         
546         /**
547          * A private method to instrument IoTSet of addresses
548          *
549          * @params  strFieldIdentifier        String field name + object ID
550          * @params  strFieldName              String field name
551          * @params  inStream                  ObjectInputStream communication
552          * @params  inStream                  ObjectOutputStream communication
553          * @params  strLanguage                           String language
554          * @return  void
555          */
556         private void instrumentIoTSetAddress(String strFieldIdentifier, String strFieldName,
557                 InputStream inStream, OutputStream outStream, String strLanguage)  
558                         throws IOException, ClassNotFoundException, InterruptedException {
559
560                 // Get information from the set
561                 List<Object[]> listObject = objAddInitHand.getFields(strFieldIdentifier);
562                 // Create a new IoTSet
563                 if(strLanguage.equals(STR_JAVA)) {
564                         Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
565                         commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTAddress!", inStream, outStream);
566                 } else
567                         ;
568                 int iRows = listObject.size();
569                 RuntimeOutput.print("IoTMaster: Number of rows for IoTAddress: " + iRows, BOOL_VERBOSE);
570                 // Transfer the address
571                 for(int iRow=0; iRow<iRows; iRow++) {
572                         arrFieldValues = listObject.get(iRow);
573                         // Get device address
574                         String strAddress = (String) arrFieldValues[0];
575                         // Send address one by one
576                         if(strLanguage.equals(STR_JAVA)) {
577                                 Message msgGetIoTSetAddObj = new MessageGetSimpleDeviceObject(IoTCommCode.GET_ADD_IOTSET_OBJECT, strAddress);
578                                 commMasterToSlave(msgGetIoTSetAddObj, "Get IoTSet objects!", inStream, outStream);
579                         } else  // TODO: Implement IoTSet Address for C++
580                                 ;
581                 }
582                 // Reinitialize IoTSet on device object
583                 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD),
584                                                                                         "Reinitialize IoTSet fields!", inStream, outStream);
585         }
586
587
588         /**
589          * A private method to instrument an object on a specific machine and setting up policies
590          *
591          * @params  strFieldObjectID              String field object ID
592          * @params  strObjControllerName          String object controller name
593          * @params  strLanguage                           String language
594          * @return  void
595          */
596         private void instrumentObject(String strFieldObjectID, String strObjControllerName, String strLanguage) throws IOException {
597
598                 // Extract the interface name for RMI
599                 // e.g. ProximitySensorInterface, TempSensorInterface, etc.
600                 
601                 String strObjCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
602                 strObjClassInterfaceName = parseConfigFile(strObjCfgFile, STR_INTERFACE_CLS_CFG);
603                 strObjStubClsIntfaceName = parseConfigFile(strObjCfgFile, STR_INT_STUB_CLS_CFG);
604                 // Create an object name, e.g. ProximitySensorImplPS1
605                 strObjName = strObjClassName + strFieldObjectID;
606                 // Check first if host exists
607                 if(commHan.objectExists(strObjName)) {
608                         // If this object exists already ...
609                         // Re-read IoTSlave object hostname for further reference
610                         strIoTSlaveObjectHostAdd = commHan.getHostAddress(strObjName);
611                         RuntimeOutput.print("IoTMaster: Object with name: " + strObjName + " has existed!", BOOL_VERBOSE);
612                 } else {
613                         // If this is a new object ... then create one
614                         // Get host address for IoTSlave from LoadBalancer
615                         //strIoTSlaveObjectHostAdd = lbIoT.selectHost();
616                         strIoTSlaveObjectHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
617                         if (strIoTSlaveControllerHostAdd == null)
618                                 throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
619                         RuntimeOutput.print("IoTMaster: Object name: " + strObjName, BOOL_VERBOSE);
620                         // Add port connection and get port numbers
621                         // Naming for objects ProximitySensor becomes ProximitySensor0, ProximitySensor1, etc.
622                         commHan.addPortConnection(strIoTSlaveObjectHostAdd, strObjName);
623                         commHan.addActiveControllerObject(strFieldObjectID, strObjName, strObjClassName, strObjClassInterfaceName, 
624                                 strObjStubClsIntfaceName, strIoTSlaveObjectHostAdd, arrFieldValues, arrFieldClasses);
625                         // ROUTING POLICY: IoTMaster and device/controller object
626                         // Master-slave communication
627                         routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTMasterHostAdd,
628                                 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
629                         // ROUTING POLICY: Send the same routing policy to both the hosts
630                         routerConfig.configureHostMainPolicies(strIoTMasterHostAdd, strIoTMasterHostAdd,
631                                 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
632                         routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTMasterHostAdd,
633                                 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
634                         // Need to accommodate callback functions here - open ports for TCP
635                         routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd,
636                                 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
637                         routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd,
638                                 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
639                         routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd,
640                                 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
641                         // Configure MAC policies for objects
642                         //String strFileName = STR_MAC_POL_PATH + strObjClassName + STR_MAC_POLICY_EXT;
643                         String strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
644                         if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
645                                 processJailConfig.configureProcessJailDeviceDriverPolicies(strIoTSlaveObjectHostAdd, strObjName, strObjClassName,
646                                         strFileName, strIoTMasterHostAdd, commHan.getComPort(strObjName), commHan.getRMIRegPort(strObjName), 
647                                         commHan.getRMIStubPort(strObjName));
648                                 processJailConfig.configureProcessJailContRMIPolicies(strObjControllerName, strIoTSlaveObjectHostAdd, 
649                                         commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
650                         }
651                         // Instrument the IoTSet declarations inside the class file
652                         instrumentObjectIoTSet(strFieldObjectID, strLanguage);
653                 }
654                 // Send routing policy to router for controller object
655                 // ROUTING POLICY: RMI communication - RMI registry and stub ports
656                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
657                         STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
658                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
659                         STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
660                 // Send the same set of routing policies to compute nodes
661                 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
662                         STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
663                 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
664                         STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
665                 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
666                         STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
667                 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
668                         STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
669         }
670
671
672         /**
673          * A private method to set router policies for IoTDeviceAddress objects
674          *
675          * @params  strFieldIdentifier        String field name + object ID
676          * @params  Map.Entry<String,Object>  Entry of map IoTSet instrumentation
677          * @params  strIoTSlaveObjectHostAdd  String slave host address
678          * @return  void
679          */
680         private void setRouterPolicyIoTSetDevice(String strFieldIdentifier, Map.Entry<String,Object> map, 
681                 String strIoTSlaveObjectHostAdd) {
682
683                 // Get information from the set
684                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
685                 int iRows = setInstrumenter.numberOfRows();
686                 RuntimeOutput.print("IoTMaster: Number of rows for IoTDeviceAddress: " + iRows, BOOL_VERBOSE);
687                 // Transfer the address
688                 for(int iRow=0; iRow<iRows; iRow++) {
689                         arrFieldValues = setInstrumenter.fieldValues(iRow);
690                         objAddInitHand.addField(strFieldIdentifier, arrFieldValues);    // Save this for object instantiation
691                         // Get device address - if 00:00:00:00:00:00 that means it needs the driver object address (self)
692                         String strDeviceAddress = null;
693                         String strDeviceAddressKey = null;
694                         if (arrFieldValues[0].equals(STR_SELF_MAC_ADD)) {
695                                 strDeviceAddress = strIoTSlaveObjectHostAdd;
696                                 strDeviceAddressKey = strObjName + "-" + strIoTSlaveObjectHostAdd;
697                         } else {        // Concatenate object name and IP address to give unique key - for a case where there is one device for multiple drivers
698                                 strDeviceAddress = routerConfig.getIPFromMACAddress((String) arrFieldValues[0]);
699                                 strDeviceAddressKey = strObjName + "-" + strDeviceAddress;
700                         }
701                         int iDestDeviceDriverPort = (int) arrFieldValues[1];
702                         String strProtocol = (String) arrFieldValues[2];
703                         // Add the port connection into communication handler - if it's not assigned yet
704                         if (commHan.getComPort(strDeviceAddressKey) == null)
705                                 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
706                         boolean bDstPortWildCard = false;
707                         // Recognize this and allocate different ports for it
708                         if (arrFieldValues.length > 3) {
709                                 bDstPortWildCard = (boolean) arrFieldValues[4];
710                                 if (bDstPortWildCard) { // This needs a unique source port
711                                         String strUniqueDev = strDeviceAddressKey + ":" + iRow; 
712                                         commHan.addAdditionalPort(strUniqueDev);
713                                 }
714                         }
715
716                         // TODO: DEBUG!!!
717                         System.out.println("\n\n DEBUG: InstrumentPolicySetDevice: Object Name: " + strObjName);
718                         System.out.println("DEBUG: InstrumentPolicySetDevice: Port number: " + commHan.getComPort(strDeviceAddressKey));
719                         System.out.println("DEBUG: InstrumentPolicySetDevice: Device address: " + strDeviceAddressKey + "\n\n");
720
721                         // Send routing policy to router for device drivers and devices
722                         // ROUTING POLICY: RMI communication - RMI registry and stub ports
723                         if((iDestDeviceDriverPort == -1) && (!strProtocol.equals(STR_NO_PROTOCOL))) {
724                                 // Port number -1 means that we don't set the policy strictly to port number level
725                                 // "nopro" = no protocol specified for just TCP or just UDP (can be both used as well)
726                                 // ROUTING POLICY: Device driver and device
727                                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol);
728                                 // ROUTING POLICY: Send to the compute node where the device driver is
729                                 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol);
730                         } else if((iDestDeviceDriverPort == -1) && (strProtocol.equals(STR_NO_PROTOCOL))) {
731                                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress);
732                                 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress);
733                         } else if(strProtocol.equals(STR_TCPGW_PROTOCOL)) {
734                                 // This is a TCP protocol that connects, e.g. a phone to our runtime system
735                                 // that provides a gateway access (accessed through destination port number)
736                                 commHan.addDevicePort(iDestDeviceDriverPort);
737                                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, STR_TCP_PROTOCOL, iDestDeviceDriverPort);
738                                 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, STR_TCP_PROTOCOL, iDestDeviceDriverPort);
739                                 routerConfig.configureRouterHTTPPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress);
740                                 routerConfig.configureHostHTTPPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress);
741                                 // Configure MAC policies
742                                 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
743                                         processJailConfig.configureProcessJailGWDevicePolicies(strIoTSlaveObjectHostAdd, STR_ROUTER_ADD, strDeviceAddress, INT_DNS_PORT);
744                         } else {
745                                 // Other port numbers...
746                                 commHan.addDevicePort(iDestDeviceDriverPort);
747                                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol, 
748                                         commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort);
749                                 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol, 
750                                         commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort);
751                                 // Configure MAC policies
752                                 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
753                                         processJailConfig.configureProcessJailDevicePolicies(strIoTSlaveObjectHostAdd, strProtocol,
754                                                 commHan.getComPort(strDeviceAddressKey), strDeviceAddress, iDestDeviceDriverPort);
755                         }
756                 }
757         }
758
759         /**
760          * A private method to set router policies for IoTAddress objects
761          *
762          * @params  strFieldIdentifier        String field name + object ID
763          * @params  Map.Entry<String,Object>  Entry of map IoTSet instrumentation
764          * @params  strHostAddress            String host address
765          * @return  void
766          */
767         private void setRouterPolicyIoTSetAddress(String strFieldIdentifier, Map.Entry<String,Object> map, 
768                 String strHostAddress, String strControllerName) {
769
770                 // Get information from the set
771                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
772                 int iRows = setInstrumenter.numberOfRows();
773                 RuntimeOutput.print("IoTMaster: Number of rows for IoTAddress: " + iRows, BOOL_VERBOSE);
774                 // Transfer the address
775                 for(int iRow=0; iRow<iRows; iRow++) {
776                         arrFieldValues = setInstrumenter.fieldValues(iRow);
777                         objAddInitHand.addField(strFieldIdentifier, arrFieldValues);    // Save this for object instantiation
778                         // Get device address
779                         String strAddress = (String) arrFieldValues[0];
780                         // Setting up router policies for HTTP/HTTPs
781                         if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
782                                 if (strControllerName != null) {
783                                         processJailConfig.configureProcessJailInetAddressPolicies(strControllerName, STR_ROUTER_ADD, strAddress);
784                                 } else {
785                                         processJailConfig.configureProcessJailInetAddressPolicies(strHostAddress, STR_ROUTER_ADD, strAddress);
786                                 }
787                         }
788                         routerConfig.configureRouterHTTPPolicies(STR_ROUTER_ADD, strHostAddress, strAddress);
789                         routerConfig.configureHostHTTPPolicies(strHostAddress, strHostAddress, strAddress);
790                 }
791         }
792
793         /**
794          * A private method to instrument an object's IoTSet and IoTRelation field to up policies
795          * <p>
796          * Mostly the IoTSet fields would contain IoTDeviceAddress objects
797          *
798          * @params  strFieldObjectID    String field object ID
799          * @params  strLanguage                 String language
800          * @return  void
801          */
802         private void instrumentObjectIoTSet(String strFieldObjectID, String strLanguage) throws IOException {
803
804                 // If this is a new object ... then create one
805                 // Instrument the class source code and look for IoTSet for device addresses
806                 // e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
807                 HashMap<String,Object> hmObjectFieldObjects = null;
808                 if(strLanguage.equals(STR_JAVA)) {
809                         String strObjectClassNamePath = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CLS_FILE_EXT;
810                         FileInputStream fis = new FileInputStream(strObjectClassNamePath);
811                         ClassReader cr = new ClassReader(fis);
812                         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
813                         // We need Object ID to instrument IoTDeviceAddress
814                         ClassRuntimeInstrumenterMaster crim = new ClassRuntimeInstrumenterMaster(cw, strFieldObjectID, BOOL_VERBOSE);
815                         cr.accept(crim, 0);
816                         fis.close();
817                         mapClassNameToCrim.put(strObjClassName + strFieldObjectID, crim);
818                         hmObjectFieldObjects = crim.getFieldObjects();
819                 } else {        // For C++
820                         String strObjectClassNamePath = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
821                         CRuntimeInstrumenterMaster crim = new CRuntimeInstrumenterMaster(strObjectClassNamePath, strFieldObjectID, BOOL_VERBOSE);
822                         mapClassNameToCrim.put(strObjClassName + strFieldObjectID, crim);
823                         hmObjectFieldObjects = crim.getFieldObjects();
824                 }
825                 // Get the object and the class names
826                 // Build objects for IoTSet and IoTRelation fields in the device object classes
827                 RuntimeOutput.print("IoTMaster: Going to instrument for " + strObjClassName + " with objectID " + 
828                         strFieldObjectID, BOOL_VERBOSE);
829                 for(Map.Entry<String,Object> map : hmObjectFieldObjects.entrySet()) {
830                         RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
831                         // Iterate over HashMap and choose between processing
832                         String strFieldName = map.getKey();
833                         String strClassName = map.getValue().getClass().getName();
834                         String strFieldIdentifier = strFieldName + strFieldObjectID;
835                         if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
836                                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
837                                 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) { 
838                                 // Instrument the normal IoTDeviceAddress
839                                         setRouterPolicyIoTSetDevice(strFieldIdentifier, map, strIoTSlaveObjectHostAdd);
840                                 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) { 
841                                 // Instrument the IoTAddress
842                                         setRouterPolicyIoTSetAddress(strFieldIdentifier, map, strIoTSlaveObjectHostAdd, null);
843                                 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) { 
844                                 // Instrument the IoTZigbeeAddress - special feature for Zigbee device support
845                                         RuntimeOutput.print("IoTMaster: IoTZigbeeAddress found! No router policy is set here..", 
846                                                 BOOL_VERBOSE);
847                                 } else {
848                                         String strErrMsg = "IoTMaster: Device driver object" +
849                                                                                 " can only have IoTSet<IoTAddress>, IoTSet<IoTDeviceAddress>," +
850                                                                                 " or IoTSet<IoTZigbeeAddress>!";
851                                         throw new Error(strErrMsg);
852                                 }
853                         } else {
854                                 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet for addresses!";
855                                 throw new Error(strErrMsg);
856                         }
857                 }
858         }
859
860
861         /**
862          * A private method to send files to a Java slave driver
863          *
864          * @params  serverSocket                                ServerSocket
865          * @params  _inStream                                   InputStream
866          * @params  _outStream                                  OutputStream
867          * @params  strObjName                                  String
868          * @params  strObjClassName                             String
869          * @params  strObjClassInterfaceName    String
870          * @params  strObjStubClsIntfaceName    String
871          * @params  strIoTSlaveObjectHostAdd    String
872          * @params  strFieldObjectID                    String
873          * @params  arrFieldValues                              Object[]
874          * @params  arrFieldClasses                             Class[]
875          * @return  void
876          */
877         private void sendFileToJavaSlaveDriver(ServerSocket serverSocket, InputStream _inStream, OutputStream _outStream,
878                 String strObjName, String strObjClassName, String strObjClassInterfaceName, String strObjStubClsIntfaceName,
879                 String strIoTSlaveObjectHostAdd, String strFieldObjectID, Object[] arrFieldValues, Class[] arrFieldClasses) 
880                         throws IOException, ClassNotFoundException {
881
882                 ObjectInputStream inStream = (ObjectInputStream) _inStream;
883                 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
884                 // Create message to transfer file first
885                 String sFileName = strObjClassName + STR_JAR_FILE_EXT;
886                 String sPath = STR_IOT_CODE_PATH + strObjClassName + "/" + sFileName;
887                 File file = new File(sPath);
888                 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, sFileName, file.length()),
889                         "Sending file!", inStream, outStream);
890                 // Send file - JAR file for object creation
891                 sendFile(serverSocket.accept(), sPath, file.length());
892                 Message msgReply = (Message) inStream.readObject();
893                 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
894                 // Pack object information to create object on a IoTSlave
895                 Message msgObjIoTSlave = new MessageCreateObject(IoTCommCode.CREATE_OBJECT, strIoTSlaveObjectHostAdd,
896                         strObjClassName, strObjName, strObjClassInterfaceName, strObjStubClsIntfaceName, commHan.getRMIRegPort(strObjName), 
897                         commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses);
898                 // Send message
899                 commMasterToSlave(msgObjIoTSlave, "Sending object information", inStream, outStream);
900         }
901
902
903         /**
904          * A private method to send files to a Java slave driver
905          *
906          * @return  void
907          */
908         private void sendFileToCppSlaveDriver(String strObjClassName, String strIoTSlaveObjectHostAdd) 
909                         throws IOException, ClassNotFoundException {
910
911                 // Create message to transfer file first
912                 String sFileName = strObjClassName + STR_ZIP_FILE_EXT;
913                 String sFile = STR_IOT_CODE_PATH + strObjClassName + "/" + sFileName;
914                 String strCmdSend = STR_SCP + " " + sFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_SLAVE_DIR;
915                 runCommand(strCmdSend);
916                 RuntimeOutput.print("IoTMaster: Executing: " + strCmdSend, BOOL_VERBOSE);
917                 // Unzip file
918                 String strCmdUnzip = STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " +
919                                         STR_SLAVE_DIR + " sudo unzip -o " + sFileName + ";";
920                 runCommand(strCmdUnzip);
921                 RuntimeOutput.print("IoTMaster: Executing: " + strCmdUnzip, BOOL_VERBOSE);
922
923         }
924
925
926         /**
927          * Construct command line for Java IoTSlave
928          *
929          * @return       String
930          */
931         private String getCmdJavaDriverIoTSlave(String strIoTMasterHostAdd, String strIoTSlaveObjectHostAdd, String strObjName) {
932
933                 // Create an Shell executable
934                 String strJavaCommand = STR_SHELL_HEADER + "\nexec " + STR_JAVA_PATH + " " + STR_CLS_PATH + " " + STR_RMI_PATH + " " + 
935                         STR_RMI_HOSTNAME + strIoTSlaveObjectHostAdd + " " + STR_IOT_SLAVE_CLS + " " + strIoTMasterHostAdd + " " +
936                         commHan.getComPort(strObjName) + " " + commHan.getRMIRegPort(strObjName) + " " +
937                         commHan.getRMIStubPort(strObjName) + " > " + STR_LOG_FILE_PATH + strObjName + ".log &";
938                 String shellFile = "./" + strObjName + STR_SHELL_FILE_EXT;
939                 createWrapperShellScript(strJavaCommand, shellFile);
940                 // Send the file to the compute node
941                 String strCmdSend = "scp " + shellFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_RUNTIME_DIR;
942                 runCommand(strCmdSend);
943                 System.out.println("IoTMaster: Sending shell file: " + strCmdSend);
944                 return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
945         }
946
947
948         /**
949          * Construct command line for C++ IoTSlave
950          *
951          * @return       String
952          */
953         private String getCmdCppDriverIoTSlave(String strIoTMasterHostAdd, String strIoTSlaveObjectHostAdd, String strObjName) {
954
955                 return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " +
956                                         STR_SLAVE_DIR + " sudo " + STR_IOTSLAVE_CPP + " " + strIoTMasterHostAdd + " " +
957                                         commHan.getComPort(strObjName) + " " + strObjName;
958         }
959
960
961         /**
962          * createWrapperShellScript() gets a wrapper shell script
963          *
964          * @param   strCommand          String command
965          * @param   strObjectName       String object name
966          * @return  PrintWriter
967          */
968         private void createWrapperShellScript(String strCommand, String strFileName) {
969
970                 PrintWriter printWriter = getPrintWriter(strFileName);
971                 printWriter.println(strCommand);
972                 printWriter.close();
973                 runCommand("chmod 755 " + strFileName);
974         }
975
976
977         /**
978          * A private method to create an object on a specific machine
979          *
980          * @params  strObjName                                  String object name
981          * @params  strObjClassName                     String object class name
982          * @params  strObjClassInterfaceName    String object class interface name
983          * @params  strIoTSlaveObjectHostAdd    String IoTSlave host address
984          * @params  strFieldObjectID                    String field object ID
985          * @params  arrFieldValues                              Array of field values
986          * @params  arrFieldClasses                             Array of field classes
987          * @return  void
988          */
989         private void createObject(String strObjName, String strObjClassName, String strObjClassInterfaceName, String strObjStubClsIntfaceName,
990                 String strIoTSlaveObjectHostAdd, String strFieldObjectID, Object[] arrFieldValues, Class[] arrFieldClasses) 
991                 throws IOException, FileNotFoundException, ClassNotFoundException, InterruptedException {
992
993                 // Read config file
994                 String sCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
995                 String strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE + "_" + strObjName);
996                 if(strLanguageDriver == null)   // Read just the field LANGUAGE if the first read is null
997                         strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE);
998                 if(strLanguageDriver == null) // Check nullness for the second time - report if it is still null
999                         throw new Error("IoTMaster: Language specification missing in config file: " + sCfgFile);
1000                 // PROFILING
1001                 long start = 0;
1002                 long result = 0;
1003                 // PROFILING
1004                 start = System.currentTimeMillis();
1005
1006                 // Construct ssh command line
1007                 // e.g. ssh rtrimana@dw-2.eecs.uci.edu cd <path>;
1008                 //      java -cp $CLASSPATH:./*.jar
1009                 //           -Djava.rmi.server.codebase=file:./*.jar
1010                 //           iotruntime.IoTSlave dw-1.eecs.uci.edu 46151 23829 42874 &
1011                 // The In-Port for IoTMaster is the Out-Port for IoTSlave and vice versa
1012                 String strSSHCommand = null;
1013                 if(strLanguageDriver.equals(STR_JAVA))
1014                         strSSHCommand = getCmdJavaDriverIoTSlave(strIoTMasterHostAdd, strIoTSlaveObjectHostAdd, strObjName);
1015                 else if(strLanguageDriver.equals(STR_CPP))
1016                         strSSHCommand = getCmdCppDriverIoTSlave(strIoTMasterHostAdd, strIoTSlaveObjectHostAdd, strObjName);
1017                 else
1018                         throw new Error("IoTMaster: Language specification not recognized: " + strLanguageDriver);
1019                 RuntimeOutput.print("IoTMaster: Language for " + strObjName + " is " + strLanguageDriver, BOOL_VERBOSE);
1020
1021                 RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
1022                 // Start a new thread to start a new JVM
1023                 createThread(strSSHCommand);
1024                 ServerSocket serverSocket = new ServerSocket(commHan.getComPort(strObjName));
1025                 Socket socket = serverSocket.accept();
1026                 //InputStream inStream = new ObjectInputStream(socket.getInputStream());
1027                 //OutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
1028                 InputStream inStream = null;
1029                 OutputStream outStream = null;
1030                 if(strLanguageDriver.equals(STR_JAVA)) {
1031                         inStream = new ObjectInputStream(socket.getInputStream());
1032                         outStream = new ObjectOutputStream(socket.getOutputStream());
1033                 } else {        // At this point the language is certainly C++, otherwise would've complained above
1034                         inStream = new BufferedInputStream(socket.getInputStream());
1035                         outStream = new BufferedOutputStream(socket.getOutputStream());
1036                         recvAck(inStream);
1037                 }
1038
1039                 // PROFILING
1040                 result = System.currentTimeMillis()-start;
1041                 System.out.println("\n\n ==> Time needed to start JVM for " + strObjName + ": " + result + "\n\n");
1042
1043                 // PROFILING
1044                 start = System.currentTimeMillis();
1045
1046                 if(strLanguageDriver.equals(STR_JAVA)) {
1047                         sendFileToJavaSlaveDriver(serverSocket, inStream, outStream, strObjName, 
1048                                 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
1049                                 strIoTSlaveObjectHostAdd, strFieldObjectID, arrFieldValues, arrFieldClasses);
1050                 } else {
1051                         sendFileToCppSlaveDriver(strObjClassName, strIoTSlaveObjectHostAdd);
1052                         createObjectCpp(strObjName, strObjClassName, strObjClassInterfaceName, strIoTSlaveObjectHostAdd,
1053                         commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses,
1054                         outStream, inStream);
1055                 }
1056
1057                 // PROFILING
1058                 result = System.currentTimeMillis()-start;
1059                 System.out.println("\n\n ==> Time needed to send JAR file for " + strObjName + ": " + result + "\n\n");
1060
1061                 // PROFILING
1062                 start = System.currentTimeMillis();
1063
1064                 // Instrument the class source code and look for IoTSet for device addresses
1065                 // e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
1066                 RuntimeOutput.print("IoTMaster: Instantiating for " + strObjClassName + " with objectID " + strFieldObjectID, BOOL_VERBOSE);
1067                 // Get the object and the class names
1068                 // Build objects for IoTSet and IoTRelation fields in the device object classes
1069                 Object crimObj = mapClassNameToCrim.get(strObjClassName + strFieldObjectID);
1070                 HashMap<String,Object> hmObjectFieldObjects = null;
1071                 if (crimObj instanceof ClassRuntimeInstrumenterMaster) {
1072                         ClassRuntimeInstrumenterMaster crim = (ClassRuntimeInstrumenterMaster) crimObj;
1073                         hmObjectFieldObjects = crim.getFieldObjects();
1074                 } else if (crimObj instanceof CRuntimeInstrumenterMaster) {
1075                         CRuntimeInstrumenterMaster crim = (CRuntimeInstrumenterMaster) crimObj;
1076                         hmObjectFieldObjects = crim.getFieldObjects();
1077                 }
1078                 for(Map.Entry<String,Object> map : hmObjectFieldObjects.entrySet()) {
1079                         RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
1080                         // Iterate over HashMap and choose between processing
1081                         String strFieldName = map.getKey();
1082                         String strClassName = map.getValue().getClass().getName();
1083                         String strFieldIdentifier = strFieldName + strFieldObjectID;
1084                         if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
1085                                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
1086                                 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) { 
1087                                 // Instrument the normal IoTDeviceAddress
1088                                         synchronized(this) {
1089                                     //RuntimeOutput.print("IoTMaster: DEBUG: Processing " + STR_IOT_DEV_ADD_CLS + "!", BOOL_VERBOSE);
1090                                                 instrumentIoTSetDevice(strFieldIdentifier, strObjName, strFieldName, strIoTSlaveObjectHostAdd, inStream, outStream, strLanguageDriver);
1091                                         }
1092                                 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) { 
1093                                 // Instrument the IoTZigbeeAddress - special feature for Zigbee device support
1094                                         synchronized(this) {
1095                                                 instrumentIoTSetZBDevice(map, strObjName, strFieldName, strIoTSlaveObjectHostAdd, inStream, outStream, strLanguageDriver);
1096                                         }
1097                                 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) { 
1098                                 // Instrument the IoTAddress
1099                                         synchronized(this) {
1100                                                 instrumentIoTSetAddress(strFieldIdentifier, strFieldName, inStream, outStream, strLanguageDriver);
1101                                         }
1102                                 } else {
1103                                         String strErrMsg = "IoTMaster: Device driver object can only have IoTSet<IoTAddress>, IoTSet<IoTDeviceAddress>," +
1104                                                                                 " or IoTSet<IoTZigbeeAddress>!";
1105                                         throw new Error(strErrMsg);
1106                                 }
1107                         } else {
1108                                 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet for addresses!";
1109                                 throw new Error(strErrMsg);
1110                         }
1111                 }
1112                 // End the session
1113                 // TODO: Change this later
1114                 if(strLanguageDriver.equals(STR_JAVA)) {
1115                         ObjectOutputStream oStream = (ObjectOutputStream) outStream;
1116                         oStream.writeObject(new MessageSimple(IoTCommCode.END_SESSION));
1117                 } else {        // C++ side for now will be running continuously because it's an infinite loop (not in a separate thread)
1118                         createDriverObjectCpp(outStream, inStream);
1119                         //endSessionCpp(outStream);
1120                 }
1121
1122                 // PROFILING
1123                 result = System.currentTimeMillis()-start;
1124                 System.out.println("\n\n ==> Time needed to create object " + strObjName + " and instrument IoTDeviceAddress: " + result + "\n\n");
1125
1126                 // Closing streams
1127                 outStream.close();
1128                 inStream.close();
1129                 socket.close();
1130                 serverSocket.close();
1131         }
1132
1133
1134         /**
1135          * A private method to create controller objects
1136          *
1137          * @return  void
1138          */
1139         private void createDriverObjects() throws InterruptedException {
1140
1141                 // Create a list of threads
1142                 List<Thread> threads = new ArrayList<Thread>();
1143                 // Get the list of active controller objects and loop it
1144                 List<String> listActiveControllerObject = commHan.getActiveControllerObjectList();
1145                 for(String strObjName : listActiveControllerObject) {
1146
1147                         ObjectCreationInfo objCrtInfo = commHan.getObjectCreationInfo(strObjName);
1148                         Thread objectThread = new Thread(new Runnable() {
1149                                 public void run() {
1150                                         synchronized(this) {
1151                                                 try {
1152                                                         createObject(strObjName, objCrtInfo.getObjectClassName(), objCrtInfo.getObjectClassInterfaceName(),
1153                                                                 objCrtInfo.getObjectStubClassInterfaceName(), objCrtInfo.getIoTSlaveObjectHostAdd(), 
1154                                                                 commHan.getFieldObjectID(strObjName), commHan.getArrayFieldValues(strObjName), 
1155                                                                 commHan.getArrayFieldClasses(strObjName));
1156                                                 } catch (IOException                    | 
1157                                                                  ClassNotFoundException |
1158                                                                  InterruptedException ex) {
1159                                                         ex.printStackTrace();
1160                                                 }
1161                                         }
1162                                 }
1163                         });
1164                         threads.add(objectThread);
1165                         objectThread.start();
1166                 }
1167                 // Join all threads
1168                 for (Thread thread : threads) {
1169                         try {
1170                                 thread.join();
1171                         } catch (InterruptedException ex) {
1172                                 ex.printStackTrace();
1173                         }
1174                 }
1175         }       
1176
1177
1178         /**
1179          * A private method to instrument IoTSet
1180          *
1181          * @params  Map.Entry<String,Object>  Entry of map IoTSet instrumentation
1182          * @params  strFieldName              String field name
1183          * @params  strLanguage                           String language
1184          * @return  void
1185          */
1186         private void instrumentIoTSet(Map.Entry<String,Object> map, String strFieldName, String strObjControllerName, String strLanguage) 
1187                 throws IOException, ClassNotFoundException, InterruptedException {
1188                                 
1189                 // Get information from the set
1190                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
1191                 objInitHand.addField(strFieldName, IoTCommCode.CREATE_NEW_IOTSET);
1192
1193                 int iRows = setInstrumenter.numberOfRows();
1194                 for(int iRow=0; iRow<iRows; iRow++) {
1195                         // Get field classes and values
1196                         arrFieldClasses = setInstrumenter.fieldClasses(iRow);
1197                         arrFieldValues = setInstrumenter.fieldValues(iRow);
1198                         // Get object ID and class name
1199                         String strObjID = setInstrumenter.fieldObjectID(iRow);
1200                         strObjClassName = setInstrumenter.fieldEntryType(strObjID);
1201                         // Call the method to create an object
1202                         instrumentObject(strObjID, strObjControllerName, strLanguage);
1203                         objInitHand.addObjectIntoField(strFieldName, strIoTSlaveObjectHostAdd, strObjName,
1204                                 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName, commHan.getRMIRegPort(strObjName), 
1205                                 commHan.getRMIStubPort(strObjName));
1206                 }
1207         }
1208
1209
1210         /**
1211          * A private method to instrument IoTRelation
1212          *
1213          * @params  Map.Entry<String,Object>  Entry of map IoTRelation instrumentation
1214          * @params  strFieldName              String field name
1215          * @params  strLanguage                           String language
1216          * @return  void
1217          */
1218         private void instrumentIoTRelation(Map.Entry<String,Object> map, String strFieldName, String strObjControllerName, String strLanguage) 
1219                 throws IOException, ClassNotFoundException, InterruptedException {
1220
1221                         // Get information from the set
1222                 RelationInstrumenter relationInstrumenter = (RelationInstrumenter) map.getValue();
1223                 int iRows = relationInstrumenter.numberOfRows();
1224                 objInitHand.addField(strFieldName, IoTCommCode.CREATE_NEW_IOTRELATION);
1225
1226                 for(int iRow=0; iRow<iRows; iRow++) {
1227                         // Operate on the first set first
1228                         arrFieldClasses = relationInstrumenter.firstFieldClasses(iRow);
1229                         arrFieldValues = relationInstrumenter.firstFieldValues(iRow);
1230                         String strObjID = relationInstrumenter.firstFieldObjectID(iRow);
1231                         strObjClassName = relationInstrumenter.firstEntryFieldType(strObjID);
1232                         // Call the method to create an object
1233                         instrumentObject(strObjID, strObjControllerName, strLanguage);
1234                         // Get the first object controller host address
1235                         String strFirstIoTSlaveObjectHostAdd = strIoTSlaveObjectHostAdd;
1236                         objInitHand.addObjectIntoField(strFieldName, strIoTSlaveObjectHostAdd, strObjName,
1237                                 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName, 
1238                                 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
1239                         // Operate on the second set
1240                         arrFieldClasses = relationInstrumenter.secondFieldClasses(iRow);
1241                         arrFieldValues = relationInstrumenter.secondFieldValues(iRow);
1242                         strObjID = relationInstrumenter.secondFieldObjectID(iRow);
1243                         strObjClassName = relationInstrumenter.secondEntryFieldType(strObjID);
1244                         // Call the method to create an object
1245                         instrumentObject(strObjID, strObjControllerName, strLanguage);
1246                         // Get the second object controller host address
1247                         String strSecondIoTSlaveObjectHostAdd = strIoTSlaveObjectHostAdd;
1248                         objInitHand.addSecondObjectIntoField(strFieldName, strIoTSlaveObjectHostAdd, strObjName,
1249                                 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName, 
1250                                 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
1251                         // ROUTING POLICY: first and second controller objects in IoTRelation
1252                         routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strFirstIoTSlaveObjectHostAdd,
1253                                 strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
1254                         // ROUTING POLICY: Send the same routing policy to both the hosts
1255                         routerConfig.configureHostMainPolicies(strFirstIoTSlaveObjectHostAdd, strFirstIoTSlaveObjectHostAdd,
1256                                 strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
1257                         routerConfig.configureHostMainPolicies(strSecondIoTSlaveObjectHostAdd, strFirstIoTSlaveObjectHostAdd,
1258                                 strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
1259                 }
1260         }
1261
1262         /**
1263          * A method to reinitialize IoTSet and IoTRelation in the code based on ObjectInitHandler information
1264          *
1265          * @params  inStream                  ObjectInputStream communication
1266          * @params  outStream                 ObjectOutputStream communication
1267          * @return      void
1268          */
1269         private void initializeSetsAndRelationsJava(InputStream inStream, OutputStream outStream)  
1270                 throws IOException, ClassNotFoundException {
1271                 // Get list of fields
1272                 List<String> strFields = objInitHand.getListOfFields();
1273                 // Iterate on HostAddress
1274                 for(String str : strFields) {
1275                         IoTCommCode iotcommMsg = objInitHand.getFieldMessage(str);
1276                         if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTSET) {
1277                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTSET
1278                                 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, str);
1279                                 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet!", inStream, outStream);
1280                                 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1281                                 for (ObjectInitInfo objInitInfo : listObject) {
1282                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTSET
1283                                         commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTSET_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(),
1284                                                 objInitInfo.getObjectName(), objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(), 
1285                                                 objInitInfo.getObjectStubClassInterfaceName(), objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort()), 
1286                                                 "Get IoTSet object!", inStream, outStream);
1287
1288                                 }
1289                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTSET FIELD
1290                                 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD),
1291                                         "Renitialize IoTSet field!", inStream, outStream);
1292                         } else if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTRELATION) {
1293                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTRELATION
1294                                 Message msgCrtIoTRel = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTRELATION, str);
1295                                 commMasterToSlave(msgCrtIoTRel, "Create new IoTRelation!", inStream, outStream);
1296                                 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1297                                 List<ObjectInitInfo> listSecondObject = objInitHand.getSecondObjectInitInfo(str);
1298                                 Iterator it = listSecondObject.iterator();
1299                                 for (ObjectInitInfo objInitInfo : listObject) {
1300                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (FIRST OBJECT)
1301                                         commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTRELATION_FIRST_OBJECT, 
1302                                                 objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(), objInitInfo.getObjectClassName(),
1303                                                 objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1304                                                 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort()), 
1305                                                 "Get IoTRelation first object!", inStream, outStream);
1306                                         ObjectInitInfo objSecObj = (ObjectInitInfo) it.next();
1307                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (SECOND OBJECT)
1308                                         commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTRELATION_SECOND_OBJECT,
1309                                                 objSecObj.getIoTSlaveObjectHostAdd(), objSecObj.getObjectName(), objSecObj.getObjectClassName(),
1310                                                 objSecObj.getObjectClassInterfaceName(), objSecObj.getObjectStubClassInterfaceName(),
1311                                                 objSecObj.getRMIRegistryPort(), objSecObj.getRMIStubPort()), 
1312                                                 "Get IoTRelation second object!", inStream, outStream);
1313                                 }
1314                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTRELATION FIELD
1315                                 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTRELATION_FIELD),
1316                                         "Renitialize IoTRelation field!", inStream, outStream);
1317                         }
1318                 }
1319         }
1320
1321         /**
1322          * A method to reinitialize IoTSet and IoTRelation in the code based on ObjectInitHandler information
1323          *
1324          * @params  inStream                  ObjectInputStream communication
1325          * @params  outStream                 ObjectOutputStream communication
1326          * @return      void
1327          */
1328         private void initializeSetsAndRelationsCpp(InputStream inStream, OutputStream outStream)  
1329                 throws IOException, ClassNotFoundException {
1330                 // Get list of fields
1331                 List<String> strFields = objInitHand.getListOfFields();
1332                 // Iterate on HostAddress
1333                 for(String str : strFields) {
1334                         IoTCommCode iotcommMsg = objInitHand.getFieldMessage(str);
1335                         if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTSET) {
1336                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTSET
1337                                 createNewIoTSetCpp(str, outStream, inStream);
1338                                 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1339                                 for (ObjectInitInfo objInitInfo : listObject) {
1340                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTSET
1341                                         getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTSET_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(), 
1342                                                 objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1343                                                 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort(), outStream, inStream);
1344                                 }
1345                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTSET FIELD
1346                                 reinitializeIoTSetFieldCpp(outStream, inStream);
1347                         } else if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTRELATION) {
1348                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTRELATION
1349                                 // TODO: createNewIoTRelation needs to be created here!
1350                                 createNewIoTRelationCpp(str, outStream, inStream);
1351                                 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1352                                 List<ObjectInitInfo> listSecondObject = objInitHand.getSecondObjectInitInfo(str);
1353                                 Iterator it = listSecondObject.iterator();
1354                                 for (ObjectInitInfo objInitInfo : listObject) {
1355                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (FIRST OBJECT)
1356                                         getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTRELATION_FIRST_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(), 
1357                                                 objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1358                                                 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort(), outStream, inStream);
1359                                         ObjectInitInfo objSecObj = (ObjectInitInfo) it.next();
1360                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (SECOND OBJECT)
1361                                         getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTRELATION_SECOND_OBJECT, objSecObj.getIoTSlaveObjectHostAdd(), objSecObj.getObjectName(), 
1362                                                 objSecObj.getObjectClassName(), objSecObj.getObjectClassInterfaceName(), objSecObj.getObjectStubClassInterfaceName(),
1363                                                 objSecObj.getRMIRegistryPort(), objSecObj.getRMIStubPort(), outStream, inStream);
1364                                 }
1365                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTRELATION FIELD
1366                                 reinitializeIoTRelationFieldCpp(outStream, inStream);
1367                         }
1368                 }
1369         }
1370
1371         /**
1372          * A method to set router basic policies at once
1373          *
1374          * @param       strRouter String router name
1375          * @return      void
1376          */
1377         private void setRouterBasicPolicies(String strRouter) {
1378
1379                 String strMonitorHost = routerConfig.getIPFromMACAddress(STR_MONITORING_HOST);
1380                 routerConfig.configureRouterICMPPolicies(strRouter, strMonitorHost);
1381                 routerConfig.configureRouterDHCPPolicies(strRouter);
1382                 routerConfig.configureRouterDNSPolicies(strRouter);
1383                 routerConfig.configureRouterSSHPolicies(strRouter, strMonitorHost);
1384                 routerConfig.configureRejectPolicies(strRouter);
1385         }
1386
1387         /**
1388          * A method to set host basic policies at once
1389          *
1390          * @param       strHost String host name
1391          * @return      void
1392          */
1393         private void setHostBasicPolicies(String strHost) {
1394
1395                 String strMonitorHost = routerConfig.getIPFromMACAddress(STR_MONITORING_HOST);
1396                 routerConfig.configureHostDHCPPolicies(strHost);
1397                 routerConfig.configureHostDNSPolicies(strHost);
1398                 if (strHost.equals(strMonitorHost)) {
1399                 // Check if this is the monitoring host
1400                         routerConfig.configureHostICMPPolicies(strHost);
1401                         routerConfig.configureHostSSHPolicies(strHost);
1402                 } else {
1403                         routerConfig.configureHostICMPPolicies(strHost, strMonitorHost);
1404                         routerConfig.configureHostSSHPolicies(strHost, strMonitorHost);
1405                 }
1406                 // Apply SQL allowance policies to master host
1407                 if (strHost.equals(strIoTMasterHostAdd)) {
1408                         routerConfig.configureHostSQLPolicies(strHost);
1409                 }
1410                 routerConfig.configureRejectPolicies(strHost);
1411         }
1412
1413         /**
1414          * A method to create a thread for policy deployment
1415          *
1416          * @param  strRouterAddress             String router address to configure
1417          * @param  setHostAddresses             Set of strings for host addresses to configure
1418          * @return                              void
1419          */
1420         private void createPolicyThreads(String strRouterAddress, Set<String> setHostAddresses) throws IOException {
1421
1422                 // Create a list of threads
1423                 List<Thread> threads = new ArrayList<Thread>();
1424                 // Start threads for hosts
1425                 for(String strAddress : setHostAddresses) {
1426                         Thread policyThread = new Thread(new Runnable() {
1427                                 public void run() {
1428                                         synchronized(this) {
1429                                                 routerConfig.sendHostPolicies(strAddress);
1430                                         }
1431                                 }
1432                         });
1433                         threads.add(policyThread);
1434                         policyThread.start();
1435                         RuntimeOutput.print("Deploying policies for: " + strAddress, BOOL_VERBOSE);
1436                 }
1437                 // A thread for router
1438                 Thread policyThread = new Thread(new Runnable() {
1439                         public void run() {
1440                                 synchronized(this) {
1441                                         routerConfig.sendRouterPolicies(strRouterAddress);
1442                                 }
1443                         }
1444                 });
1445                 threads.add(policyThread);
1446                 policyThread.start();
1447                 RuntimeOutput.print("Deploying policies on router: " + strRouterAddress, BOOL_VERBOSE);         
1448                 // Join all threads
1449                 for (Thread thread : threads) {
1450                         try {
1451                                 thread.join();
1452                         } catch (InterruptedException ex) {
1453                                 ex.printStackTrace();
1454                         }
1455                 }
1456         }
1457
1458         /**
1459          * A method to create a thread for policy deployment
1460          *
1461          * @param  setHostAddresses             Set of strings for host addresses to configure
1462          * @return                              void
1463          */
1464         private void createMACPolicyThreads(Set<String> setHostAddresses) throws IOException {
1465
1466                 // Create a list of threads
1467                 List<Thread> threads = new ArrayList<Thread>();
1468                 // Start threads for hosts
1469                 for(String strAddress : setHostAddresses) {
1470                         Thread policyThread = new Thread(new Runnable() {
1471                                 public void run() {
1472                                         synchronized(this) {
1473                                                 processJailConfig.sendMACPolicies(strAddress);
1474                                         }
1475                                 }
1476                         });
1477                         threads.add(policyThread);
1478                         policyThread.start();
1479                         RuntimeOutput.print("Deploying MAC policies for: " + strAddress, BOOL_VERBOSE);
1480                 }
1481                 // Join all threads
1482                 for (Thread thread : threads) {
1483                         try {
1484                                 thread.join();
1485                         } catch (InterruptedException ex) {
1486                                 ex.printStackTrace();
1487                         }
1488                 }
1489         }
1490
1491
1492         /**
1493          * A method to send files to Java IoTSlave
1494          *
1495          * @params  strObjControllerName      String
1496          * @params  serverSocket              ServerSocket
1497          * @params  inStream                  ObjectInputStream communication
1498          * @params  outStream                 ObjectOutputStream communication
1499          * @return       void
1500          */     
1501         private void sendFileToJavaSlave(String strObjControllerName, ServerSocket serverSocket, 
1502                         InputStream _inStream, OutputStream _outStream) throws IOException, ClassNotFoundException {
1503
1504                 ObjectInputStream inStream = (ObjectInputStream) _inStream;
1505                 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
1506                 // Send .jar file
1507                 String strControllerJarName = strObjControllerName + STR_JAR_FILE_EXT;
1508                 String strControllerJarNamePath = STR_CONT_PATH + strObjControllerName + "/" +
1509                         strControllerJarName;
1510                 File file = new File(strControllerJarNamePath);
1511                 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, strControllerJarName, file.length()),
1512                         "Sending file!", inStream, outStream);
1513                 // Send file - Class file for object creation
1514                 sendFile(serverSocket.accept(), strControllerJarNamePath, file.length());
1515                 Message msgReply = (Message) inStream.readObject();
1516                 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
1517                 // Send .zip file if additional zip file is specified
1518                 String strObjCfgFile = strObjControllerName + STR_CFG_FILE_EXT;
1519                 String strObjCfgFilePath = STR_CONT_PATH + strObjControllerName + "/" + strObjCfgFile;
1520                 String strAdditionalFile = parseConfigFile(strObjCfgFilePath, STR_FILE_TRF_CFG);
1521                 if (strAdditionalFile.equals(STR_YES)) {
1522                         String strControllerCmpName = strObjControllerName + STR_ZIP_FILE_EXT;
1523                         String strControllerCmpNamePath = STR_CONT_PATH + strObjControllerName + "/" +
1524                                 strControllerCmpName;
1525                         file = new File(strControllerCmpNamePath);
1526                         commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, strControllerCmpName, file.length()),
1527                                 "Sending file!", inStream, outStream);
1528                         // Send file - Class file for object creation
1529                         sendFile(serverSocket.accept(), strControllerCmpNamePath, file.length());
1530                         msgReply = (Message) inStream.readObject();
1531                         RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
1532                 }
1533         }
1534
1535
1536         /**
1537          * A method to send files to C++ IoTSlave
1538          *
1539          * @return       void
1540          * TODO: Need to look into this (as of now, file transferred retains the "data" format, 
1541          * hence it is unreadable from outside world
1542          */
1543         private void sendFileToCppSlave(String sFilePath, String sFileName, Socket fileSocket, 
1544                         InputStream inStream, OutputStream outStream) throws IOException {
1545
1546                 sendCommCode(IoTCommCode.TRANSFER_FILE, outStream, inStream);
1547                 // Send file name
1548                 sendString(sFileName, outStream); recvAck(inStream);
1549                 File file = new File(sFilePath + sFileName);
1550                 int iFileLen = toIntExact(file.length());
1551                 RuntimeOutput.print("IoTMaster: Sending file " + sFileName + " with length " + iFileLen + " bytes...", BOOL_VERBOSE);
1552                 // Send file length
1553                 sendInteger(iFileLen, outStream); recvAck(inStream);
1554                 RuntimeOutput.print("IoTMaster: Sent file size!", BOOL_VERBOSE);
1555                 byte[] bytFile = new byte[iFileLen];
1556                 InputStream inFileStream = new FileInputStream(file);
1557                 RuntimeOutput.print("IoTMaster: Opened file!", BOOL_VERBOSE);
1558
1559                 OutputStream outFileStream = fileSocket.getOutputStream();
1560                 RuntimeOutput.print("IoTMaster: Got output stream!", BOOL_VERBOSE);
1561                 int iCount;
1562                 while ((iCount = inFileStream.read(bytFile)) > 0) {
1563                         outFileStream.write(bytFile, 0, iCount);
1564                 }
1565                 RuntimeOutput.print("IoTMaster: File sent!", BOOL_VERBOSE);
1566                 recvAck(inStream);
1567         }
1568
1569
1570         /**
1571          * A method to send files to C++ IoTSlave (now master using Process() to start 
1572          * file transfer using scp)
1573          *
1574          * @return       void
1575          */
1576         private void sendFileToCppSlave(String sFilePath, String sFileName) throws IOException {
1577
1578                 // Construct shell command to transfer file     
1579                 String sFile = sFilePath + sFileName;
1580                 String strCmdSend = STR_SCP + " " + sFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_SLAVE_DIR;
1581                 runCommand(strCmdSend);
1582                 RuntimeOutput.print("IoTMaster: Executing: " + strCmdSend, BOOL_VERBOSE);
1583                 // Unzip file
1584                 String strCmdUnzip = STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " +
1585                                         STR_SLAVE_DIR + " sudo unzip -o " + sFileName + ";";
1586                 runCommand(strCmdUnzip);
1587                 RuntimeOutput.print("IoTMaster: Executing: " + strCmdUnzip, BOOL_VERBOSE);
1588         }
1589
1590
1591         /**
1592          * runCommand() method runs shell command
1593          *
1594          * @param   strCommand  String that contains command line
1595          * @return  void
1596          */
1597         private void runCommand(String strCommand) {
1598
1599                 try {
1600                         Runtime runtime = Runtime.getRuntime();
1601                         Process process = runtime.exec(strCommand);
1602                         process.waitFor();
1603                 } catch (IOException ex) {
1604                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
1605                         ex.printStackTrace();
1606                 } catch (InterruptedException ex) {
1607                         System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
1608                         ex.printStackTrace();
1609                 }
1610         }
1611
1612
1613         /**
1614          * Construct command line for Java IoTSlave
1615          *
1616          * @return       String
1617          */
1618         private String getCmdJavaIoTSlave(String strObjControllerName) {
1619
1620                 // Create an Shell executable
1621                 String strJavaCommand = STR_SHELL_HEADER + "\nexec " + STR_JAVA_PATH + " " + STR_JVM_INIT_HEAP_SIZE + " " + 
1622                                         STR_JVM_MAX_HEAP_SIZE + " " + STR_CLS_PATH + " " + STR_RMI_PATH + " " + STR_IOT_SLAVE_CLS + " " + 
1623                                         strIoTMasterHostAdd + " " + commHan.getComPort(strObjControllerName) + " " +
1624                                         commHan.getRMIRegPort(strObjControllerName) + " " + commHan.getRMIStubPort(strObjControllerName) + 
1625                                         " > " + STR_LOG_FILE_PATH + strObjControllerName + ".log &";
1626                 String shellFile = "./" + strObjControllerName + STR_SHELL_FILE_EXT;
1627                 createWrapperShellScript(strJavaCommand, shellFile);
1628                 // Send the file to the compute node
1629                 String strCmdSend = "scp " + shellFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_RUNTIME_DIR;
1630                 runCommand(strCmdSend);
1631                 System.out.println("IoTMaster: Sending main controller shell file: " + strCmdSend);
1632                 return STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
1633         }
1634
1635
1636         /**
1637          * Construct command line for C++ IoTSlave
1638          *
1639          * @return       String
1640          */
1641         private String getCmdCppIoTSlave(String strObjControllerName) {
1642
1643                 return STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " +
1644                                         STR_SLAVE_DIR + " sudo " + STR_IOTSLAVE_CPP + " " + strIoTMasterHostAdd + " " +
1645                                         commHan.getComPort(strObjControllerName) + " " + strObjControllerName;
1646         }
1647
1648
1649         /**
1650          * sendInteger() sends an integer in bytes
1651          */
1652         public void sendInteger(int intSend, OutputStream outStream) throws IOException {
1653
1654                 BufferedOutputStream output = (BufferedOutputStream) outStream;
1655                 // Transform integer into bytes
1656                 ByteBuffer bb = ByteBuffer.allocate(INT_SIZE);
1657                 bb.putInt(intSend);
1658                 // Send the byte array
1659                 output.write(bb.array(), 0, INT_SIZE);
1660                 output.flush();
1661         }
1662
1663
1664         /**
1665          * recvInteger() receives integer in bytes
1666          */
1667         public int recvInteger(InputStream inStream) throws IOException {
1668
1669                 BufferedInputStream input = (BufferedInputStream) inStream;
1670                 // Wait until input is available
1671                 while(input.available() == 0);
1672                 // Read integer - 4 bytes
1673                 byte[] recvInt = new byte[INT_SIZE];
1674                 input.read(recvInt, 0, INT_SIZE);
1675                 int retVal = ByteBuffer.wrap(recvInt).getInt();
1676
1677                 return retVal;
1678         }
1679
1680
1681         /**
1682          * recvString() receives String in bytes
1683          */
1684         public String recvString(InputStream inStream) throws IOException {
1685
1686                 BufferedInputStream input = (BufferedInputStream) inStream;
1687                 int strLen = recvInteger(inStream);
1688                 // Wait until input is available
1689                 while(input.available() == 0);
1690                 // Read String per strLen
1691                 byte[] recvStr = new byte[strLen];
1692                 input.read(recvStr, 0, strLen);
1693                 String retVal = new String(recvStr);
1694
1695                 return retVal;
1696         }
1697
1698
1699         /**
1700          * sendString() sends a String in bytes
1701          */
1702         public void sendString(String strSend, OutputStream outStream) throws IOException {
1703
1704                 BufferedOutputStream output = (BufferedOutputStream) outStream;
1705                 // Transform String into bytes
1706                 byte[] strSendBytes = strSend.getBytes();
1707                 int strLen = strSend.length();
1708                 // Send the string length first
1709                 sendInteger(strLen, outStream);
1710                 // Send the byte array
1711                 output.write(strSendBytes, 0, strLen);
1712                 output.flush();
1713         }
1714
1715
1716         /**
1717          * Convert integer to enum
1718          */
1719         public IoTCommCode getCode(int intCode) throws IOException {
1720
1721                 IoTCommCode[] commCode = IoTCommCode.values();
1722                 IoTCommCode retCode = commCode[intCode];
1723                 return retCode;
1724
1725         }
1726
1727
1728         /**
1729          * Receive ACK
1730          */
1731         public synchronized boolean recvAck(InputStream inStream) throws IOException {
1732
1733                 int intAck = recvInteger(inStream);
1734                 IoTCommCode codeAck = getCode(intAck);
1735                 if (codeAck == IoTCommCode.ACKNOWLEDGED)
1736                         return true;
1737                 return false;
1738
1739         }
1740
1741
1742         /**
1743          * Send END
1744          */
1745         public void sendEndTransfer(OutputStream outStream) throws IOException {
1746
1747                 int endCode = IoTCommCode.END_TRANSFER.ordinal();
1748                 sendInteger(endCode, outStream);
1749         }
1750
1751
1752         /**
1753          * Send communication code to C++
1754          */
1755         public void sendCommCode(IoTCommCode inpCommCode, OutputStream outStream, InputStream inStream) throws IOException {
1756
1757
1758                 IoTCommCode commCode = inpCommCode;
1759                 int intCode = commCode.ordinal();
1760                 // TODO: delete this later
1761                 System.out.println("DEBUG: Sending " + commCode + " with ordinal: " + intCode);
1762                 sendInteger(intCode, outStream); recvAck(inStream);
1763         }
1764
1765
1766         /**
1767          * Create a main controller object for C++
1768          */
1769         public void createMainObjectCpp(String strObjControllerName, OutputStream outStream, InputStream inStream) throws IOException {
1770
1771                 sendCommCode(IoTCommCode.CREATE_MAIN_OBJECT, outStream, inStream);
1772                 String strMainObjName = strObjControllerName;
1773                 sendString(strMainObjName, outStream); recvAck(inStream);
1774                 RuntimeOutput.print("IoTMaster: Create a main object: " + strMainObjName, BOOL_VERBOSE);
1775         }
1776
1777
1778         /**
1779          * A helper function that converts Class into String
1780          *
1781          * @param  strDataType  String MySQL data type
1782          * @return              Class
1783          */
1784         public String getClassConverted(Class<?> cls) {
1785
1786                 if (cls == String.class) {
1787                         return "string";
1788                 } else if (cls == int.class) {
1789                         return "int";
1790                 } else {
1791                         return null;
1792                 }
1793         }
1794
1795
1796         /**
1797          * A helper function that converts Object into String for transfer to C++ slave
1798          *
1799          * @param  obj           Object to be converted
1800          * @param  strClassType  String Java Class type
1801          * @return               Object
1802          */
1803         public String getObjectConverted(Object obj) {
1804
1805                 if (obj instanceof String) {
1806                         return (String) obj;
1807                 } else if (obj instanceof Integer) {
1808                         return Integer.toString((Integer) obj);
1809                 } else {
1810                         return null;
1811                 }
1812         }
1813
1814
1815         /**
1816          * Create a driver object for C++
1817          */
1818         public void createObjectCpp(String strObjName, String strObjClassName, String strObjClassInterfaceName, String strIoTSlaveObjectHostAdd, 
1819                 Integer iRMIRegistryPort, Integer iRMIStubPort, Object[] arrFieldValues, Class[] arrFieldClasses, 
1820                 OutputStream outStream, InputStream inStream) throws IOException {
1821
1822                 sendCommCode(IoTCommCode.CREATE_OBJECT, outStream, inStream);
1823                 RuntimeOutput.print("IoTMaster: Send request to create a driver object... ", BOOL_VERBOSE);
1824                 RuntimeOutput.print("IoTMaster: Driver object name: " + strObjName, BOOL_VERBOSE);
1825                 sendString(strObjName, outStream); recvAck(inStream);
1826                 RuntimeOutput.print("IoTMaster: Driver object class name: " + strObjClassName, BOOL_VERBOSE);
1827                 sendString(strObjClassName, outStream); recvAck(inStream);
1828                 RuntimeOutput.print("IoTMaster: Driver object interface name: " + strObjClassInterfaceName, BOOL_VERBOSE);
1829                 sendString(strObjStubClsIntfaceName, outStream); recvAck(inStream);
1830                 RuntimeOutput.print("IoTMaster: Driver object skeleton class name: " + strObjClassInterfaceName + STR_SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
1831                 sendString(strObjClassInterfaceName + STR_SKEL_CLASS_SUFFIX, outStream); recvAck(inStream);
1832                 RuntimeOutput.print("IoTMaster: Driver object registry port: " + iRMIRegistryPort, BOOL_VERBOSE);
1833                 sendInteger(iRMIRegistryPort, outStream); recvAck(inStream);
1834                 RuntimeOutput.print("IoTMaster: Driver object stub port: " + iRMIStubPort, BOOL_VERBOSE);
1835                 sendInteger(iRMIStubPort, outStream); recvAck(inStream);
1836                 int numOfArgs = arrFieldValues.length;
1837                 RuntimeOutput.print("IoTMaster: Send constructor arguments! Number of arguments: " + numOfArgs, BOOL_VERBOSE);
1838                 sendInteger(numOfArgs, outStream); recvAck(inStream);
1839                 for(Object obj : arrFieldValues) {
1840                         String str = getObjectConverted(obj);
1841                         sendString(str, outStream); recvAck(inStream);
1842                 }
1843                 RuntimeOutput.print("IoTMaster: Send constructor argument classes!", BOOL_VERBOSE);
1844                 for(Class cls : arrFieldClasses) {
1845                         String str = getClassConverted(cls);
1846                         sendString(str, outStream); recvAck(inStream);
1847                 }
1848         }
1849
1850
1851         /**
1852          * Create new IoTSet for C++
1853          */
1854         public void createNewIoTSetCpp(String strObjFieldName, OutputStream outStream, InputStream inStream) throws IOException {
1855
1856                 sendCommCode(IoTCommCode.CREATE_NEW_IOTSET, outStream, inStream);
1857                 RuntimeOutput.print("IoTMaster: Creating new IoTSet...", BOOL_VERBOSE);
1858                 RuntimeOutput.print("IoTMaster: Send object field name: " + strObjFieldName, BOOL_VERBOSE);
1859                 sendString(strObjFieldName, outStream); recvAck(inStream);
1860         }
1861
1862
1863         /**
1864          * Create new IoTRelation for C++
1865          */
1866         public void createNewIoTRelationCpp(String strObjFieldName, OutputStream outStream, InputStream inStream) throws IOException {
1867
1868                 sendCommCode(IoTCommCode.CREATE_NEW_IOTRELATION, outStream, inStream);
1869                 RuntimeOutput.print("IoTMaster: Creating new IoTRelation...", BOOL_VERBOSE);
1870                 RuntimeOutput.print("IoTMaster: Send object field name: " + strObjFieldName, BOOL_VERBOSE);
1871                 sendString(strObjFieldName, outStream); recvAck(inStream);
1872         }
1873
1874
1875         /**
1876          * Get a IoTDeviceAddress object for C++
1877          */
1878         public void getDeviceIoTSetObjectCpp(OutputStream outStream, InputStream inStream,
1879                         String strDeviceAddress, int iSourcePort, int iDestPort, boolean bSourceWildCard, boolean bDestWildCard) throws IOException {
1880
1881                 sendCommCode(IoTCommCode.GET_DEVICE_IOTSET_OBJECT, outStream, inStream);
1882                 RuntimeOutput.print("IoTMaster: Getting IoTDeviceAddress...", BOOL_VERBOSE);
1883                 sendString(strDeviceAddress, outStream); recvAck(inStream);
1884                 sendInteger(iSourcePort, outStream); recvAck(inStream);
1885                 sendInteger(iDestPort, outStream); recvAck(inStream);
1886                 int iSourceWildCard = (bSourceWildCard ? 1 : 0);
1887                 sendInteger(iSourceWildCard, outStream); recvAck(inStream);
1888                 int iDestWildCard = (bDestWildCard ? 1 : 0);
1889                 sendInteger(iDestWildCard, outStream); recvAck(inStream);
1890                 RuntimeOutput.print("IoTMaster: Send device address: " + strDeviceAddress, BOOL_VERBOSE);
1891         }
1892
1893
1894         /**
1895          * Get a IoTSet content object for C++
1896          */
1897         public void getIoTSetRelationObjectCpp(IoTCommCode iotCommCode, String strIoTSlaveHostAddress, String strObjectName, String strObjectClassName, 
1898                         String strObjectClassInterfaceName, String strObjectStubClassInterfaceName, int iRMIRegistryPort, int iRMIStubPort, 
1899                         OutputStream outStream, InputStream inStream) throws IOException {
1900
1901                 sendCommCode(iotCommCode, outStream, inStream);
1902                 RuntimeOutput.print("IoTMaster: Getting IoTSet object content...", BOOL_VERBOSE);
1903                 // Send info
1904                 RuntimeOutput.print("IoTMaster: Send host address: " + strIoTSlaveHostAddress, BOOL_VERBOSE);
1905                 sendString(strIoTSlaveHostAddress, outStream); recvAck(inStream);
1906                 RuntimeOutput.print("IoTMaster: Driver object name: " + strObjectName, BOOL_VERBOSE);
1907                 sendString(strObjectName, outStream); recvAck(inStream);
1908                 RuntimeOutput.print("IoTMaster: Driver object class name: " + strObjectClassName, BOOL_VERBOSE);
1909                 sendString(strObjectClassName, outStream); recvAck(inStream);
1910                 RuntimeOutput.print("IoTMaster: Driver object interface name: " + strObjectClassInterfaceName, BOOL_VERBOSE);
1911                 sendString(strObjectClassInterfaceName, outStream); recvAck(inStream);
1912                 RuntimeOutput.print("IoTMaster: Driver object stub class name: " + strObjectStubClassInterfaceName + STR_STUB_CLASS_SUFFIX, BOOL_VERBOSE);
1913                 sendString(strObjectStubClassInterfaceName + STR_STUB_CLASS_SUFFIX, outStream); recvAck(inStream);
1914                 RuntimeOutput.print("IoTMaster: Driver object registry port: " + iRMIRegistryPort, BOOL_VERBOSE);
1915                 sendInteger(iRMIRegistryPort, outStream); recvAck(inStream);
1916                 RuntimeOutput.print("IoTMaster: Driver object stub port: " + iRMIStubPort, BOOL_VERBOSE);
1917                 sendInteger(iRMIStubPort, outStream); recvAck(inStream);
1918         }
1919
1920
1921         /**
1922          * Reinitialize IoTRelation field for C++
1923          */
1924         private void reinitializeIoTRelationFieldCpp(OutputStream outStream, InputStream inStream) throws IOException {
1925
1926                 RuntimeOutput.print("IoTMaster: About to Reinitialize IoTRelation field!", BOOL_VERBOSE);
1927                 sendCommCode(IoTCommCode.REINITIALIZE_IOTRELATION_FIELD, outStream, inStream);
1928                 RuntimeOutput.print("IoTMaster: Reinitialize IoTRelation field!", BOOL_VERBOSE);
1929         }
1930
1931
1932         /**
1933          * Reinitialize IoTSet field for C++
1934          */
1935         private void reinitializeIoTSetFieldCpp(OutputStream outStream, InputStream inStream) throws IOException {
1936
1937                 RuntimeOutput.print("IoTMaster: About to Reinitialize IoTSet field!", BOOL_VERBOSE);
1938                 sendCommCode(IoTCommCode.REINITIALIZE_IOTSET_FIELD, outStream, inStream);
1939                 RuntimeOutput.print("IoTMaster: Reinitialize IoTSet field!", BOOL_VERBOSE);
1940         }
1941
1942
1943         /**
1944          * Create driver object for C++
1945          */
1946         private void createDriverObjectCpp(OutputStream outStream, InputStream inStream) throws IOException {
1947
1948                 sendCommCode(IoTCommCode.CREATE_DRIVER_OBJECT, outStream, inStream);
1949                 RuntimeOutput.print("IoTMaster: Send command to create driver object!", BOOL_VERBOSE);
1950         }
1951
1952
1953         /**
1954          * Invoke init() for C++
1955          */
1956         private void invokeInitMethodCpp(OutputStream outStream, InputStream inStream) throws IOException {
1957
1958                 sendCommCode(IoTCommCode.INVOKE_INIT_METHOD, outStream, inStream);
1959                 RuntimeOutput.print("IoTMaster: Invoke init method!", BOOL_VERBOSE);
1960         }
1961
1962
1963         /**
1964          * End session for C++
1965          */
1966         public void endSessionCpp(OutputStream outStream) throws IOException {
1967
1968                 // Send message to end session
1969                 IoTCommCode endSessionCode = IoTCommCode.END_SESSION;
1970                 int intCode = endSessionCode.ordinal();
1971                 sendInteger(intCode, outStream);
1972                 //RuntimeOutput.print("IoTMaster: Send request to create a main object: " + strObjName, BOOL_VERBOSE);
1973                 RuntimeOutput.print("IoTMaster: Send request to end session!", BOOL_VERBOSE);
1974         }
1975
1976
1977         /**
1978          * A method to assign objects to multiple JVMs, including
1979          * the controller/device object that uses other objects
1980          * in IoTSet and IoTRelation
1981          *
1982          * @return       void
1983          */
1984         private void createObjects() {
1985
1986                 // PROFILING
1987                 long start = 0;
1988                 long result = 0;
1989
1990                 try {
1991                         // Extract hostname for this IoTMaster from MySQL DB
1992                         strIoTMasterHostAdd = routerConfig.getIPFromMACAddress(STR_MASTER_MAC_ADD);
1993                         // Loop as we can still find controller/device classes
1994                         for(int i=0; i<strObjectNames.length; i++) {
1995                                 // PROFILING
1996                                 start = System.currentTimeMillis();
1997
1998                                 // Assign a new list of PrintWriter objects
1999                                 routerConfig.renewPrintWriter();
2000                                 // Get controller names one by one
2001                                 String strObjControllerName = strObjectNames[i];
2002                                 // Use LoadBalancer to assign a host address
2003                                 //strIoTSlaveControllerHostAdd = lbIoT.selectHost();
2004                                 strIoTSlaveControllerHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
2005                                 if (strIoTSlaveControllerHostAdd == null)
2006                                         throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
2007                                 // == START INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
2008                                 // Add port connection and get port numbers
2009                                 // Naming for objects ProximitySensor becomes ProximitySensor0, ProximitySensor1, etc.
2010                                 commHan.addPortConnection(strIoTSlaveControllerHostAdd, strObjControllerName);
2011                                 // ROUTING POLICY: IoTMaster and main controller object
2012                                 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTMasterHostAdd,
2013                                         strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2014                                 // ROUTING POLICY: Send the same routing policy to both the hosts
2015                                 routerConfig.configureHostMainPolicies(strIoTMasterHostAdd, strIoTMasterHostAdd,
2016                                         strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2017                                 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTMasterHostAdd,
2018                                         strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2019                                 // Read config file
2020                                 String strControllerCfg = STR_CONT_PATH + strObjControllerName + "/" + strObjControllerName + STR_CFG_FILE_EXT;
2021                                 STR_LANGUAGE_CONTROLLER = parseConfigFile(strControllerCfg, STR_LANGUAGE);
2022                                 if(STR_LANGUAGE_CONTROLLER == null)
2023                                         throw new Error("IoTMaster: Language specification missing in config file: " + strControllerCfg);
2024                                 // Construct ssh command line and create a controller thread for e.g. AcmeProximity
2025                                 String strSSHCommand = null;
2026                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2027                                         strSSHCommand = getCmdJavaIoTSlave(strObjControllerName);
2028                                 else if(STR_LANGUAGE_CONTROLLER.equals(STR_CPP))
2029                                         strSSHCommand = getCmdCppIoTSlave(strObjControllerName);
2030                                 else
2031                                         throw new Error("IoTMaster: Language specification not recognized: " + STR_LANGUAGE_CONTROLLER);
2032                                 RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
2033                                 createThread(strSSHCommand);
2034                                 // Wait for connection
2035                                 // Create a new socket for communication
2036                                 ServerSocket serverSocket = new ServerSocket(commHan.getComPort(strObjControllerName));
2037                                 Socket socket = serverSocket.accept();
2038                                 InputStream inStream = null;
2039                                 OutputStream outStream = null;
2040                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2041                                         inStream = new ObjectInputStream(socket.getInputStream());
2042                                         outStream = new ObjectOutputStream(socket.getOutputStream());
2043                                 } else {        // At this point the language is certainly C++, otherwise would've complained above
2044                                         inStream = new BufferedInputStream(socket.getInputStream());
2045                                         outStream = new BufferedOutputStream(socket.getOutputStream());
2046                                         recvAck(inStream);
2047                                 }
2048                                 RuntimeOutput.print("IoTMaster: Communication established!", BOOL_VERBOSE);
2049
2050                                 // PROFILING
2051                                 result = System.currentTimeMillis()-start;
2052                                 System.out.println("\n\n ==> From start until after SSH for main controller: " + result);
2053                                 // PROFILING
2054                                 start = System.currentTimeMillis();
2055
2056                                 // Send files for every controller class
2057                                 // e.g. AcmeProximity.jar and AcmeProximity.zip
2058                                 String strControllerClassName = strObjControllerName + STR_CLS_FILE_EXT;
2059                                 String strControllerClassNamePath = STR_CONT_PATH + strObjControllerName + "/" +
2060                                         strControllerClassName;
2061
2062                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2063                                         sendFileToJavaSlave(strObjControllerName, serverSocket, inStream, outStream);
2064                                         // Create main controller/device object
2065                                         commMasterToSlave(new MessageCreateMainObject(IoTCommCode.CREATE_MAIN_OBJECT, strObjControllerName),
2066                                                 "Create main object!", inStream, outStream);
2067                                 } else {
2068                                         String strControllerZipFile = strObjControllerName + STR_ZIP_FILE_EXT;
2069                                         String strControllerFilePath = STR_CONT_PATH + strObjControllerName + "/";
2070                                         sendFileToCppSlave(strControllerFilePath, strControllerZipFile);
2071                                         createMainObjectCpp(strObjControllerName, outStream, inStream);
2072                                 }
2073                                 // Write basic MAC policies for controller
2074                                 //String strFileName = STR_MAC_POL_PATH + strObjControllerName + STR_MAC_POLICY_EXT;
2075                                 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
2076                                         String strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
2077                                         processJailConfig.configureProcessJailControllerPolicies(strObjControllerName, strFileName, 
2078                                                 strIoTMasterHostAdd, commHan.getComPort(strObjControllerName));
2079                                 }
2080                                 // PROFILING
2081                                 result = System.currentTimeMillis()-start;
2082                                 System.out.println("\n\n ==> From IoTSlave start until main controller object is created: " + result);
2083                                 System.out.println(" ==> Including file transfer times!\n\n");
2084                                 // PROFILING
2085                                 start = System.currentTimeMillis();
2086
2087                                 // == END INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
2088                                 // Instrumenting one file
2089                                 RuntimeOutput.print("IoTMaster: Opening class file: " + strControllerClassName, BOOL_VERBOSE);
2090                                 RuntimeOutput.print("IoTMaster: Class file path: " + strControllerClassNamePath, BOOL_VERBOSE);
2091                                 HashMap<String,Object> hmControllerFieldObjects = null;
2092                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2093                                         FileInputStream fis = new FileInputStream(strControllerClassNamePath);
2094                                         ClassReader cr = new ClassReader(fis);
2095                                         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
2096                                         ClassRuntimeInstrumenterMaster crim = new ClassRuntimeInstrumenterMaster(cw, null, BOOL_VERBOSE);
2097                                         cr.accept(crim, 0);
2098                                         fis.close();
2099                                         hmControllerFieldObjects = crim.getFieldObjects();
2100                                 } else {
2101                                         String strControllerConfigFile = STR_CONT_PATH + strObjControllerName + "/" + strObjControllerName + STR_CFG_FILE_EXT;
2102                                         CRuntimeInstrumenterMaster crim = new CRuntimeInstrumenterMaster(strControllerConfigFile, null, BOOL_VERBOSE);
2103                                         hmControllerFieldObjects = crim.getFieldObjects();
2104                                 }
2105                                 // Get the object and the class names
2106                                 // Build objects for IoTSet and IoTRelation fields in the controller/device classes
2107                                 //HashMap<String,Object> hmControllerFieldObjects = crim.getFieldObjects();
2108                                 for(Map.Entry<String,Object> map : hmControllerFieldObjects.entrySet()) {
2109                                         RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
2110                                         // Iterate over HashMap and choose between processing
2111                                         // SetInstrumenter vs. RelationInstrumenter
2112                                         String strFieldName = map.getKey();
2113                                         String strClassName = map.getValue().getClass().getName();
2114                                         if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
2115                                                 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
2116                                                 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) { 
2117                                                         String strErrMsg = "IoTMaster: Controller object" +
2118                                                                 " cannot have IoTSet<IoTDeviceAddress>!";
2119                                                         throw new Error(strErrMsg);
2120                                                 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) { 
2121                                                         String strErrMsg = "IoTMaster: Controller object" +
2122                                                                 " cannot have IoTSet<ZigbeeAddress>!";
2123                                                         throw new Error(strErrMsg);
2124                                                 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) { 
2125                                                 // Instrument the IoTAddress
2126                                                         setRouterPolicyIoTSetAddress(strFieldName, map, strIoTSlaveControllerHostAdd, strObjControllerName);
2127                                                         instrumentIoTSetAddress(strFieldName, strFieldName, inStream, outStream, STR_LANGUAGE_CONTROLLER);
2128                                                 } else {
2129                                                 // Any other cases
2130                                                         instrumentIoTSet(map, strFieldName, strObjControllerName, STR_LANGUAGE_CONTROLLER);
2131                                                 }
2132                                         } else if (strClassName.equals(STR_REL_INSTRUMENTER_CLS)) {
2133                                                 instrumentIoTRelation(map, strFieldName, strObjControllerName, STR_LANGUAGE_CONTROLLER);
2134                                         }
2135                                 }
2136                                 // Combine controller MAC policies with the main policy file for the host
2137                                 String strTempFileName = "./" + strObjControllerName + STR_MAC_POLICY_EXT;
2138                                 processJailConfig.combineControllerMACPolicies(strIoTSlaveControllerHostAdd, strObjControllerName, strTempFileName);
2139                                 processJailConfig.close();
2140
2141                                 // PROFILING
2142                                 result = System.currentTimeMillis()-start;
2143                                 System.out.println("\n\n ==> Time needed to instrument device driver objects: " + result + "\n\n");
2144                                 System.out.println(" ==> #Objects: " + commHan.getActiveControllerObjectList().size() + "\n\n");
2145
2146                                 // PROFILING
2147                                 start = System.currentTimeMillis();
2148
2149                                 // ROUTING POLICY: Deploy basic policies if this is the last controller
2150                                 if (i == strObjectNames.length-1) {
2151                                         // ROUTING POLICY: implement basic policies to reject all other irrelevant traffics
2152                                         for(String s: commHan.getHosts()) {
2153                                                 setHostBasicPolicies(s);
2154                                         }
2155                                         // We retain all the basic policies for router, 
2156                                         // but we delete the initial allowance policies for internal all TCP and UDP communications
2157                                         setRouterBasicPolicies(STR_ROUTER_ADD);
2158                                 }
2159                                 // Close access to policy files and deploy policies
2160                                 routerConfig.close();
2161                                 // Deploy the policy
2162                                 HashSet<String> setAddresses = new HashSet<String>(commHan.getHosts());
2163                                 setAddresses.add(strIoTMasterHostAdd);
2164                                 createPolicyThreads(STR_ROUTER_ADD, setAddresses);
2165
2166                                 // PROFILING
2167                                 result = System.currentTimeMillis()-start;
2168                                 System.out.println("\n\n ==> Time needed to send policy files and deploy them : " + result + "\n\n");
2169
2170                                 // PROFILING
2171                                 start = System.currentTimeMillis();
2172
2173                                 // Separating object creations and Set/Relation initializations
2174                                 createDriverObjects();
2175
2176                                 // PROFILING
2177                                 result = System.currentTimeMillis()-start;
2178                                 System.out.println("\n\n ==> Time needed to instantiate objects: " + result + "\n\n");
2179                                 // PROFILING
2180                                 start = System.currentTimeMillis();
2181
2182                                 // Sets and relations initializations
2183                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2184                                         initializeSetsAndRelationsJava(inStream, outStream);
2185                                 else
2186                                         initializeSetsAndRelationsCpp(inStream, outStream);;
2187
2188                                 // PROFILING
2189                                 result = System.currentTimeMillis()-start;
2190                                 System.out.println("\n\n ==> Time needed to initialize sets and relations: " + result + "\n\n");
2191
2192                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2193                                         // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO EXECUTE INIT METHOD
2194                                         commMasterToSlave(new MessageSimple(IoTCommCode.INVOKE_INIT_METHOD), "Invoke init() method!", inStream, outStream);
2195                                 else
2196                                         invokeInitMethodCpp(outStream, inStream);
2197                                 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO END PROCESS
2198                                 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2199                                         ObjectOutputStream oStream = (ObjectOutputStream) outStream;
2200                                         oStream.writeObject(new MessageSimple(IoTCommCode.END_SESSION));
2201                                 } else  // C++ side will wait until the program finishes, it's not generating a separate thread for now
2202                                         //endSessionCpp(outStream);
2203                                 outStream.close();
2204                                 inStream.close();
2205                                 socket.close();
2206                                 serverSocket.close();
2207                                 commHan.printLists();
2208                                 lbIoT.printHostInfo();
2209                                 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
2210                                         createMACPolicyThreads(setAddresses);
2211                         }
2212
2213                 } catch (IOException          |
2214                                  InterruptedException |
2215                                  ClassNotFoundException ex) {
2216                         System.out.println("IoTMaster: Exception: "
2217                                 + ex.getMessage());
2218                         ex.printStackTrace();
2219                 }
2220         }
2221
2222         public static void main(String args[]) {
2223
2224                 // Detect the available controller/device classes
2225                 // Input args[] should be used to list the controllers/devices
2226                 // e.g. java IoTMaster AcmeProximity AcmeThermostat AcmeVentController
2227                 IoTMaster iotMaster = new IoTMaster(args);
2228                 // Read config file
2229                 iotMaster.parseIoTMasterConfigFile();
2230                 // Initialize CommunicationHandler, LoadBalancer, and RouterConfig
2231                 iotMaster.initLiveDataStructure();
2232                 // Create objects
2233                 iotMaster.createObjects();
2234         }
2235 }