Updating service provider plug-in with the following changes:
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / manager / ResourceManager.java
1 package oic.simulator.serviceprovider.manager;
2
3 import java.net.URL;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.Iterator;
9 import java.util.LinkedList;
10 import java.util.List;
11 import java.util.Map;
12 import java.util.Set;
13
14 import oic.simulator.serviceprovider.Activator;
15 import oic.simulator.serviceprovider.listener.IAutomationUIListener;
16 import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
17 import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
18 import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
19 import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
20 import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
21 import oic.simulator.serviceprovider.resource.MetaProperty;
22 import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
23 import oic.simulator.serviceprovider.resource.SimulatorResource;
24 import oic.simulator.serviceprovider.resource.StandardConfiguration;
25 import oic.simulator.serviceprovider.utils.Constants;
26 import oic.simulator.serviceprovider.utils.Utility;
27
28 import org.eclipse.jface.resource.ImageDescriptor;
29 import org.eclipse.swt.graphics.Image;
30 import org.oic.simulator.AutomationType;
31 import org.oic.simulator.IAutomation;
32 import org.oic.simulator.ResourceAttribute;
33 import org.oic.simulator.ResourceAttribute.Range;
34 import org.oic.simulator.ResourceAttribute.Type;
35 import org.oic.simulator.SimulatorManager;
36 import org.oic.simulator.SimulatorResourceModel;
37 import org.oic.simulator.serviceprovider.IObserver;
38 import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
39 import org.oic.simulator.serviceprovider.ObserverInfo;
40 import org.oic.simulator.serviceprovider.SimulatorResourceServer;
41
42 public class ResourceManager {
43
44     private Map<String, Map<String, SimulatorResource>> resourceMap;
45
46     private Map<String, ArrayList<String>>              orderedResourceUriMap;
47
48     private StandardConfiguration                       stdConfig;
49
50     private SimulatorResource                           currentResourceInSelection;
51
52     private List<IResourceListChangedUIListener>        resourceListChangedUIListeners;
53
54     private List<IResourceSelectionChangedUIListener>   resourceSelectionChangedUIListeners;
55
56     private List<IResourceModelChangedUIListener>       resourceModelChangedUIListeners;
57
58     private List<IAutomationUIListener>                 automationUIListeners;
59
60     private List<IObserverListChangedUIListener>        observerUIListeners;
61
62     private IResourceModelChangedListener               resourceModelChangeListener;
63
64     private IAutomation                                 automationListener;
65
66     private IObserver                                   observer;
67
68     private NotificationSynchronizerThread              synchronizerThread;
69
70     private Thread                                      threadHandle;
71
72     static {
73         System.loadLibrary("SimulatorManager");
74     }
75
76     public ResourceManager() {
77         resourceMap = new HashMap<String, Map<String, SimulatorResource>>();
78         orderedResourceUriMap = new HashMap<String, ArrayList<String>>();
79         stdConfig = new StandardConfiguration();
80
81         resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
82         resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
83         resourceModelChangedUIListeners = new ArrayList<IResourceModelChangedUIListener>();
84         automationUIListeners = new ArrayList<IAutomationUIListener>();
85         observerUIListeners = new ArrayList<IObserverListChangedUIListener>();
86
87         resourceModelChangeListener = new IResourceModelChangedListener() {
88
89             @Override
90             public void onResourceModelChanged(final String resourceURI,
91                     final SimulatorResourceModel resourceModelN) {
92                 synchronizerThread.addToQueue(new Runnable() {
93
94                     @Override
95                     public void run() {
96                         if (null == resourceURI || null == resourceModelN) {
97                             return;
98                         }
99                         SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
100                         if (null == resource) {
101                             return;
102                         }
103                         // Fetch the resource attributes
104                         Map<String, LocalResourceAttribute> resourceAttributeMapNew;
105                         resourceAttributeMapNew = fetchResourceAttributesFromModel(resourceModelN);
106                         if (null == resourceAttributeMapNew) {
107                             return;
108                         }
109                         // Update the resource with new model data
110                         Map<String, LocalResourceAttribute> resourceAttributeMapOld;
111                         resourceAttributeMapOld = resource
112                                 .getResourceAttributesMap();
113                         if (null == resourceAttributeMapOld) {
114                             return;
115                         }
116                         ModelChangeNotificationType notificationType;
117                         Set<LocalResourceAttribute> changeSet = new HashSet<LocalResourceAttribute>();
118                         notificationType = compareAndUpdateLocalAttributes(
119                                 resourceAttributeMapOld,
120                                 resourceAttributeMapNew, changeSet);
121                         if (notificationType != ModelChangeNotificationType.NONE) {
122                             // Update the UI listeners
123                             resourceModelChangedUINotification(
124                                     notificationType, resourceURI, changeSet);
125                         }
126                     }
127                 });
128             }
129         };
130
131         automationListener = new IAutomation() {
132
133             @Override
134             public void onAutomationComplete(final String resourceURI,
135                     final int automationId) {
136                 synchronizerThread.addToQueue(new Runnable() {
137
138                     @Override
139                     public void run() {
140                         System.out.println("onAutomationComplete() entry");
141                         SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
142                         if (null == resource) {
143                             return;
144                         }
145                         System.out
146                                 .println("onAutomationComplete() resource is not null");
147                         // Checking whether this notification is for an
148                         // attribute or a resource
149                         if (resource.isResourceAutomationInProgress()) {
150                             System.out
151                                     .println("onAutomationComplete() for resource");
152                             changeResourceLevelAutomationStatus(resource, false);
153                             // Notify the UI listeners
154                             automationCompleteUINotification(resourceURI, null);
155                         } else if (resource.isAttributeAutomationInProgress()) {
156                             System.out
157                                     .println("onAutomationComplete() for attribute");
158                             // Find the attribute with the given automation id
159                             LocalResourceAttribute attribute;
160                             attribute = getAttributeWithGivenAutomationId(
161                                     resource, automationId);
162                             if (null != attribute) {
163                                 attribute.setAutomationInProgress(false);
164                                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
165                                 // Notify the UI listeners
166                                 automationCompleteUINotification(resourceURI,
167                                         attribute.getAttributeName());
168                             }
169                         } else {
170                             // Ignoring the notification as there are no
171                             // known automation for the current resource.
172                         }
173                     }
174                 });
175             }
176         };
177
178         observer = new IObserver() {
179
180             @Override
181             public void onObserverChanged(final String resourceURI,
182                     final int status, final ObserverInfo observer) {
183                 System.out.println("onObserverListChanged in Manager");
184                 new Thread() {
185                     @Override
186                     public void run() {
187                         if (null == resourceURI) {
188                             return;
189                         }
190                         System.out.println("URI:" + resourceURI);
191                         SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
192                         if (null == resource) {
193                             return;
194                         }
195                         System.out.println("Resource Exist");
196                         // Update the observers information
197                         if (status == 0) {
198                             resource.addObserverInfo(observer);
199                         } else {
200                             resource.removeObserverInfo(observer);
201                         }
202
203                         System.out.println(observer.getAddress() + ","
204                                 + observer.getPort() + "," + observer.getId());
205
206                         System.out.println(resource.getObserver());
207
208                         System.out.println("status:" + status);
209                         // Notify the UI listeners
210                         observerListChangedUINotification(resourceURI);
211                     }
212                 }.start();
213             }
214         };
215
216         synchronizerThread = new NotificationSynchronizerThread();
217         threadHandle = new Thread(synchronizerThread);
218         threadHandle.setName("Simulator service provider event queue");
219         threadHandle.start();
220     }
221
222     private static class NotificationSynchronizerThread implements Runnable {
223
224         LinkedList<Runnable> notificationQueue = new LinkedList<Runnable>();
225
226         @Override
227         public void run() {
228             while (!Thread.interrupted()) {
229                 synchronized (this) {
230                     try {
231                         while (notificationQueue.isEmpty()) {
232                             this.wait();
233                             break;
234                         }
235                     } catch (InterruptedException e) {
236                         return;
237                     }
238                 }
239
240                 Runnable thread;
241                 synchronized (this) {
242                     thread = notificationQueue.pop();
243                 }
244                 try {
245                     thread.run();
246                 } catch (Exception e) {
247                     if (e instanceof InterruptedException) {
248                         return;
249                     }
250                     e.printStackTrace();
251                 }
252             }
253         }
254
255         public void addToQueue(Runnable event) {
256             synchronized (this) {
257                 notificationQueue.add(event);
258                 this.notify();
259             }
260         }
261     }
262
263     // This method gives a list of available RAML resource configurations.
264     public Map<String, String> getResourceConfigurationList() {
265         return stdConfig.getStandardResourceConfigurationList();
266     }
267
268     public String getConfigFilePath(String fileName) {
269         return stdConfig.getFilePath(fileName);
270     }
271
272     public void addResourceListChangedUIListener(
273             IResourceListChangedUIListener resourceListChangedUIListener) {
274         synchronized (resourceListChangedUIListeners) {
275             resourceListChangedUIListeners.add(resourceListChangedUIListener);
276         }
277     }
278
279     public void addResourceSelectionChangedUIListener(
280             IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
281         synchronized (resourceSelectionChangedUIListeners) {
282             resourceSelectionChangedUIListeners
283                     .add(resourceSelectionChangedUIListener);
284         }
285     }
286
287     public void addResourceModelChangedUIListener(
288             IResourceModelChangedUIListener resourceModelChangedUIListener) {
289         synchronized (resourceModelChangedUIListeners) {
290             resourceModelChangedUIListeners.add(resourceModelChangedUIListener);
291         }
292     }
293
294     public void addAutomationUIListener(
295             IAutomationUIListener automationUIListener) {
296         synchronized (automationUIListeners) {
297             automationUIListeners.add(automationUIListener);
298         }
299     }
300
301     public void addObserverListChangedUIListener(
302             IObserverListChangedUIListener observerListChangedUIListener) {
303         synchronized (observerUIListeners) {
304             observerUIListeners.add(observerListChangedUIListener);
305         }
306     }
307
308     public void removeResourceListChangedUIListener(
309             IResourceListChangedUIListener listener) {
310         synchronized (resourceListChangedUIListeners) {
311             if (null != listener && resourceListChangedUIListeners.size() > 0) {
312                 resourceListChangedUIListeners.remove(listener);
313             }
314         }
315     }
316
317     public void removeResourceSelectionChangedUIListener(
318             IResourceSelectionChangedUIListener listener) {
319         synchronized (resourceSelectionChangedUIListeners) {
320             if (null != listener
321                     && resourceSelectionChangedUIListeners.size() > 0) {
322                 resourceSelectionChangedUIListeners.remove(listener);
323             }
324         }
325     }
326
327     public void removeResourceModelChangedUIListener(
328             IResourceModelChangedUIListener listener) {
329         synchronized (resourceModelChangedUIListeners) {
330             if (null != listener && resourceModelChangedUIListeners.size() > 0) {
331                 resourceModelChangedUIListeners.remove(listener);
332             }
333         }
334     }
335
336     public void removeAutomationUIListener(IAutomationUIListener listener) {
337         synchronized (automationUIListeners) {
338             if (null != listener && automationUIListeners.size() > 0) {
339                 automationUIListeners.remove(listener);
340             }
341         }
342     }
343
344     public void removeObserverListChangedUIListener(
345             IObserverListChangedUIListener listener) {
346         synchronized (observerUIListeners) {
347             if (null != listener && observerUIListeners.size() > 0) {
348                 observerUIListeners.remove(listener);
349             }
350         }
351     }
352
353     public synchronized SimulatorResource getCurrentResourceInSelection() {
354         return currentResourceInSelection;
355     }
356
357     public synchronized void setCurrentResourceInSelection(
358             SimulatorResource resource) {
359         this.currentResourceInSelection = resource;
360     }
361
362     private void addResourceUriToOrderedMap(String resourceType,
363             String resourceURI) {
364         if (null != resourceURI && null != resourceType) {
365             synchronized (orderedResourceUriMap) {
366                 ArrayList<String> uriListForType = orderedResourceUriMap
367                         .get(resourceType);
368                 if (null == uriListForType) {
369                     uriListForType = new ArrayList<String>();
370                     orderedResourceUriMap.put(resourceType, uriListForType);
371                 }
372                 uriListForType.add(resourceURI);
373             }
374         }
375     }
376
377     private void removeResourceUriFromOrderedMap(String resourceType,
378             String resourceURI) {
379         synchronized (orderedResourceUriMap) {
380             if (null != resourceURI && null != resourceType) {
381                 ArrayList<String> uriListForType = orderedResourceUriMap
382                         .get(resourceType);
383                 if (null != uriListForType) {
384                     uriListForType.remove(resourceURI);
385                     if (uriListForType.size() < 1) {
386                         orderedResourceUriMap.remove(resourceType);
387                     }
388                 }
389             } else if (null != resourceURI) {
390                 orderedResourceUriMap.remove(resourceType);
391             } else {
392                 orderedResourceUriMap.clear();
393             }
394         }
395     }
396
397     private void addResourceToMap(SimulatorResource simulatorResource) {
398         if (null != simulatorResource) {
399             synchronized (resourceMap) {
400                 Map<String, SimulatorResource> resourceTypeMap;
401                 resourceTypeMap = resourceMap.get(simulatorResource
402                         .getResourceType());
403                 if (null == resourceTypeMap) {
404                     resourceTypeMap = new HashMap<String, SimulatorResource>();
405                     resourceMap.put(simulatorResource.getResourceType(),
406                             resourceTypeMap);
407                 }
408                 resourceTypeMap.put(simulatorResource.getResourceURI(),
409                         simulatorResource);
410             }
411         }
412     }
413
414     private void addResourceToMap(String resourceType,
415             Map<String, SimulatorResource> newResourceTypeMap) {
416         if (null != resourceType && null != newResourceTypeMap) {
417             synchronized (resourceMap) {
418                 Map<String, SimulatorResource> resourceTypeMap = resourceMap
419                         .get(resourceType);
420                 if (null != resourceTypeMap) {
421                     resourceTypeMap.putAll(newResourceTypeMap);
422                 } else {
423                     resourceMap.put(resourceType, newResourceTypeMap);
424                 }
425             }
426         }
427     }
428
429     private void removeResourceFromMap(String resourceType, String resourceURI) {
430         if (null != resourceURI && null != resourceType) {
431             synchronized (resourceMap) {
432                 Map<String, SimulatorResource> resourceTypeMap = resourceMap
433                         .get(resourceType);
434                 if (null != resourceTypeMap) {
435                     resourceTypeMap.remove(resourceURI);
436                     if (resourceTypeMap.size() < 1) {
437                         resourceMap.remove(resourceType);
438                     }
439                 }
440             }
441         }
442     }
443
444     public boolean isResourceExist(String resourceURI) {
445         boolean result = false;
446         if (null != resourceURI) {
447             SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
448             if (null != resource) {
449                 result = true;
450             }
451         }
452         return result;
453     }
454
455     public void createResource(final String configFilePath) {
456         new Thread() {
457             @Override
458             public void run() {
459                 SimulatorResourceServer resourceServerN;
460                 resourceServerN = SimulatorManager.createResource(
461                         configFilePath, resourceModelChangeListener);
462                 if (null == resourceServerN) {
463                     return;
464                 }
465                 SimulatorResource simulatorResource;
466                 simulatorResource = fetchResourceData(resourceServerN);
467                 if (null != simulatorResource) {
468                     addResourceToMap(simulatorResource);
469                     addResourceUriToOrderedMap(
470                             simulatorResource.getResourceType(),
471                             simulatorResource.getResourceURI());
472                     resourceCreatedUINotification();
473
474                     // Print the resource data
475                     simulatorResource.printResourceInfo();
476                 }
477                 // Set the observer for the created resource
478                 resourceServerN.setObserverCallback(observer);
479             }
480         }.start();
481     }
482
483     public void createResource(final String configFilePath,
484             final int noOfInstances) {
485         new Thread() {
486             @Override
487             public void run() {
488                 Map<String, SimulatorResource> resourceTypeMap;
489                 SimulatorResourceServer[] simulatorResourceServers = null;
490                 simulatorResourceServers = SimulatorManager.createResource(
491                         configFilePath, noOfInstances,
492                         resourceModelChangeListener);
493                 if (null == simulatorResourceServers) {
494                     return;
495                 }
496                 resourceTypeMap = new HashMap<String, SimulatorResource>();
497                 SimulatorResource resource;
498                 String uri;
499                 for (SimulatorResourceServer resourceServerN : simulatorResourceServers) {
500                     resource = fetchResourceData(resourceServerN);
501                     if (null != resource) {
502                         uri = resource.getResourceURI();
503                         resourceTypeMap.put(uri, resource);
504                         addResourceUriToOrderedMap(resource.getResourceType(),
505                                 uri);
506                     }
507                     // Set the observer for the created resource
508                     resourceServerN.setObserverCallback(observer);
509                 }
510
511                 // Find the resourceType and add it to the local data
512                 // structure and notify UI Listeners
513                 if (resourceTypeMap.size() > 0) {
514                     String resourceType;
515                     Set<String> uriSet = resourceTypeMap.keySet();
516                     Iterator<String> itr = uriSet.iterator();
517                     if (itr.hasNext()) {
518                         SimulatorResource simResource = resourceTypeMap.get(itr
519                                 .next());
520                         if (null != simResource) {
521                             resourceType = simResource.getResourceType();
522
523                             addResourceToMap(resourceType, resourceTypeMap);
524                             resourceCreatedUINotification();
525                         }
526                     }
527                 }
528             }
529         }.start();
530     }
531
532     private SimulatorResource fetchResourceData(
533             SimulatorResourceServer resourceServerN) {
534         SimulatorResource simulatorResource = null;
535         if (null != resourceServerN) {
536             simulatorResource = new SimulatorResource();
537             simulatorResource.setResourceServer(resourceServerN);
538             simulatorResource.setResourceURI(resourceServerN.getURI());
539             simulatorResource
540                     .setResourceType(resourceServerN.getResourceType());
541             simulatorResource.setResourceName(resourceServerN.getName());
542             simulatorResource.setResourceInterface(resourceServerN
543                     .getInterfaceType());
544
545             SimulatorResourceModel resourceModelN = resourceServerN.getModel();
546             if (null != resourceModelN) {
547                 simulatorResource.setResourceModel(resourceModelN);
548
549                 // Fetch the resource attributes
550                 Map<String, LocalResourceAttribute> resourceAttributeMap;
551                 resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
552                 if (null != resourceAttributeMap) {
553                     simulatorResource
554                             .setResourceAttributesMap(resourceAttributeMap);
555                 }
556             }
557         }
558         return simulatorResource;
559     }
560
561     private Map<String, LocalResourceAttribute> fetchResourceAttributesFromModel(
562             SimulatorResourceModel resourceModelN) {
563         Map<String, LocalResourceAttribute> resourceAttributeMap = null;
564         if (null != resourceModelN) {
565             Map<String, ResourceAttribute> attributeMapN;
566             attributeMapN = resourceModelN.getAttributes();
567             if (null != attributeMapN) {
568                 resourceAttributeMap = new HashMap<String, LocalResourceAttribute>();
569
570                 Set<String> attNameSet = attributeMapN.keySet();
571                 String attName;
572                 Object attValueObj;
573                 ResourceAttribute attributeN;
574                 LocalResourceAttribute attribute;
575                 Iterator<String> attNameItr = attNameSet.iterator();
576                 while (attNameItr.hasNext()) {
577                     attName = attNameItr.next();
578                     attributeN = attributeMapN.get(attName);
579                     if (null != attributeN) {
580                         attribute = new LocalResourceAttribute();
581                         attribute.setResourceAttribute(attributeN);
582                         attribute.setAttributeName(attName);
583
584                         attValueObj = attributeN.getValue();
585                         if (null != attValueObj) {
586                             attribute.setAttributeValue(attValueObj);
587                         }
588
589                         // Set the attribute type
590                         attribute.setAttValBaseType(attributeN.getBaseType());
591                         attribute.setAttValType(attributeN.getType());
592
593                         // Set the range and allowed values
594                         Range range = attributeN.getRange();
595                         if (null != range) {
596                             attribute.setMinValue(range.getMin());
597                             attribute.setMaxValue(range.getMax());
598                             System.out.println("Fetching range");
599                             System.out.println(range.getMin() + ","
600                                     + range.getMax());
601                         } else {
602                             Object[] values = attributeN.getAllowedValues();
603                             System.out.println("Size of allowed values:"
604                                     + values.length);
605                             if (null != values && values.length > 0) {
606                                 List<Object> valueList = new ArrayList<Object>();
607                                 for (Object obj : values) {
608                                     valueList.add(obj);
609                                 }
610                                 attribute.setAllowedValues(valueList);
611                             }
612                         }
613
614                         // Initially disabling the automation
615                         attribute.setAutomationInProgress(false);
616
617                         // TODO: Temporarily setting the interval to 500.
618                         // This value should come from the native layer.
619                         // Native implementation is in progress.
620                         attribute
621                                 .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
622
623                         // Setting the default automation type
624                         attribute
625                                 .setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
626
627                         resourceAttributeMap.put(attName, attribute);
628                     }
629                 }
630             }
631         }
632         return resourceAttributeMap;
633     }
634
635     public void deleteResourceByURI(final String resourceURI) {
636         if (null != resourceURI) {
637             new Thread() {
638                 @Override
639                 public void run() {
640                     SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
641                     if (null != resource) {
642                         String resourceType = resource.getResourceType();
643
644                         // Unregister the resource from the platform
645                         deleteResource(resource);
646
647                         // Delete from the local data structure
648                         deleteLocalResourceDetails(resourceType, resourceURI);
649
650                         // Notify the UI listener for removing this resource
651                         // from UI
652                         resourceDeletedUINotification();
653
654                         if (null != currentResourceInSelection
655                                 && resource == currentResourceInSelection) {
656                             // Listeners might query the resource being deleted
657                             // if exists. So set the currently selection to
658                             // null.
659                             setCurrentResourceInSelection(null);
660
661                             // Notify all observers for resource selection
662                             // change event
663                             resourceSelectionChangedUINotification();
664                         }
665                     }
666                 }
667             }.start();
668         }
669     }
670
671     private SimulatorResource getSimulatorResourceByURI(String resourceURI) {
672         SimulatorResource resource = null;
673         if (null != resourceURI) {
674             synchronized (resourceMap) {
675                 Set<String> typeSet = resourceMap.keySet();
676                 Iterator<String> typeItr = typeSet.iterator();
677                 String resourceType;
678                 Map<String, SimulatorResource> resourceTypeMap;
679                 while (typeItr.hasNext()) {
680                     resourceType = typeItr.next();
681                     resourceTypeMap = resourceMap.get(resourceType);
682                     if (null != resourceTypeMap) {
683                         resource = resourceTypeMap.get(resourceURI);
684                         if (null != resource) {
685                             break;
686                         }
687                     }
688                 }
689             }
690         }
691         return resource;
692     }
693
694     private void deleteResource(SimulatorResource resource) {
695         if (null != resource) {
696             SimulatorResourceServer resourceServerN = resource
697                     .getResourceServer();
698             if (null != resourceServerN) {
699                 SimulatorManager.deleteResource(resourceServerN);
700             }
701         }
702     }
703
704     public void deleteResourceByType(final String resourceType) {
705         if (null != resourceType) {
706             new Thread() {
707                 @Override
708                 public void run() {
709                     // Unregister the resources from the platform
710                     deleteResource(resourceType);
711
712                     // Delete from the local data structure
713                     deleteLocalResourceDetails(resourceType, null);
714
715                     // Notify the UI listener for removing this resource from UI
716                     resourceDeletedUINotification();
717
718                     if (null != currentResourceInSelection
719                             && resourceType.equals(currentResourceInSelection
720                                     .getResourceType())) {
721                         // Listeners might query the resource being deleted if
722                         // exists. So set the currently selection to null.
723                         setCurrentResourceInSelection(null);
724
725                         // Notify all observers for resource selection change
726                         // event
727                         resourceSelectionChangedUINotification();
728                     }
729                 }
730             }.start();
731         }
732     }
733
734     private void deleteResource(String resourceType) {
735         if (null != resourceType) {
736             SimulatorManager.deleteResources(resourceType);
737         }
738     }
739
740     public void deleteAllResources() {
741         new Thread() {
742             @Override
743             public void run() {
744                 // Unregister the resources from the platform
745                 deleteResource();
746
747                 // Delete from the local data structure
748                 deleteLocalResourceDetails(null, null);
749
750                 // Notify the UI listener for removing this resource from UI
751                 resourceDeletedUINotification();
752
753                 // Listeners might query the resource being deleted if exists.
754                 // So set the currently selection to null.
755                 setCurrentResourceInSelection(null);
756
757                 // Notify all observers for resource selection change event
758                 resourceSelectionChangedUINotification();
759             }
760         }.start();
761     }
762
763     private void deleteResource() {
764         SimulatorManager.deleteResources(null);
765     }
766
767     private void deleteLocalResourceDetails(String resourceType,
768             String resourceURI) {
769         if (null != resourceType && null != resourceURI) {
770             removeResourceFromMap(resourceType, resourceURI);
771             removeResourceUriFromOrderedMap(resourceType, resourceURI);
772         } else {
773             synchronized (resourceMap) {
774                 if (null != resourceType) {
775                     removeResourceUriFromOrderedMap(resourceType, null);
776                     resourceMap.remove(resourceType);
777                 } else {
778                     resourceMap.clear();
779                     removeResourceUriFromOrderedMap(null, null);
780                 }
781             }
782         }
783     }
784
785     private void resourceCreatedUINotification() {
786         synchronized (resourceListChangedUIListeners) {
787             if (resourceListChangedUIListeners.size() > 0) {
788                 IResourceListChangedUIListener listener;
789                 Iterator<IResourceListChangedUIListener> listenerItr = resourceListChangedUIListeners
790                         .iterator();
791                 while (listenerItr.hasNext()) {
792                     listener = listenerItr.next();
793                     if (null != listener) {
794                         listener.onResourceCreation();
795                     }
796                 }
797             }
798         }
799     }
800
801     private void resourceDeletedUINotification() {
802         synchronized (resourceListChangedUIListeners) {
803             if (resourceListChangedUIListeners.size() > 0) {
804                 IResourceListChangedUIListener listener;
805                 Iterator<IResourceListChangedUIListener> listenerItr = resourceListChangedUIListeners
806                         .iterator();
807                 while (listenerItr.hasNext()) {
808                     listener = listenerItr.next();
809                     if (null != listener) {
810                         listener.onResourceDeletion();
811                     }
812                 }
813             }
814         }
815     }
816
817     private void resourceSelectionChangedUINotification() {
818         synchronized (resourceSelectionChangedUIListeners) {
819             if (resourceSelectionChangedUIListeners.size() > 0) {
820                 IResourceSelectionChangedUIListener listener;
821                 Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
822                         .iterator();
823                 while (listenerItr.hasNext()) {
824                     listener = listenerItr.next();
825                     if (null != listener) {
826                         listener.onResourceSelectionChange();
827                     }
828                 }
829             }
830         }
831     }
832
833     private void resourceModelChangedUINotification(
834             ModelChangeNotificationType notificationType, String resourceURI,
835             Set<LocalResourceAttribute> changeSet) {
836         synchronized (resourceModelChangedUIListeners) {
837             if (resourceModelChangedUIListeners.size() > 0
838                     && notificationType != ModelChangeNotificationType.NONE
839                     && null != resourceURI) {
840                 IResourceModelChangedUIListener listener;
841                 Iterator<IResourceModelChangedUIListener> listenerItr = resourceModelChangedUIListeners
842                         .iterator();
843                 while (listenerItr.hasNext()) {
844                     listener = listenerItr.next();
845                     if (null != listener) {
846                         listener.onResourceModelChange(notificationType,
847                                 resourceURI, changeSet);
848                     }
849                 }
850             }
851         }
852     }
853
854     private void resourceAutomationStartedUINotification(String resourceURI) {
855         synchronized (automationUIListeners) {
856             if (automationUIListeners.size() > 0 && null != resourceURI) {
857                 IAutomationUIListener listener;
858                 Iterator<IAutomationUIListener> listenerItr = automationUIListeners
859                         .iterator();
860                 while (listenerItr.hasNext()) {
861                     listener = listenerItr.next();
862                     if (null != listener) {
863                         listener.onResourceAutomationStart(resourceURI);
864                     }
865                 }
866             }
867         }
868     }
869
870     private void automationCompleteUINotification(String resourceURI,
871             String attName) {
872         synchronized (automationUIListeners) {
873             if (automationUIListeners.size() > 0 && null != resourceURI) {
874                 IAutomationUIListener listener;
875                 Iterator<IAutomationUIListener> listenerItr = automationUIListeners
876                         .iterator();
877                 while (listenerItr.hasNext()) {
878                     listener = listenerItr.next();
879                     if (null != listener) {
880                         listener.onAutomationComplete(resourceURI, attName);
881                     }
882                 }
883             }
884         }
885     }
886
887     private void observerListChangedUINotification(String resourceURI) {
888         synchronized (observerUIListeners) {
889             if (observerUIListeners.size() > 0 && null != resourceURI) {
890                 IObserverListChangedUIListener listener;
891                 Iterator<IObserverListChangedUIListener> listenerItr = observerUIListeners
892                         .iterator();
893                 while (listenerItr.hasNext()) {
894                     listener = listenerItr.next();
895                     if (null != listener) {
896                         listener.onObserverListChanged(resourceURI);
897                     }
898                 }
899             }
900         }
901     }
902
903     public List<String> getResourceTypeList() {
904         List<String> typeList = null;
905         synchronized (resourceMap) {
906             if (resourceMap.size() > 0) {
907                 typeList = new ArrayList<String>();
908                 Set<String> typeSet = resourceMap.keySet();
909                 Iterator<String> typeItr = typeSet.iterator();
910                 while (typeItr.hasNext()) {
911                     typeList.add(typeItr.next());
912                 }
913             }
914         }
915         return typeList;
916     }
917
918     public boolean isTypeExist(String resType) {
919         synchronized (resourceMap) {
920             if (resourceMap.containsKey(resType)) {
921                 return true;
922             }
923         }
924         return false;
925     }
926
927     public List<String> getURIList() {
928         List<String> list = null;
929         synchronized (orderedResourceUriMap) {
930             Set<String> typeSet = orderedResourceUriMap.keySet();
931             List<String> typeList = Utility.convertSetToList(typeSet);
932             if (null == typeList || typeList.size() < 1) {
933                 return null;
934             }
935             list = new ArrayList<String>();
936
937             // Sort the types
938             Collections.sort(typeList);
939
940             // Add all URIs to the output list
941             Iterator<String> typeItr = typeList.iterator();
942             while (typeItr.hasNext()) {
943                 List<String> l = orderedResourceUriMap.get(typeItr.next());
944                 if (null != l) {
945                     list.addAll(l);
946                 }
947             }
948         }
949         return list;
950     }
951
952     public void resourceSelectionChanged(final String selectedItem) {
953         new Thread() {
954             @Override
955             public void run() {
956                 // Check whether the item selected is a resource or resource
957                 // category
958                 if (isTypeExist(selectedItem)) {
959                     // Given item is a resource Type
960                     setCurrentResourceInSelection(null);
961                 } else {
962                     // Given item is a resource URI
963                     SimulatorResource resource = getSimulatorResourceByURI(selectedItem);
964                     if (null != resource) {
965                         setCurrentResourceInSelection(resource);
966                     } else {
967                         setCurrentResourceInSelection(null);
968                     }
969                 }
970                 // Notify all observers for resource selection change event
971                 resourceSelectionChangedUINotification();
972             }
973         }.start();
974     }
975
976     public List<MetaProperty> getMetaProperties(SimulatorResource resource) {
977         if (null != resource) {
978             String propName;
979             String propValue;
980
981             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
982
983             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
984                 propName = Constants.META_PROPERTIES[index];
985                 if (propName.equals(Constants.RESOURCE_URI)) {
986                     propValue = resource.getResourceURI();
987                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
988                     propValue = resource.getResourceType();
989                 } else if (propName.equals(Constants.RESOURCE_UID)) {
990                     // propValue = resource.getResourceUID();
991                     propValue = "Dummy123"; // TODO: Temporarily adding dummy
992                                             // value to
993                     // show in UI
994                 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
995                     // propValue = resource.getConnectivityType();
996                     propValue = "IP"; // TODO: Temporarily adding dummy value to
997                                       // see
998                     // show UI
999                 } else {
1000                     propValue = null;
1001                 }
1002                 if (null != propValue) {
1003                     metaPropertyList.add(new MetaProperty(propName, propValue));
1004                 }
1005             }
1006
1007             return metaPropertyList;
1008         }
1009         return null;
1010     }
1011
1012     public List<LocalResourceAttribute> getAttributes(SimulatorResource resource) {
1013         List<LocalResourceAttribute> attList = null;
1014         if (null != resource) {
1015             Map<String, LocalResourceAttribute> attMap = resource
1016                     .getResourceAttributesMap();
1017             if (null != attMap && attMap.size() > 0) {
1018                 attList = new ArrayList<LocalResourceAttribute>();
1019                 Set<String> attNameSet = attMap.keySet();
1020                 String attName;
1021                 LocalResourceAttribute attribute;
1022                 // ResourceAttribute attributeClone;
1023                 Iterator<String> attNameItr = attNameSet.iterator();
1024                 while (attNameItr.hasNext()) {
1025                     attName = attNameItr.next();
1026                     attribute = attMap.get(attName);
1027                     if (null != attribute) {
1028                         // attributeClone =
1029                         // ResourceAttribute.clone(attribute);
1030                         attList.add(attribute);
1031                     }
1032                 }
1033             }
1034         }
1035         return attList;
1036     }
1037
1038     public void attributeValueUpdated(SimulatorResource resource,
1039             String attributeName, String value) {
1040         if (null != resource && null != attributeName && null != value) {
1041             SimulatorResourceServer server = resource.getResourceServer();
1042             if (null != server) {
1043                 LocalResourceAttribute att = resource
1044                         .getAttribute(attributeName);
1045                 if (null == att) {
1046                     return;
1047                 }
1048                 Type baseType = att.getAttValBaseType();
1049                 if (baseType == Type.STRING) {
1050                     server.updateAttributeStringN(attributeName, value);
1051                 } else if (baseType == Type.INT) {
1052                     int val;
1053                     try {
1054                         val = Integer.parseInt(value);
1055                     } catch (NumberFormatException nfe) {
1056                         return;
1057                     }
1058                     server.updateAttributeInteger(attributeName, val);
1059                 } else if (baseType == Type.DOUBLE) {
1060                     double val;
1061                     try {
1062                         val = Double.parseDouble(value);
1063                     } catch (NumberFormatException nfe) {
1064                         return;
1065                     }
1066                     server.updateAttributeDouble(attributeName, val);
1067                 } else if (baseType == Type.BOOL) {
1068                     boolean val;
1069                     val = Boolean.parseBoolean(value);
1070                     server.updateAttributeBoolean(attributeName, val);
1071                 }
1072             }
1073         }
1074     }
1075
1076     private ModelChangeNotificationType compareAndUpdateLocalAttributes(
1077             Map<String, LocalResourceAttribute> resourceAttributeMapOld,
1078             Map<String, LocalResourceAttribute> resourceAttributeMapNew,
1079             Set<LocalResourceAttribute> changeSet) {
1080         ModelChangeNotificationType notificationType = ModelChangeNotificationType.NONE;
1081         if (null != resourceAttributeMapOld && null != resourceAttributeMapNew) {
1082             Set<String> oldMapKeySet = resourceAttributeMapOld.keySet();
1083             Iterator<String> attributeMapOldItr = oldMapKeySet.iterator();
1084             String attName;
1085             LocalResourceAttribute attributeOld;
1086             LocalResourceAttribute attributeNew;
1087             Object attValueOld;
1088             Object attValueNew;
1089             String oldValueStr;
1090             String newValueStr;
1091             while (attributeMapOldItr.hasNext()) {
1092                 attName = attributeMapOldItr.next();
1093                 if (resourceAttributeMapNew.containsKey(attName)) {
1094                     attributeOld = resourceAttributeMapOld.get(attName);
1095                     attributeNew = resourceAttributeMapNew.get(attName);
1096                     // Copy the attribute value from new to old if the value
1097                     // has been changed
1098                     // Comparing only the attribute's value considering the
1099                     // fact that only the value can be changed
1100                     if (null != attributeOld && null != attributeNew) {
1101                         attValueOld = attributeOld.getAttributeValue();
1102                         attValueNew = attributeNew.getAttributeValue();
1103
1104                         oldValueStr = String.valueOf(attValueOld);
1105                         newValueStr = String.valueOf(attValueNew);
1106
1107                         if (null != oldValueStr && null != newValueStr) {
1108                             if (!oldValueStr.equals(newValueStr)) {
1109                                 attributeOld.setAttributeValue(attValueNew);
1110                                 notificationType = ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED;
1111                                 changeSet.add(attributeOld);
1112                             }
1113                         }
1114                     }
1115                     resourceAttributeMapNew.remove(attName);
1116                 } else {
1117                     // Attribute doesn't exist in the new model. Hence
1118                     // removing it from the model.
1119                     resourceAttributeMapOld.remove(attName);
1120                     notificationType = ModelChangeNotificationType.ATTRIBUTE_REMOVED;
1121                 }
1122             }
1123             // Check for new attributes in the new model
1124             if (resourceAttributeMapNew.size() > 0) {
1125                 Set<String> remainingAttSet = resourceAttributeMapNew.keySet();
1126                 Iterator<String> remainingAttItr = remainingAttSet.iterator();
1127                 LocalResourceAttribute attribute;
1128                 while (remainingAttItr.hasNext()) {
1129                     attName = remainingAttItr.next();
1130                     if (null != attName) {
1131                         attribute = resourceAttributeMapNew.get(attName);
1132                         if (null != attribute) {
1133                             resourceAttributeMapOld.put(attName, attribute);
1134                         }
1135                     }
1136                 }
1137                 notificationType = ModelChangeNotificationType.ATTRIBUTE_ADDED;
1138             }
1139         }
1140         return notificationType;
1141     }
1142
1143     public int startAutomation(SimulatorResource resource,
1144             LocalResourceAttribute attribute, AutomationType autoType,
1145             int autoUpdateInterval) {
1146         int autoId = -1;
1147         if (null != resource && null != attribute) {
1148             SimulatorResourceServer resourceServerN = resource
1149                     .getResourceServer();
1150             if (null != resourceServerN) {
1151                 String attrName = attribute.getAttributeName();
1152                 autoId = resourceServerN.startAttributeAutomation(attrName,
1153                         autoType.ordinal(), automationListener);
1154                 if (-1 != autoId) {
1155                     attribute.setAutomationId(autoId);
1156                     attribute.setAutomationType(autoType);
1157                     attribute.setAutomationUpdateInterval(autoUpdateInterval);
1158                     attribute.setAutomationInProgress(true);
1159                     resource.setAttributeAutomationInProgress(true);
1160                 } else {
1161                     attribute.setAutomationInProgress(false);
1162                 }
1163             }
1164         }
1165         return autoId;
1166     }
1167
1168     public void stopAutomation(SimulatorResource resource,
1169             LocalResourceAttribute att, int autoId) {
1170         if (null != resource) {
1171             SimulatorResourceServer resourceServerN = resource
1172                     .getResourceServer();
1173             if (null != resourceServerN) {
1174                 resourceServerN.stopAutomation(autoId);
1175                 // Change the automation status
1176                 att.setAutomationInProgress(false);
1177                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
1178             }
1179         }
1180     }
1181
1182     private boolean isAnyAttributeInAutomation(SimulatorResource resource) {
1183         if (null == resource) {
1184             return false;
1185         }
1186         Map<String, LocalResourceAttribute> attMap = resource
1187                 .getResourceAttributesMap();
1188         if (null == attMap) {
1189             return false;
1190         }
1191         boolean status = false;
1192         Set<String> keySet = attMap.keySet();
1193         Iterator<String> attItr = keySet.iterator();
1194         while (attItr.hasNext()) {
1195             LocalResourceAttribute attribute = attMap.get(attItr.next());
1196             if (attribute.isAutomationInProgress()) {
1197                 status = true;
1198                 break;
1199             }
1200         }
1201         return status;
1202     }
1203
1204     private LocalResourceAttribute getAttributeWithGivenAutomationId(
1205             SimulatorResource resource, int automationId) {
1206         LocalResourceAttribute targetAttribute = null;
1207         if (null != resource) {
1208             Map<String, LocalResourceAttribute> attributeMap = resource
1209                     .getResourceAttributesMap();
1210             if (null != attributeMap) {
1211                 Set<String> attNameSet = attributeMap.keySet();
1212                 Iterator<String> attNameItr = attNameSet.iterator();
1213                 String attName;
1214                 LocalResourceAttribute attribute;
1215                 while (attNameItr.hasNext()) {
1216                     attName = attNameItr.next();
1217                     if (null != attName) {
1218                         attribute = attributeMap.get(attName);
1219                         if (null != attribute) {
1220                             if (attribute.isAutomationInProgress()
1221                                     && (attribute.getAutomationId() == automationId)) {
1222                                 targetAttribute = attribute;
1223                                 break;
1224                             }
1225                         }
1226                     }
1227                 }
1228             }
1229         }
1230         return targetAttribute;
1231     }
1232
1233     public boolean startResourceAutomationUIRequest(final String resourceURI) {
1234         if (null == resourceURI) {
1235             return false;
1236         }
1237         boolean status = false;
1238         SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
1239         if (null != resource) {
1240             changeResourceLevelAutomationStatus(resource, true);
1241
1242             // Invoke the native automation method
1243             SimulatorResourceServer resourceServer = resource
1244                     .getResourceServer();
1245             if (null != resourceServer) {
1246                 // TODO: Temporarily handling the normal one-time automation for
1247                 // resources
1248                 int autoId = resourceServer.startResourceAutomation(
1249                         AutomationType.NORMAL.ordinal(), automationListener);
1250                 if (-1 == autoId) {
1251                     // Automation request failed and hence status is being
1252                     // rolled back
1253                     changeResourceLevelAutomationStatus(resource, false);
1254                 } else {
1255                     // Automation request accepted.
1256                     resource.setAutomationId(autoId);
1257
1258                     // Notify the UI listeners in a different thread.
1259                     Thread notifyThread = new Thread() {
1260                         public void run() {
1261                             resourceAutomationStartedUINotification(resourceURI);
1262                         };
1263                     };
1264                     notifyThread.setPriority(Thread.MAX_PRIORITY);
1265                     notifyThread.start();
1266
1267                     status = true;
1268                 }
1269             }
1270         }
1271         return status;
1272     }
1273
1274     public void stopResourceAutomationUIRequest(final String resourceURI) {
1275         Thread stopThread = new Thread() {
1276             public void run() {
1277                 SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
1278                 if (null == resource) {
1279                     return;
1280                 }
1281                 int autoId = resource.getAutomationId();
1282                 if (-1 == autoId) {
1283                     return;
1284                 }
1285                 SimulatorResourceServer resourceServer = resource
1286                         .getResourceServer();
1287                 if (null == resourceServer) {
1288                     return;
1289                 }
1290                 // Call native method
1291                 resourceServer.stopAutomation(autoId);
1292
1293                 // Invoke the automation complete callback
1294                 automationListener.onAutomationComplete(resourceURI, autoId);
1295             }
1296         };
1297         stopThread.start();
1298     }
1299
1300     // Changes the automation state of the resource and its attributes
1301     private void changeResourceLevelAutomationStatus(
1302             SimulatorResource resource, boolean status) {
1303
1304         Map<String, LocalResourceAttribute> attributeMap = resource
1305                 .getResourceAttributesMap();
1306         if (null != attributeMap) {
1307             Set<String> attrNameSet = attributeMap.keySet();
1308             Iterator<String> attrNameItr = attrNameSet.iterator();
1309             String attrName;
1310             LocalResourceAttribute attribute;
1311             while (attrNameItr.hasNext()) {
1312                 attrName = attrNameItr.next();
1313                 attribute = attributeMap.get(attrName);
1314                 if (null != attribute) {
1315                     attribute.setAutomationInProgress(status);
1316                 }
1317             }
1318         }
1319         resource.setResourceAutomationInProgress(status);
1320     }
1321
1322     public boolean isResourceAutomationStarted(String resourceURI) {
1323         boolean status = false;
1324         if (null == resourceURI) {
1325             return status;
1326         }
1327
1328         SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
1329         if (null != resource) {
1330             status = resource.isResourceAutomationInProgress();
1331         }
1332         return status;
1333     }
1334
1335     public boolean isAttributeAutomationStarted(String resourceURI) {
1336         boolean status = false;
1337         if (null == resourceURI) {
1338             return status;
1339         }
1340         SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
1341         if (null != resource) {
1342             status = resource.isAttributeAutomationInProgress();
1343         }
1344         return status;
1345     }
1346
1347     public LocalResourceAttribute getAttributeByResourceURI(String uri,
1348             String attName) {
1349         if (null == uri || null == attName) {
1350             return null;
1351         }
1352         SimulatorResource resource = getSimulatorResourceByURI(uri);
1353         if (null == resource) {
1354             return null;
1355         }
1356         Map<String, LocalResourceAttribute> attMap = resource
1357                 .getResourceAttributesMap();
1358         if (null == attMap) {
1359             return null;
1360         }
1361         return attMap.get(attName);
1362     }
1363
1364     public void notifyObserverRequest(SimulatorResource res, int observerId) {
1365         System.out.println("In notifyObserverRequest()");
1366         if (null == res) {
1367             return;
1368         }
1369         SimulatorResourceServer server = res.getResourceServer();
1370         if (null == server) {
1371             return;
1372         }
1373         server.notifyObserver(observerId);
1374     }
1375
1376     public Image getImage(String resourceURI) {
1377         if (null == resourceURI) {
1378             return null;
1379         }
1380         URL url = Activator.getDefault().getBundle()
1381                 .getEntry(getImageURL(resourceURI));
1382         if (null == url) {
1383             return null;
1384         }
1385         return ImageDescriptor.createFromURL(url).createImage();
1386     }
1387
1388     private String getImageURL(String resourceURI) {
1389         // TODO: Hard-coding the image file name temporarily.
1390         // It will be included in a separate class which manages all image
1391         // resources
1392         return "/icons/light_16x16.png";
1393     }
1394
1395     public void shutdown() {
1396         threadHandle.interrupt();
1397     }
1398 }