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