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