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