Making classes final to make inheritance impossible
[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 final 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                 // Instantiate the skeleton and put in the object
211                 String strObjSkelName = STR_OBJ_CLS_PFX + "." + sMessage.getObjectClass() +
212                                                                         "." + sMessage.getObjectInterfaceName() + SKEL_CLASS_SUFFIX;
213                 RuntimeOutput.print("IoTSlave: Skeleton object: " + strObjSkelName, BOOL_VERBOSE);
214                 Class<?> clsSkel = Class.forName(strObjSkelName);
215                 Class<?> clsInt = Class.forName(STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + 
216                         "." + sMessage.getObjectInterfaceName());
217                 Class[] clsSkelParams = { clsInt, int.class, int.class };       // Port number is integer
218                 Constructor<?> objSkelCons = clsSkel.getDeclaredConstructor(clsSkelParams);
219                 Object objSkelParams[] = { objMainCls, iRMIStubPort, iRMIRegPort };
220                 // Create a new thread for each skeleton
221                 Thread objectThread = new Thread(new Runnable() {
222                         public void run() {
223                                 try {
224                                         Object objSkel = objSkelCons.newInstance(objSkelParams);
225                                 } catch (InstantiationException |
226                                                  IllegalAccessException |
227                                                  InvocationTargetException ex) {
228                                         ex.printStackTrace();
229                                 }
230                         }
231                 });
232                 objectThread.start();
233                 RuntimeOutput.print("IoTSlave: Done generating object!", BOOL_VERBOSE);
234         }
235
236         /**
237          * A private method to create object
238          *
239          * @return  void
240          */
241         private void createObject() throws IOException,
242                 ClassNotFoundException, NoSuchMethodException, InstantiationException,
243                         RemoteException, AlreadyBoundException, IllegalAccessException,
244                                 InvocationTargetException {
245
246                 // Translating into the actual Message class
247                 MessageCreateObject sMessage = (MessageCreateObject) sIoTMasterMsg;
248                 // Instantiate object using reflection
249                 String strObjClassName = STR_OBJ_CLS_PFX + "." + sMessage.getObjectClass() +
250                                                                                                                  "." + sMessage.getObjectClass();
251                 File file = new File(STR_JAR_FILE_PATH + sMessage.getObjectClass() + STR_JAR_FILE_EXT);
252                 RuntimeOutput.print("IoTSlave: DEBUG print path: " + STR_JAR_FILE_PATH +
253                                                                                          sMessage.getObjectClass() + STR_JAR_FILE_EXT, BOOL_VERBOSE);
254                 addURL(file.toURI().toURL());
255                 clsMain = Class.forName(strObjClassName);
256                 Class[] clsParams = sMessage.getObjectFldCls();
257                 Constructor<?> ct = clsMain.getDeclaredConstructor(clsParams);
258                 Object objParams[] = sMessage.getObjectFields();
259                 objMainCls = ct.newInstance(objParams);
260                 RuntimeOutput.print("IoTSlave: Creating RMI skeleton: " +
261                         sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
262                         " with RMI stub port: " + iRMIStubPort, BOOL_VERBOSE);
263                 if (CAPAB_BASED_RMI) {
264                 // Use the new capability-based RMI in Java
265                         createCapabBasedRMIJava(sMessage);
266                 } else {
267                         // Register object to RMI - there are 2 ports: RMI registry port and RMI stub port
268                         Object objStub = (Object)
269                                 UnicastRemoteObject.exportObject((Remote) objMainCls, iRMIStubPort);
270                         Registry registry = LocateRegistry.createRegistry(iRMIRegPort);
271                         registry.bind(sMessage.getObjectName(), (Remote) objStub);
272                 }
273                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
274                 RuntimeOutput.print("IoTSlave: Registering object via RMI!", BOOL_VERBOSE);
275
276         }
277
278         
279         /**
280          * A private method to transfer file
281          *
282          * @return  void
283          */
284         private void transferFile() throws IOException,
285                 UnknownHostException, FileNotFoundException {
286
287                 // Translating into the actual Message class
288                 MessageSendFile sMessage = (MessageSendFile) sIoTMasterMsg;
289
290                 // Send back the received message as acknowledgement
291                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
292
293                 // Write file to the current location
294                 Socket filesocket = new Socket(sIoTMasterHostAdd, iComPort);
295                 InputStream inFileStream = filesocket.getInputStream();
296                 OutputStream outFileStream = new FileOutputStream(sMessage.getFileName());
297                 byte[] bytFile = new byte[Math.toIntExact(sMessage.getFileSize())];
298
299                 int iCount = 0;
300                 while ((iCount = inFileStream.read(bytFile)) > 0) {
301                         outFileStream.write(bytFile, 0, iCount);
302                 }
303                 // Unzip if this is a zipped file
304                 if (sMessage.getFileName().contains(STR_ZIP_FILE_EXT)) {
305                         RuntimeOutput.print("IoTSlave: Unzipping file: " + sMessage.getFileName(), BOOL_VERBOSE);
306                         try {
307                                 ZipFile zipFile = new ZipFile(sMessage.getFileName());
308                                 zipFile.extractAll(STR_UNZIP_DIR);
309                         } catch (ZipException ex) {
310                                 System.out.println("IoTSlave: Error in unzipping file!");
311                                 ex.printStackTrace();
312                         }
313                 }
314                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
315                 RuntimeOutput.print("IoTSlave: Receiving file transfer!", BOOL_VERBOSE);
316         }
317
318         /**
319          * A private method to create a main object
320          *
321          * @return  void
322          */
323         private void createMainObject() throws IOException,
324                 ClassNotFoundException, InstantiationException, IllegalAccessException,
325                         InvocationTargetException {
326
327                 // Translating into the actual Message class
328                 MessageCreateMainObject sMessage = (MessageCreateMainObject) sIoTMasterMsg;
329
330                 // Getting controller class
331                 File file = new File(STR_JAR_FILE_PATH + sMessage.getObjectName() + STR_JAR_FILE_EXT);
332                 RuntimeOutput.print("IoTSlave: DEBUG print path: " + STR_JAR_FILE_PATH +
333                                                                                          sMessage.getObjectName() + STR_JAR_FILE_EXT, BOOL_VERBOSE);
334                 addURL(file.toURI().toURL());
335                 // We will always have a package name <object name>.<object name>
336                 // e.g. SmartLightsController.SmartLightsController
337                 sMainObjectName = sMessage.getObjectName();
338                 clsMain = Class.forName(sMainObjectName + "." + sMainObjectName);
339                 objMainCls = clsMain.newInstance();
340
341                 // Send back the received message as acknowledgement
342                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
343                 RuntimeOutput.print("IoTSlave: Instantiating main controller/device class "
344                                                                                          + sMessage.getObjectName(), BOOL_VERBOSE);
345
346         }
347
348         /**
349          * A private method to create a new IoTSet
350          *
351          * @return  void
352          */
353         private void createNewIoTSet() throws IOException {
354
355                 // Translating into the actual Message class
356                 MessageCreateSetRelation sMessage = (MessageCreateSetRelation) sIoTMasterMsg;
357
358                 // Initialize field name
359                 strFieldName = sMessage.getObjectFieldName();
360                 RuntimeOutput.print("IoTSlave: Setting up field " + strFieldName, BOOL_VERBOSE);
361
362                 // Creating a new IoTSet object
363                 isetObject = new ISet<Object>();
364
365                 // Send back the received message as acknowledgement
366                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
367                 RuntimeOutput.print("IoTSlave: Creating a new IoTSet object!", BOOL_VERBOSE);
368
369         }
370
371         /**
372          * A private method to create a new IoTRelation
373          *
374          * @return  void
375          */
376         private void createNewIoTRelation() throws IOException {
377
378                 // Translating into the actual Message class
379                 MessageCreateSetRelation sMessage = (MessageCreateSetRelation) sIoTMasterMsg;
380
381                 // Initialize field name
382                 strFieldName = sMessage.getObjectFieldName();
383                 RuntimeOutput.print("IoTSlave: Setting up field " + strFieldName, BOOL_VERBOSE);
384
385                 // Creating a new IoTRelation object
386                 irelObject = new IRelation<Object,Object>();
387
388                 // Send back the received message as acknowledgement
389                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
390                 RuntimeOutput.print("IoTSlave: Creating a new IoTRelation object!", BOOL_VERBOSE);
391
392         }
393
394         /**
395          * A private method to get an object from the registry
396          *
397          * @return  Object
398          */
399         private Object getObjectFromRegistry() throws RemoteException,
400                         ClassNotFoundException, NotBoundException {
401
402                 // Translating into the actual Message class
403                 MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
404
405                 // Locate RMI registry and add object into IoTSet
406                 Registry registry =
407                         LocateRegistry.getRegistry(sMessage.getHostAddress(), sMessage.getRMIRegPort());
408                 RuntimeOutput.print("IoTSlave: Looking for RMI registry: " +
409                         sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() +
410                         " with RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
411                 Object stubObj = registry.lookup(sMessage.getObjectName());
412                 RuntimeOutput.print("IoTSlave: Looking for object name: " + sMessage.getObjectName(), BOOL_VERBOSE);
413
414                 // Class conversion to interface class of this class,
415                 // e.g. ProximitySensorImpl has ProximitySensor interface
416                 String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
417                         sMessage.getObjectInterfaceName();
418                 Class<?> clsInf = Class.forName(strObjClassInterfaceName);
419                 Object stubObjConv = clsInf.cast(stubObj);
420
421                 return stubObjConv;
422         }
423
424         /**
425          * A private method to get an object and create a stub
426          * <p>
427          * This is using the capability-based RMI skeleton and stub scheme
428          *
429          * @return  Object
430          */
431         private Object getObjectFromStub() throws RemoteException,
432                         ClassNotFoundException, NoSuchMethodException, InstantiationException, 
433                         IllegalAccessException, NotBoundException, InvocationTargetException, UnknownHostException {
434
435                 // Translating into the actual Message class
436                 MessageGetObject sMessage = (MessageGetObject) sIoTMasterMsg;
437                 Object stubObjConv = null;
438                 String strObjectName = sMessage.getObjectName();
439                 String strObjClassInterfaceName = STR_OBJ_CLS_PFX + "." + STR_INTERFACE_PFX + "." +
440                         sMessage.getObjectStubInterfaceName();
441                 Class<?> clsInf = Class.forName(strObjClassInterfaceName);
442                 if (mapObjNameStub.containsKey(strObjectName)) {
443                         RuntimeOutput.print("IoTSlave: Getting back object on slave: " + strObjectName, BOOL_VERBOSE);
444                         stubObjConv = clsInf.cast(mapObjNameStub.get(strObjectName));
445                 } else {
446                         // Instantiate the stub and put in the object
447                         String strObjStubName = sMainObjectName + "." + sMessage.getObjectStubInterfaceName() + STUB_CLASS_SUFFIX;
448                         Class<?> clsStub = Class.forName(strObjStubName);       // Port number is integer
449                         Class[] clsStubParams = { int.class, int.class, int.class, int.class, String.class, int.class };
450                         Constructor<?> objStubCons = clsStub.getDeclaredConstructor(clsStubParams);
451
452                         int rev = 0;
453                         Object objStubParams[] = { 0, 0, sMessage.getRMIStubPort(), sMessage.getRMIRegPort(), sMessage.getHostAddress(), rev };
454                         RuntimeOutput.print("IoTSlave: Creating RMI stub: " +
455                                 sMessage.getHostAddress() + ":" + sMessage.getRMIRegPort() + 
456                                 " and RMI stub port: " + sMessage.getRMIStubPort(), BOOL_VERBOSE);
457                         Object stubObj = objStubCons.newInstance(objStubParams);
458                         // Class conversion to interface class of this class,
459                         // e.g. ProximitySensorImpl has ProximitySensor interface
460                         RuntimeOutput.print("IoTSlave: Registering new stub object: " + strObjectName, BOOL_VERBOSE);
461                         mapObjNameStub.put(strObjectName, stubObj);
462                         stubObjConv = clsInf.cast(stubObj);
463                 }
464
465                 return stubObjConv;
466         }
467
468         /**
469          * A private method to get an IoTSet object
470          *
471          * @return  void
472          */
473         private void getIoTSetObject() throws IOException,
474                 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
475                 InstantiationException, IllegalAccessException, InvocationTargetException {
476                 Object objRegistry = null;
477                 if (CAPAB_BASED_RMI)
478                         objRegistry = getObjectFromStub();
479                 else
480                         objRegistry = getObjectFromRegistry();
481                 isetObject.add(objRegistry);
482                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
483
484                 // Send back the received message as acknowledgement
485                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
486                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
487         }
488
489         /**
490          * A private method to get an IoTRelation first object
491          *
492          * @return  void
493          */
494         private void getIoTRelationFirstObject() throws IOException,
495                 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
496                 InstantiationException, IllegalAccessException, InvocationTargetException {
497                 Object objRegistry = null;
498                 if (CAPAB_BASED_RMI)
499                         objRegistry = getObjectFromStub();
500                 else
501                         objRegistry = getObjectFromRegistry();
502                 iRelFirstObject = objRegistry;
503
504                 // Send back the received message as acknowledgement
505                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
506                 RuntimeOutput.print("IoTSlave: Getting a first object for IoTRelation!", BOOL_VERBOSE);
507
508         }
509
510         /**
511          * A private method to get an IoTRelation second object
512          *
513          * @return  void
514          */
515         private void getIoTRelationSecondObject() throws IOException,
516                 ClassNotFoundException, RemoteException, NotBoundException, NoSuchMethodException,
517                 InstantiationException, IllegalAccessException, InvocationTargetException {
518                 Object objRegistry = null;
519                 if (CAPAB_BASED_RMI)
520                         objRegistry = getObjectFromStub();
521                 else
522                         objRegistry = getObjectFromRegistry();
523                 iRelSecondObject = objRegistry;
524
525                 // Now add the first and the second object into IoTRelation
526                 irelObject.put(iRelFirstObject, iRelSecondObject);
527                 RuntimeOutput.print("IoTSlave: This IoTRelation now has: " + irelObject.size() + " entry(s)", BOOL_VERBOSE);
528
529                 // Send back the received message as acknowledgement
530                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
531                 RuntimeOutput.print("IoTSlave: Getting a second object for IoTRelation!", BOOL_VERBOSE);
532
533         }
534
535         /**
536          * A private method to reinitialize IoTSet field
537          *
538          * @return  void
539          */
540         private void reinitializeIoTSetField() throws IOException,
541                 IllegalAccessException, NoSuchFieldException {
542
543                 // Reinitialize IoTSet field after getting all the objects
544                 iotsetObject = new IoTSet<Object>(isetObject.values());
545                 // Private fields need getDeclaredField(), while public fields use getField()
546                 Field fld = clsMain.getDeclaredField(strFieldName);
547                 boolean bAccess = fld.isAccessible();
548                 fld.setAccessible(true);
549                 fld.set(objMainCls, iotsetObject);
550                 fld.setAccessible(bAccess);
551                 RuntimeOutput.print("IoTSlave: Reinitializing field " + strFieldName, BOOL_VERBOSE);
552
553                 // Send back the received message as acknowledgement
554                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
555                 RuntimeOutput.print("IoTSlave: Reinitializing IoTSet field!", BOOL_VERBOSE);
556
557         }
558
559         /**
560          * A private method to reinitialize IoTRelation field
561          *
562          * @return  void
563          */
564         private void reinitializeIoTRelationField() throws IOException,
565                 IllegalAccessException, NoSuchFieldException {
566
567                 // Reinitialize IoTSet field after getting all the objects
568                 iotrelObject = new IoTRelation<Object,Object>(irelObject.relationMap(), irelObject.size());
569                 // Private fields need getDeclaredField(), while public fields use getField()
570                 Field fld = clsMain.getDeclaredField(strFieldName);
571                 boolean bAccess = fld.isAccessible();
572                 fld.setAccessible(true);
573                 fld.set(objMainCls, iotrelObject);
574                 fld.setAccessible(bAccess);
575                 RuntimeOutput.print("IoTSlave: Reinitializing field " + strFieldName, BOOL_VERBOSE);
576
577                 // Send back the received message as acknowledgement
578                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
579                 RuntimeOutput.print("IoTSlave: Reinitializing IoTRelation field!", BOOL_VERBOSE);
580
581         }
582
583         /**
584          * A private method to get the device driver object's IoTSet
585          * <p>
586          * This is to handle device driver's IoTSet that contains IP addresses
587          *
588          * @return  void
589          */
590         private void getDeviceIoTSetObject() throws IOException {
591
592                 // Translating into the actual Message class
593                 MessageGetDeviceObject sMessage = (MessageGetDeviceObject) sIoTMasterMsg;
594                 // Get IoTSet objects for IP address set on device driver/controller
595                 IoTDeviceAddress objDeviceAddress = new IoTDeviceAddress(sMessage.getHostAddress(),
596                         sMessage.getSourceDeviceDriverPort(),
597                         sMessage.getDestinationDeviceDriverPort(),
598                         sMessage.isSourcePortWildCard(),
599                         sMessage.isDestinationPortWildCard());
600                 RuntimeOutput.print("IoTSlave: Device address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
601                 isetObject.add(objDeviceAddress);
602                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
603
604                 // Send back the received message as acknowledgement
605                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
606                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
607
608         }
609
610         /**
611          * A private method to get the device driver object's IoTSet for IoTZigbeeAddress
612          * <p>
613          * This is to handle device driver's IoTSet that contains Zigbee addresses
614          *
615          * @return  void
616          */
617         private void getZBDevIoTSetObject() throws IOException {
618
619                 // Translating into the actual Message class
620                 MessageGetSimpleDeviceObject sMessage = (MessageGetSimpleDeviceObject) sIoTMasterMsg;
621                 // Get IoTSet objects for IP address set on device driver/controller
622                 IoTZigbeeAddress objZBDevAddress = new IoTZigbeeAddress(sMessage.getHostAddress());
623                 RuntimeOutput.print("IoTSlave: Device address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
624                 isetObject.add(objZBDevAddress);
625                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
626
627                 // Send back the received message as acknowledgement
628                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
629                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
630
631         }
632
633         
634         /**
635          * A private method to get IoTAddress objects for IoTSet
636          *
637          * @return  void
638          */
639         private void getAddIoTSetObject() throws IOException {
640
641                 // Translating into the actual Message class
642                 MessageGetSimpleDeviceObject sMessage = (MessageGetSimpleDeviceObject) sIoTMasterMsg;
643                 // Get IoTSet objects for IP address set on device driver/controller
644                 IoTAddress objAddress = new IoTAddress(sMessage.getHostAddress());
645                 RuntimeOutput.print("IoTSlave: Address transferred: " + sMessage.getHostAddress(), BOOL_VERBOSE);
646                 isetObject.add(objAddress);
647                 RuntimeOutput.print("IoTSlave: This IoTSet now has: " + isetObject.size() + " entry(s)", BOOL_VERBOSE);
648                 // Send back the received message as acknowledgement
649                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
650                 RuntimeOutput.print("IoTSlave: Getting an object for IoTSet!", BOOL_VERBOSE);
651
652         }
653         
654         /**
655          * A private method to invoke init() method in the controller object
656          *
657          * @return  void
658          */
659         private void invokeInitMethod() throws IOException {
660
661                 new Thread() {
662                         public void run() {
663                                 try {
664                                         Class<?> noparams[] = {};
665                                         Method method = clsMain.getDeclaredMethod("init", noparams);
666                                         method.invoke(objMainCls);
667                                 } catch (NoSuchMethodException  |
668                                                  IllegalAccessException |
669                                                  InvocationTargetException ex) {
670                                         System.out.println("IoTSlave: Exception: "
671                                                  + ex.getMessage());
672                                         ex.printStackTrace();
673                                 }
674                         }
675                 }.start();
676
677                 // Start a new thread to invoke the init function
678                 RuntimeOutput.print("IoTSlave: Invoke init method! Job done!", BOOL_VERBOSE);
679
680                 // Send back the received message as acknowledgement
681                 outStream.writeObject(new MessageSimple(IoTCommCode.ACKNOWLEDGED));
682
683         }
684
685         /**
686          * A public method to do communication with IoTMaster
687          *
688          * @params  iIndex  Integer index
689          * @return  void
690          */
691         public void commIoTMaster() {
692
693                 try {
694
695                         // Loop, receive and process commands from IoTMaster
696                         socket = new Socket(sIoTMasterHostAdd, iComPort);
697                         outStream = new ObjectOutputStream(socket.getOutputStream());
698                         inStream = new ObjectInputStream(socket.getInputStream());
699
700                         LOOP:
701                         while(true) {
702                                 // Get the first payload
703                                 RuntimeOutput.print("IoTSlave: Slave waiting...", BOOL_VERBOSE);
704                                 sIoTMasterMsg = (Message) inStream.readObject();
705
706                                 // Check payload message from IoTMaster and make a decision
707                                 switch (sIoTMasterMsg.getMessage()) {
708
709                                 case CREATE_OBJECT:
710                                         createObject();
711                                         break;
712
713                                 case TRANSFER_FILE:
714                                         transferFile();
715                                         break;
716
717                                 case CREATE_MAIN_OBJECT:
718                                         createMainObject();
719                                         break;
720
721                                 case CREATE_NEW_IOTSET:
722                                         createNewIoTSet();
723                                         break;
724
725                                 case CREATE_NEW_IOTRELATION:
726                                         createNewIoTRelation();
727                                         break;
728
729                                 case GET_IOTSET_OBJECT:
730                                         getIoTSetObject();
731                                         break;
732
733                                 case GET_IOTRELATION_FIRST_OBJECT:
734                                         getIoTRelationFirstObject();
735                                         break;
736
737                                 case GET_IOTRELATION_SECOND_OBJECT:
738                                         getIoTRelationSecondObject();
739                                         break;
740
741                                 case REINITIALIZE_IOTSET_FIELD:
742                                         reinitializeIoTSetField();
743                                         break;
744
745                                 case REINITIALIZE_IOTRELATION_FIELD:
746                                         reinitializeIoTRelationField();
747                                         break;
748
749                                 case GET_DEVICE_IOTSET_OBJECT:
750                                         getDeviceIoTSetObject();
751                                         break;
752
753                                 case GET_ZB_DEV_IOTSET_OBJECT:
754                                         getZBDevIoTSetObject();
755                                         break;
756
757                                 case GET_ADD_IOTSET_OBJECT:
758                                         getAddIoTSetObject();
759                                         break;
760
761                                 case INVOKE_INIT_METHOD:
762                                         invokeInitMethod();
763                                         break;
764
765                                 case END_SESSION:
766                                         // END of session
767                                         break LOOP;
768
769                                 default:
770                                         break;
771                                 }
772                         }
773                         RuntimeOutput.print("IoTSlave: Session ends!", BOOL_VERBOSE);
774
775                         // Closing streams and end session
776                         outStream.close();
777                         inStream.close();
778                         socket.close();
779                         RuntimeOutput.print("IoTSlave: Closing!", BOOL_VERBOSE);
780                         // We have to continuously loop because we are preserving our stubs and skeletons
781                         //while(true) { }
782
783                 } catch (IOException               |
784                                  ClassNotFoundException    |
785                                  NoSuchMethodException     |
786                                  InstantiationException    |
787                                  AlreadyBoundException     |
788                                  IllegalAccessException    |
789                                  InvocationTargetException |
790                                  NotBoundException         |
791                                  NoSuchFieldException ex) {
792                         System.out.println("IoTSlave: Exception: "
793                                  + ex.getMessage());
794                         ex.printStackTrace();
795                 }
796         }
797
798         public static void main(String args[]) {
799                 IoTSlave iotSlave = new IoTSlave(args);
800                 iotSlave.parseIoTSlaveConfigFile();
801                 iotSlave.commIoTMaster();
802         }
803 }