Fixing 2 issues in LifxLightBulb driver: 1) Detached thread handling (need to pass...
[iot2.git] / iotjava / iotruntime / slave / IoTSlave.java
1 package iotruntime.slave;
2
3 import iotruntime.*;
4 import iotruntime.zigbee.*;
5 import iotruntime.messages.*;
6 import iotruntime.master.RuntimeOutput;
7
8 // Java packages
9 import java.io.File;
10 import java.io.FileInputStream;
11 import java.io.FileOutputStream;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14 import java.io.InputStream;
15 import java.io.OutputStream;
16 import java.io.IOException;
17 import java.io.FileNotFoundException;
18 import java.lang.ClassNotFoundException;
19 import java.lang.Class;
20 import java.lang.reflect.*;
21 import java.lang.ClassLoader;
22 import java.net.InetAddress;
23 import java.net.Socket;
24 import java.net.UnknownHostException;
25 import java.net.URL;
26 import java.net.URLClassLoader;
27 import java.rmi.registry.LocateRegistry;
28 import java.rmi.registry.Registry;
29 import java.rmi.Remote;
30 import java.rmi.RemoteException;
31 import java.rmi.AlreadyBoundException;
32 import java.rmi.NotBoundException;
33 import java.rmi.server.UnicastRemoteObject;
34 import java.util.Arrays;
35 import java.util.Properties;
36 import java.util.HashMap;
37 import java.util.Map;
38
39 // Zip/Unzip utility
40 import net.lingala.zip4j.exception.ZipException;
41 import net.lingala.zip4j.core.ZipFile;
42
43 /** Class IoTSlave is run by IoTMaster on a different JVM's.
44  *  It needs to respond to IoTMaster's commands
45  *
46  * @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
47  * @version     1.0
48  * @since       2016-06-16
49  */
50 public class IoTSlave {
51
52         /**
53          * IoTSlave class properties
54          */
55         private Message sIoTMasterMsg;
56         private String sIoTMasterHostAdd;
57         private String sMainObjectName;
58         private int iComPort;
59         private int iRMIRegPort;
60         private int iRMIStubPort;
61         private String strFieldName;
62         private Class<?> clsMain;
63         private Object objMainCls;
64         private Object iRelFirstObject;
65         private Object iRelSecondObject;
66         private Socket socket;
67         private ObjectOutputStream outStream;
68         private ObjectInputStream inStream;
69         private Map<String,Object> mapObjNameStub;
70
71         /**
72          * IoTSet object, e.g. IoTSet<ProximitySensor> proximity_sensors;
73          * IoTRelation object, e.g. IoTRelation<ProximitySensor, LightBulb> ps_lb_relation;
74          */
75         private ISet<Object> isetObject;
76         private IoTSet<Object> iotsetObject;
77         private IRelation<Object,Object> irelObject;
78         private IoTRelation<Object,Object> iotrelObject;
79
80         // Constants that are to be extracted from config file
81         private static String STR_JAR_FILE_PATH;
82         private static String STR_OBJ_CLS_PFX;
83         private static String STR_INTERFACE_PFX;
84         private static String SKEL_CLASS_SUFFIX;
85         private static String STUB_CLASS_SUFFIX;
86         private static boolean BOOL_VERBOSE;
87         private static boolean CAPAB_BASED_RMI;
88
89         /**
90          * IoTSlave class constants - not to be changed by users
91          */
92         private static final String STR_IOT_SLAVE_NAME = "IoTSlave";
93         private static final String STR_CFG_FILE_EXT = ".config";
94         private static final String STR_CLS_FILE_EXT = ".class";
95         private static final String STR_JAR_FILE_EXT = ".jar";
96         private static final String STR_ZIP_FILE_EXT = ".zip";
97         private static final String STR_UNZIP_DIR = "./";
98         private static final Class<?>[] STR_URL_PARAM = new Class[] {URL.class };
99         private static final String STR_YES = "Yes";
100         private static final String STR_NO = "No";
101
102         /**
103          * Class constructor
104          *
105          */
106         public IoTSlave(String[] argInp) {
107
108                 sIoTMasterMsg = null;
109                 sIoTMasterHostAdd = argInp[0];
110                 iComPort = Integer.parseInt(argInp[1]);
111                 iRMIRegPort = Integer.parseInt(argInp[2]);
112                 iRMIStubPort = Integer.parseInt(argInp[3]);
113                 sMainObjectName = null;
114                 strFieldName = null;
115                 clsMain = null;
116                 objMainCls = null;
117                 isetObject = null;
118                 iotsetObject = null;
119                 irelObject = null;
120                 iotrelObject = null;
121                 iRelFirstObject = null;
122                 iRelSecondObject = null;
123                 socket = null;
124                 outStream = null;
125                 inStream = null;
126                 mapObjNameStub = new HashMap<String,Object>();
127
128                 STR_JAR_FILE_PATH = null;
129                 STR_OBJ_CLS_PFX = null;
130                 STR_INTERFACE_PFX = null;
131                 SKEL_CLASS_SUFFIX = null;
132                 STUB_CLASS_SUFFIX = null;
133                 BOOL_VERBOSE = false;
134                 CAPAB_BASED_RMI = false;
135         }
136
137         /**
138          * A method to initialize constants from config file
139          *
140          * @return void
141          */
142         private void parseIoTSlaveConfigFile() {
143                 // Parse configuration file
144                 Properties prop = new Properties();
145                 String strCfgFileName = STR_IOT_SLAVE_NAME + STR_CFG_FILE_EXT;
146                 File file = new File(strCfgFileName);
147                 try {
148                         FileInputStream fis = new FileInputStream(file);
149                         prop.load(fis);
150                 } catch (IOException ex) {
151                         System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
152                         ex.printStackTrace();
153                 }
154                 System.out.println("IoTMaster: Extracting information from config file: " + strCfgFileName);
155                 // Initialize constants from config file
156                 STR_JAR_FILE_PATH = prop.getProperty("JAR_FILE_PATH");
157                 STR_OBJ_CLS_PFX = prop.getProperty("OBJECT_CLASS_PREFIX");
158                 STR_INTERFACE_PFX = prop.getProperty("INTERFACE_PREFIX");
159                 SKEL_CLASS_SUFFIX = prop.getProperty("SKEL_CLASS_SUFFIX");
160                 STUB_CLASS_SUFFIX = prop.getProperty("STUB_CLASS_SUFFIX");
161                 if (prop.getProperty("VERBOSE").equals(STR_YES)) {
162                         BOOL_VERBOSE = true;
163                 }
164                 if (prop.getProperty("CAPAB_BASED_RMI").equals(STR_YES)) {
165                         CAPAB_BASED_RMI = true;
166                 }
167
168                 System.out.println("JAR_FILE_PATH=" + STR_JAR_FILE_PATH);
169                 System.out.println("OBJECT_CLASS_PREFIX=" + STR_OBJ_CLS_PFX);
170                 System.out.println("INTERFACE_PREFIX=" + STR_INTERFACE_PFX);
171                 System.out.println("SKEL_CLASS_SUFFIX=" + SKEL_CLASS_SUFFIX);
172                 System.out.println("STUB_CLASS_SUFFIX=" + STUB_CLASS_SUFFIX);
173                 System.out.println("CAPAB_BASED_RMI=" + CAPAB_BASED_RMI);
174                 System.out.println("IoTMaster: Information extracted successfully!");
175         }
176
177         /**
178          * Adds the content pointed by the URL to the classpath dynamically at runtime (hack!!!)
179          *
180          * @param  url         the URL pointing to the content to be added
181          * @throws IOException
182          * @see    <a href="http://stackoverflow.com/questions/60764/how-should-i-load-jars-dynamically-at-runtime</a>
183          */
184         private static void addURL(URL url) throws IOException {
185
186                 URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
187                 Class<?> sysclass = URLClassLoader.class;
188
189                 try {
190
191                         Method method = sysclass.getDeclaredMethod("addURL", STR_URL_PARAM);
192                         method.setAccessible(true);
193                         method.invoke(sysloader,new Object[] { url });
194
195                 } catch (Throwable t) {
196
197                         t.printStackTrace();
198                         throw new IOException("IoTSlave: Could not add URL to system classloader!");
199                 }
200         }
201
202         /**
203          * A private method to create object
204          *
205          * @return  void
206          */
207         private void createCapabBasedRMIJava(MessageCreateObject sMessage) throws 
208                 ClassNotFoundException, NoSuchMethodException, UnknownHostException {
209
210                 // TODO: DEBUG
211                 System.out.println("\n\nDEBUG: Create capab based RMI here!");
212                 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
213                 System.out.println("DEBUG: sMessage object class: " + sMessage.getObjectClass());
214                 System.out.println("DEBUG: sMessage object name: " + sMessage.getObjectName());
215                 System.out.println("DEBUG: sMessage interface name: " + sMessage.getObjectInterfaceName());
216                 System.out.println("DEBUG: sMessage reg port: " + sMessage.getRMIRegPort());
217                 System.out.println("DEBUG: sMessage stub port: " + sMessage.getRMIStubPort());
218                 System.out.println("DEBUG: sMessage object fields: " + Arrays.toString(sMessage.getObjectFields()));
219                 System.out.println("DEBUG: sMessage object fields: " + Arrays.toString(sMessage.getObjectFldCls()));
220                 System.out.println("\n\n");
221
222                 // Instantiate the skeleton and put in the object
223                 String strObjSkelName = STR_OBJ_CLS_PFX + "." + sMessage.getObjectClass() +
224                                                                         "." + sMessage.getObjectInterfaceName() + SKEL_CLASS_SUFFIX;
225                 RuntimeOutput.print("IoTSlave: Skeleton object: " + strObjSkelName, BOOL_VERBOSE);
226                 Class<?> clsSkel = Class.forName(strObjSkelName);
227                 Class<?> clsInt = Class.forName(STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + 
228                         "." + sMessage.getObjectInterfaceName());
229                 Class[] clsSkelParams = { clsInt, String.class, int.class };    // Port number is integer
230                 Constructor<?> objSkelCons = clsSkel.getDeclaredConstructor(clsSkelParams);
231                 String callbackAddress = InetAddress.getLocalHost().getHostAddress();   // Callback address is this machine's address
232                 Object objSkelParams[] = { objMainCls, callbackAddress, iRMIStubPort };
233                 // Create a new thread for each skeleton
234                 Thread objectThread = new Thread(new Runnable() {
235                         public void run() {
236                                 try {
237                                         Object objSkel = objSkelCons.newInstance(objSkelParams);
238                                 } catch (InstantiationException |
239                                                  IllegalAccessException |
240                                                  InvocationTargetException ex) {
241                                         ex.printStackTrace();
242                                 }
243                         }
244                 });
245                 objectThread.start();
246                 RuntimeOutput.print("IoTSlave: Done generating object!", BOOL_VERBOSE);
247         }
248
249         /**
250          * A private method to create object
251          *
252          * @return  void
253          */
254         private void createObject() throws IOException,
255                 ClassNotFoundException, NoSuchMethodException, InstantiationException,
256                         RemoteException, AlreadyBoundException, IllegalAccessException,
257                                 InvocationTargetException {
258
259                 // TODO: DEBUG
260                 System.out.println("\n\nDEBUG: CREATE DRIVER OBJECT!!!\n\n");
261
262                 // Translating into the actual Message class
263                 MessageCreateObject sMessage = (MessageCreateObject) sIoTMasterMsg;
264                 // Instantiate object using reflection
265                 String strObjClassName = STR_OBJ_CLS_PFX + "." + sMessage.getObjectClass() +
266                                                                                                                  "." + sMessage.getObjectClass();
267                 File file = new File(STR_JAR_FILE_PATH + sMessage.getObjectClass() + STR_JAR_FILE_EXT);
268                 RuntimeOutput.print("IoTSlave: DEBUG print path: " + STR_JAR_FILE_PATH +
269                                                                                          sMessage.getObjectClass() + STR_JAR_FILE_EXT, BOOL_VERBOSE);
270                 addURL(file.toURI().toURL());
271                 clsMain = Class.forName(strObjClassName);
272                 Class[] clsParams = sMessage.getObjectFldCls();
273                 Constructor<?> ct = clsMain.getDeclaredConstructor(clsParams);
274                 Object objParams[] = sMessage.getObjectFields();
275                 objMainCls = ct.newInstance(objParams);
276                 RuntimeOutput.print("IoTSlave: Creating RMI skeleton: " +
277                         sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
278                         " with RMI stub port: " + iRMIStubPort, BOOL_VERBOSE);
279                 if (CAPAB_BASED_RMI) {
280                 // Use the new capability-based RMI in Java
281                         createCapabBasedRMIJava(sMessage);
282                 } else {
283                         // Register object to RMI - there are 2 ports: RMI registry port and RMI stub port
284                         Object objStub = (Object)
285                                 UnicastRemoteObject.exportObject((Remote) objMainCls, iRMIStubPort);
286                         Registry registry = LocateRegistry.createRegistry(iRMIRegPort);
287                         registry.bind(sMessage.getObjectName(), (Remote) objStub);
288                 }
289                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
290                 RuntimeOutput.print("IoTSlave: Registering object via RMI!", BOOL_VERBOSE);
291
292         }
293
294         
295         /**
296          * A private method to transfer file
297          *
298          * @return  void
299          */
300         private void transferFile() throws IOException,
301                 UnknownHostException, FileNotFoundException {
302
303                 // Translating into the actual Message class
304                 MessageSendFile sMessage = (MessageSendFile) sIoTMasterMsg;
305
306                 // Send back the received message as acknowledgement
307                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
308
309                 // Write file to the current location
310                 Socket filesocket = new Socket(sIoTMasterHostAdd, iComPort);
311                 InputStream inFileStream = filesocket.getInputStream();
312                 OutputStream outFileStream = new FileOutputStream(sMessage.getFileName());
313                 byte[] bytFile = new byte[Math.toIntExact(sMessage.getFileSize())];
314
315                 int iCount = 0;
316                 while ((iCount = inFileStream.read(bytFile)) > 0) {
317                         outFileStream.write(bytFile, 0, iCount);
318                 }
319                 // Unzip if this is a zipped file
320                 if (sMessage.getFileName().contains(STR_ZIP_FILE_EXT)) {
321                         RuntimeOutput.print("IoTSlave: Unzipping file: " + sMessage.getFileName(), BOOL_VERBOSE);
322                         try {
323                                 ZipFile zipFile = new ZipFile(sMessage.getFileName());
324                                 zipFile.extractAll(STR_UNZIP_DIR);
325                         } catch (ZipException ex) {
326                                 System.out.println("IoTSlave: Error in unzipping file!");
327                                 ex.printStackTrace();
328                         }
329                 }
330                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
331                 RuntimeOutput.print("IoTSlave: Receiving file transfer!", BOOL_VERBOSE);
332         }
333
334         /**
335          * A private method to create a main object
336          *
337          * @return  void
338          */
339         private void createMainObject() throws IOException,
340                 ClassNotFoundException, InstantiationException, IllegalAccessException,
341                         InvocationTargetException {
342
343                 // Translating into the actual Message class
344                 MessageCreateMainObject sMessage = (MessageCreateMainObject) sIoTMasterMsg;
345
346                 // TODO: DEBUG
347                 System.out.println("\n\nDEBUG: CREATE MAIN OBJECT!!!");
348                 System.out.println("DEBUG: sMessage object name: " + sMessage.getObjectName());
349
350                 // Getting controller class
351                 File file = new File(STR_JAR_FILE_PATH + sMessage.getObjectName() + STR_JAR_FILE_EXT);
352                 RuntimeOutput.print("IoTSlave: DEBUG print path: " + STR_JAR_FILE_PATH +
353                                                                                          sMessage.getObjectName() + STR_JAR_FILE_EXT, BOOL_VERBOSE);
354                 addURL(file.toURI().toURL());
355                 // We will always have a package name <object name>.<object name>
356                 // e.g. SmartLightsController.SmartLightsController
357                 sMainObjectName = sMessage.getObjectName();
358                 clsMain = Class.forName(sMainObjectName + "." + sMainObjectName);
359                 objMainCls = clsMain.newInstance();
360
361                 // Send back the received message as acknowledgement
362                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
363                 RuntimeOutput.print("IoTSlave: Instantiating main controller/device class "
364                                                                                          + sMessage.getObjectName(), BOOL_VERBOSE);
365
366         }
367
368         /**
369          * A private method to create a new IoTSet
370          *
371          * @return  void
372          */
373         private void createNewIoTSet() throws IOException {
374
375                 // Translating into the actual Message class
376                 MessageCreateSetRelation sMessage = (MessageCreateSetRelation) sIoTMasterMsg;
377
378                 // TODO: DEBUG
379                 System.out.println("\n\nDEBUG: CREATE NEW IOT SET!!!");
380                 System.out.println("DEBUG: sMessage object field name: " + sMessage.getObjectFieldName());
381
382                 // Initialize field name
383                 strFieldName = sMessage.getObjectFieldName();
384                 RuntimeOutput.print("IoTSlave: Setting up field " + strFieldName, BOOL_VERBOSE);
385
386                 // Creating a new IoTSet object
387                 isetObject = new ISet<Object>();
388
389                 // Send back the received message as acknowledgement
390                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
391                 RuntimeOutput.print("IoTSlave: Creating a new IoTSet object!", BOOL_VERBOSE);
392
393         }
394
395         /**
396          * A private method to create a new IoTRelation
397          *
398          * @return  void
399          */
400         private void createNewIoTRelation() throws IOException {
401
402                 // Translating into the actual Message class
403                 MessageCreateSetRelation sMessage = (MessageCreateSetRelation) sIoTMasterMsg;
404
405                 // TODO: DEBUG
406                 System.out.println("\n\nDEBUG: CREATE NEW IOT RELATION!!!");
407                 System.out.println("DEBUG: sMessage object field name: " + sMessage.getObjectFieldName());
408
409                 // Initialize field name
410                 strFieldName = sMessage.getObjectFieldName();
411                 RuntimeOutput.print("IoTSlave: Setting up field " + strFieldName, BOOL_VERBOSE);
412
413                 // Creating a new IoTRelation object
414                 irelObject = new IRelation<Object,Object>();
415
416                 // Send back the received message as acknowledgement
417                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
418                 RuntimeOutput.print("IoTSlave: Creating a new IoTRelation object!", BOOL_VERBOSE);
419
420         }
421
422         /**
423          * A private method to get an object from the registry
424          *
425          * @return  Object
426          */
427         private Object getObjectFromRegistry() throws RemoteException,
428                         ClassNotFoundException, NotBoundException {
429
430                 // Translating into the actual Message class
431                 MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
432
433                 // Locate RMI registry and add object into IoTSet
434                 Registry registry =
435                         LocateRegistry.getRegistry(sMessage.getHostAddress(), sMessage.getRMIRegPort());
436                 RuntimeOutput.print("IoTSlave: Looking for RMI registry: " +
437                         sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
438                         " with RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
439                 Object stubObj = registry.lookup(sMessage.getObjectName());
440                 RuntimeOutput.print("IoTSlave: Looking for object name: " + sMessage.getObjectName(), BOOL_VERBOSE);
441
442                 // Class conversion to interface class of this class,
443                 // e.g. ProximitySensorImpl has ProximitySensor interface
444                 String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
445                         sMessage.getObjectInterfaceName();
446                 Class<?> clsInf = Class.forName(strObjClassInterfaceName);
447                 Object stubObjConv = clsInf.cast(stubObj);
448
449                 return stubObjConv;
450         }
451
452         /**
453          * A private method to get an object and create a stub
454          * <p>
455          * This is using the capability-based RMI skeleton and stub scheme
456          *
457          * @return  Object
458          */
459         private Object getObjectFromStub() throws RemoteException,
460                         ClassNotFoundException, NoSuchMethodException, InstantiationException, 
461                         IllegalAccessException, NotBoundException, InvocationTargetException, UnknownHostException {
462
463                 // Translating into the actual Message class
464                 MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
465
466                 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
467                 System.out.println("DEBUG: sMessage object class: " + sMessage.getObjectClass());
468                 System.out.println("DEBUG: sMessage object name: " + sMessage.getObjectName());
469                 System.out.println("DEBUG: sMessage interface name: " + sMessage.getObjectInterfaceName());
470                 System.out.println("DEBUG: sMessage reg port: " + sMessage.getRMIRegPort());
471                 System.out.println("DEBUG: sMessage stub port: " + sMessage.getRMIStubPort());
472                 System.out.println("DEBUG: sMessage callback ports: " + Arrays.toString(sMessage.getRMICallbackPorts()));
473                 System.out.println("\n\n");
474
475                 Object stubObjConv = null;
476                 String strObjectName = sMessage.getObjectName();
477                 String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
478                         sMessage.getObjectStubInterfaceName();
479                 Class<?> clsInf = Class.forName(strObjClassInterfaceName);
480                 if (mapObjNameStub.containsKey(strObjectName)) {
481                         RuntimeOutput.print("IoTSlave: Getting back object on slave: " + strObjectName, BOOL_VERBOSE);
482                         stubObjConv = clsInf.cast(mapObjNameStub.get(strObjectName));
483                 } else {
484                         // Instantiate the stub and put in the object
485                         String strObjStubName = sMainObjectName + "." + sMessage.getObjectStubInterfaceName() + STUB_CLASS_SUFFIX;
486                         Class<?> clsStub = Class.forName(strObjStubName);       // Port number is integer
487                         Class[] clsStubParams = { int.class, String.class, String.class, int.class, int[].class };
488                         Constructor<?> objStubCons = clsStub.getDeclaredConstructor(clsStubParams);
489                         Integer[] portsInteger = sMessage.getRMICallbackPorts();
490                         int[] ports = Arrays.stream(portsInteger).mapToInt(Integer::intValue).toArray();
491
492                         int rev = 0;
493                         String callbackAddress = InetAddress.getLocalHost().getHostAddress();   // Callback address is this machine's address
494                         Object objStubParams[] = { sMessage.getRMIStubPort(), sMessage.getHostAddress(), callbackAddress,
495                                                                                 rev, ports };
496                         RuntimeOutput.print("IoTSlave: Creating RMI stub: " +
497                                 sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
498                                 " with callback address: " + callbackAddress + " and RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
499                         Object stubObj = objStubCons.newInstance(objStubParams);
500                         // Class conversion to interface class of this class,
501                         // e.g. ProximitySensorImpl has ProximitySensor interface
502                         RuntimeOutput.print("IoTSlave: Registering new stub object: " + strObjectName, BOOL_VERBOSE);
503                         mapObjNameStub.put(strObjectName, stubObj);
504                         stubObjConv = clsInf.cast(stubObj);
505                 }
506
507                 return stubObjConv;
508         }
509
510         /**
511          * A private method to get an IoTSet object
512          *
513          * @return  void
514          */
515         private void getIoTSetObject() throws IOException,
516                 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
517                 InstantiationException, IllegalAccessException, InvocationTargetException {
518
519                 // TODO: DEBUG
520                 System.out.println("\n\nDEBUG: GET IOT SET OBJECT!!!");
521
522                 Object objRegistry = null;
523                 if (CAPAB_BASED_RMI)
524                         objRegistry = getObjectFromStub();
525                 else
526                         objRegistry = getObjectFromRegistry();
527                 isetObject.add(objRegistry);
528                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
529
530                 // Send back the received message as acknowledgement
531                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
532                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
533         }
534
535         /**
536          * A private method to get an IoTRelation first object
537          *
538          * @return  void
539          */
540         private void getIoTRelationFirstObject() throws IOException,
541                 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
542                 InstantiationException, IllegalAccessException, InvocationTargetException {
543
544                 // TODO: DEBUG
545                 System.out.println("\n\nDEBUG: GET IOT RELATION FIRST OBJECT!!!");
546
547                 Object objRegistry = null;
548                 if (CAPAB_BASED_RMI)
549                         objRegistry = getObjectFromStub();
550                 else
551                         objRegistry = getObjectFromRegistry();
552                 iRelFirstObject = objRegistry;
553
554                 // Send back the received message as acknowledgement
555                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
556                 RuntimeOutput.print("IoTSlave: Getting a first object for IoTRelation!", BOOL_VERBOSE);
557
558         }
559
560         /**
561          * A private method to get an IoTRelation second object
562          *
563          * @return  void
564          */
565         private void getIoTRelationSecondObject() throws IOException,
566                 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
567                 InstantiationException, IllegalAccessException, InvocationTargetException {
568
569                 // TODO: DEBUG
570                 System.out.println("\n\nDEBUG: GET IOT RELATION SECOND OBJECT!!!");
571
572                 Object objRegistry = null;
573                 if (CAPAB_BASED_RMI)
574                         objRegistry = getObjectFromStub();
575                 else
576                         objRegistry = getObjectFromRegistry();
577                 iRelSecondObject = objRegistry;
578
579                 // Now add the first and the second object into IoTRelation
580                 irelObject.put(iRelFirstObject, iRelSecondObject);
581                 RuntimeOutput.print("IoTSlave: This IoTRelation now has: " + irelObject.size() + " entry(s)", BOOL_VERBOSE);
582
583                 // Send back the received message as acknowledgement
584                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
585                 RuntimeOutput.print("IoTSlave: Getting a second object for IoTRelation!", BOOL_VERBOSE);
586
587         }
588
589         /**
590          * A private method to reinitialize IoTSet field
591          *
592          * @return  void
593          */
594         private void reinitializeIoTSetField() throws IOException,
595                 IllegalAccessException, NoSuchFieldException {
596
597                 // Reinitialize IoTSet field after getting all the objects
598                 iotsetObject = new IoTSet<Object>(isetObject.values());
599
600                 // TODO: DEBUG
601                 System.out.println("\n\nDEBUG: REINITIALIZE IOT SET FIELD!!!");
602                 System.out.println("DEBUG: Field name: " + strFieldName + "\n\n");
603
604                 // Private fields need getDeclaredField(), while public fields use getField()
605                 Field fld = clsMain.getDeclaredField(strFieldName);
606                 boolean bAccess = fld.isAccessible();
607                 fld.setAccessible(true);
608                 fld.set(objMainCls, iotsetObject);
609                 fld.setAccessible(bAccess);
610                 RuntimeOutput.print("IoTSlave: Reinitializing field " + strFieldName, BOOL_VERBOSE);
611
612                 // Send back the received message as acknowledgement
613                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
614                 RuntimeOutput.print("IoTSlave: Reinitializing IoTSet field!", BOOL_VERBOSE);
615
616         }
617
618         /**
619          * A private method to reinitialize IoTRelation field
620          *
621          * @return  void
622          */
623         private void reinitializeIoTRelationField() throws IOException,
624                 IllegalAccessException, NoSuchFieldException {
625
626                 // Reinitialize IoTSet field after getting all the objects
627                 iotrelObject = new IoTRelation<Object,Object>(irelObject.relationMap(), irelObject.size());
628
629                 // TODO: DEBUG
630                 System.out.println("\n\nDEBUG: REINITIALIZE IOT RELATION FIELD!!!");
631                 System.out.println("DEBUG: Field name: " + strFieldName + "\n\n");
632
633                 // Private fields need getDeclaredField(), while public fields use getField()
634                 Field fld = clsMain.getDeclaredField(strFieldName);
635                 boolean bAccess = fld.isAccessible();
636                 fld.setAccessible(true);
637                 fld.set(objMainCls, iotrelObject);
638                 fld.setAccessible(bAccess);
639                 RuntimeOutput.print("IoTSlave: Reinitializing field " + strFieldName, BOOL_VERBOSE);
640
641                 // Send back the received message as acknowledgement
642                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
643                 RuntimeOutput.print("IoTSlave: Reinitializing IoTRelation field!", BOOL_VERBOSE);
644
645         }
646
647         /**
648          * A private method to get the device driver object's IoTSet
649          * <p>
650          * This is to handle device driver's IoTSet that contains IP addresses
651          *
652          * @return  void
653          */
654         private void getDeviceIoTSetObject() throws IOException {
655
656                 // Translating into the actual Message class
657                 MessageGetDeviceObject sMessage = (MessageGetDeviceObject) sIoTMasterMsg;
658
659                 // TODO: DEBUG
660                 System.out.println("\n\nDEBUG: GET DEVICE IOT SET OBJECT!!!");
661                 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress());
662                 System.out.println("DEBUG: sMessage source port: " + sMessage.getSourceDeviceDriverPort());
663                 System.out.println("DEBUG: sMessage destination port: " + sMessage.getDestinationDeviceDriverPort());
664                 System.out.println("DEBUG: sMessage source wild card: " + sMessage.isSourcePortWildCard());
665                 System.out.println("DEBUG: sMessage desination wild card: " + sMessage.isDestinationPortWildCard() + "\n\n");
666
667                 // Get IoTSet objects for IP address set on device driver/controller
668                 IoTDeviceAddress objDeviceAddress = new IoTDeviceAddress(sMessage.getHostAddress(),
669                         sMessage.getSourceDeviceDriverPort(),
670                         sMessage.getDestinationDeviceDriverPort(),
671                         sMessage.isSourcePortWildCard(),
672                         sMessage.isDestinationPortWildCard());
673                 RuntimeOutput.print("IoTSlave: Device address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
674                 isetObject.add(objDeviceAddress);
675                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
676
677                 // Send back the received message as acknowledgement
678                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
679                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
680
681         }
682
683         /**
684          * A private method to get the device driver object's IoTSet for IoTZigbeeAddress
685          * <p>
686          * This is to handle device driver's IoTSet that contains Zigbee addresses
687          *
688          * @return  void
689          */
690         private void getZBDevIoTSetObject() throws IOException {
691
692                 // Translating into the actual Message class
693                 MessageGetSimpleDeviceObject sMessage = (MessageGetSimpleDeviceObject) sIoTMasterMsg;
694
695                 // TODO: DEBUG
696                 System.out.println("\n\nDEBUG: GET ZIGBEE DEVICE IOT SET OBJECT!!!");
697                 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress() + "\n\n");
698
699                 // Get IoTSet objects for IP address set on device driver/controller
700                 IoTZigbeeAddress objZBDevAddress = new IoTZigbeeAddress(sMessage.getHostAddress());
701                 RuntimeOutput.print("IoTSlave: Device address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
702                 isetObject.add(objZBDevAddress);
703                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
704
705                 // Send back the received message as acknowledgement
706                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
707                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
708
709         }
710
711         
712         /**
713          * A private method to get IoTAddress objects for IoTSet
714          *
715          * @return  void
716          */
717         private void getAddIoTSetObject() throws IOException {
718
719                 // Translating into the actual Message class
720                 MessageGetSimpleDeviceObject sMessage = (MessageGetSimpleDeviceObject) sIoTMasterMsg;
721
722                 // TODO: DEBUG
723                 System.out.println("\n\nDEBUG: GET ADD IOT SET OBJECT!!!");
724                 System.out.println("DEBUG: sMessage host address: " + sMessage.getHostAddress() + "\n\n");
725
726                 // Get IoTSet objects for IP address set on device driver/controller
727                 IoTAddress objAddress = new IoTAddress(sMessage.getHostAddress());
728                 RuntimeOutput.print("IoTSlave: Address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
729                 isetObject.add(objAddress);
730                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
731                 // Send back the received message as acknowledgement
732                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
733                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
734
735         }
736         
737         /**
738          * A private method to invoke init() method in the controller object
739          *
740          * @return  void
741          */
742         private void invokeInitMethod() throws IOException {
743
744                 // TODO: DEBUG
745                 System.out.println("\n\nDEBUG: INVOKE INIT METHOD!!!\n\n");
746
747                 new Thread() {
748                         public void run() {
749                                 try {
750                                         Class<?> noparams[] = {};
751                                         Method method = clsMain.getDeclaredMethod("init", noparams);
752                                         method.invoke(objMainCls);
753                                 } catch (NoSuchMethodException  |
754                                                  IllegalAccessException |
755                                                  InvocationTargetException ex) {
756                                         System.out.println("IoTSlave: Exception: "
757                                                  + ex.getMessage());
758                                         ex.printStackTrace();
759                                 }
760                         }
761                 }.start();
762
763                 // Start a new thread to invoke the init function
764                 RuntimeOutput.print("IoTSlave: Invoke init method! Job done!", BOOL_VERBOSE);
765
766                 // Send back the received message as acknowledgement
767                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
768
769         }
770
771         /**
772          * A public method to do communication with IoTMaster
773          *
774          * @params  iIndex  Integer index
775          * @return  void
776          */
777         public void commIoTMaster() {
778
779                 try {
780
781                         // Loop, receive and process commands from IoTMaster
782                         socket = new Socket(sIoTMasterHostAdd, iComPort);
783                         outStream = new ObjectOutputStream(socket.getOutputStream());
784                         inStream = new ObjectInputStream(socket.getInputStream());
785
786                         LOOP:
787                         while(true) {
788                                 // Get the first payload
789                                 RuntimeOutput.print("IoTSlave: Slave waiting...", BOOL_VERBOSE);
790                                 sIoTMasterMsg = (Message) inStream.readObject();
791
792                                 // Check payload message from IoTMaster and make a decision
793                                 switch (sIoTMasterMsg.getMessage()) {
794
795                                 case CREATE_OBJECT:
796                                         createObject();
797                                         break;
798
799                                 case TRANSFER_FILE:
800                                         transferFile();
801                                         break;
802
803                                 case CREATE_MAIN_OBJECT:
804                                         createMainObject();
805                                         break;
806
807                                 case CREATE_NEW_IOTSET:
808                                         createNewIoTSet();
809                                         break;
810
811                                 case CREATE_NEW_IOTRELATION:
812                                         createNewIoTRelation();
813                                         break;
814
815                                 case GET_IOTSET_OBJECT:
816                                         getIoTSetObject();
817                                         break;
818
819                                 case GET_IOTRELATION_FIRST_OBJECT:
820                                         getIoTRelationFirstObject();
821                                         break;
822
823                                 case GET_IOTRELATION_SECOND_OBJECT:
824                                         getIoTRelationSecondObject();
825                                         break;
826
827                                 case REINITIALIZE_IOTSET_FIELD:
828                                         reinitializeIoTSetField();
829                                         break;
830
831                                 case REINITIALIZE_IOTRELATION_FIELD:
832                                         reinitializeIoTRelationField();
833                                         break;
834
835                                 case GET_DEVICE_IOTSET_OBJECT:
836                                         getDeviceIoTSetObject();
837                                         break;
838
839                                 case GET_ZB_DEV_IOTSET_OBJECT:
840                                         getZBDevIoTSetObject();
841                                         break;
842
843                                 case GET_ADD_IOTSET_OBJECT:
844                                         getAddIoTSetObject();
845                                         break;
846
847                                 case INVOKE_INIT_METHOD:
848                                         invokeInitMethod();
849                                         break;
850
851                                 case END_SESSION:
852                                         // END of session
853                                         break LOOP;
854
855                                 default:
856                                         break;
857                                 }
858                         }
859                         RuntimeOutput.print("IoTSlave: Session ends!", BOOL_VERBOSE);
860
861                         // Closing streams and end session
862                         outStream.close();
863                         inStream.close();
864                         socket.close();
865                         RuntimeOutput.print("IoTSlave: Closing!", BOOL_VERBOSE);
866                         // We have to continuously loop because we are preserving our stubs and skeletons
867                         //while(true) { }
868
869                 } catch (IOException               |
870                                  ClassNotFoundException    |
871                                  NoSuchMethodException     |
872                                  InstantiationException    |
873                                  AlreadyBoundException     |
874                                  IllegalAccessException    |
875                                  InvocationTargetException |
876                                  NotBoundException         |
877                                  NoSuchFieldException ex) {
878                         System.out.println("IoTSlave: Exception: "
879                                  + ex.getMessage());
880                         ex.printStackTrace();
881                 }
882         }
883
884         public static void main(String args[]) {
885                 IoTSlave iotSlave = new IoTSlave(args);
886                 iotSlave.parseIoTSlaveConfigFile();
887                 iotSlave.commIoTMaster();
888         }
889 }