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