Resolved issues and concerns found during overall functionality testing.
[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 org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.swt.widgets.Display;
21
22 import java.text.NumberFormat;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Date;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.Vector;
33
34 import org.oic.simulator.ArrayProperty;
35 import org.oic.simulator.AttributeProperty;
36 import org.oic.simulator.AttributeProperty.Type;
37 import org.oic.simulator.AttributeValue;
38 import org.oic.simulator.AttributeValue.TypeInfo;
39 import org.oic.simulator.AttributeValue.ValueType;
40 import org.oic.simulator.BooleanProperty;
41 import org.oic.simulator.DeviceInfo;
42 import org.oic.simulator.DeviceListener;
43 import org.oic.simulator.DoubleProperty;
44 import org.oic.simulator.ILogger.Level;
45 import org.oic.simulator.IntegerProperty;
46 import org.oic.simulator.PlatformInfo;
47 import org.oic.simulator.SimulatorException;
48 import org.oic.simulator.SimulatorManager;
49 import org.oic.simulator.SimulatorResourceAttribute;
50 import org.oic.simulator.SimulatorResourceModel;
51 import org.oic.simulator.StringProperty;
52 import org.oic.simulator.server.Observer;
53 import org.oic.simulator.server.SimulatorResource;
54 import org.oic.simulator.server.SimulatorResource.AutoUpdateListener;
55 import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
56 import org.oic.simulator.server.SimulatorResource.ObserverListener;
57 import org.oic.simulator.server.SimulatorResource.ResourceModelChangeListener;
58 import org.oic.simulator.server.SimulatorSingleResource;
59
60 import oic.simulator.serviceprovider.Activator;
61 import oic.simulator.serviceprovider.model.AttributeElement;
62 import oic.simulator.serviceprovider.model.MetaProperty;
63 import oic.simulator.serviceprovider.model.Resource;
64 import oic.simulator.serviceprovider.model.ResourceType;
65 import oic.simulator.serviceprovider.model.SingleResource;
66 import oic.simulator.serviceprovider.utils.AttributeValueStringConverter;
67 import oic.simulator.serviceprovider.utils.Constants;
68 import oic.simulator.serviceprovider.utils.Utility;
69
70 /**
71  * This class acts as an interface between the simulator java SDK and the
72  * various UI modules. It maintains all the details of resources and provides
73  * other UI modules with the information required. It also handles model change,
74  * automation, and observer related events from native layer and propagates
75  * those events to the registered UI listeners.
76  */
77 public class ResourceManager {
78
79     private Data                           data;
80
81     private Resource                       currentResourceInSelection;
82
83     private ResourceModelChangeListener    resourceModelChangeListener;
84
85     private AutoUpdateListener             automationListener;
86
87     private ObserverListener               observer;
88
89     private DeviceListener                 deviceListener;
90
91     private NotificationSynchronizerThread synchronizerThread;
92
93     private Thread                         threadHandle;
94
95     private DeviceInfo                     deviceInfo;
96     private PlatformInfo                   platformInfo;
97
98     private String                         deviceName;
99
100     public ResourceManager() {
101         data = new Data();
102
103         deviceListener = new DeviceListener() {
104
105             @Override
106             public void onDeviceFound(final String host,
107                     final DeviceInfo deviceInfo) {
108                 if (null != ResourceManager.this.deviceInfo
109                         || null == deviceInfo || null == host) {
110                     return;
111                 }
112                 synchronizerThread.addToQueue(new Runnable() {
113                     @Override
114                     public void run() {
115                         String rcvdDeviceName = deviceInfo.getName();
116                         if (null == rcvdDeviceName) {
117                             return;
118                         }
119                         if (deviceName.equalsIgnoreCase(rcvdDeviceName)) {
120                             ResourceManager.this.deviceInfo = deviceInfo;
121
122                             // Notify the UI Listeners
123                             UiListenerHandler.getInstance()
124                                     .deviceInfoReceivedNotification();
125                         }
126                     }
127                 });
128             }
129         };
130
131         resourceModelChangeListener = new ResourceModelChangeListener() {
132
133             @Override
134             public void onResourceModelChanged(final String resourceURI,
135                     final SimulatorResourceModel resourceModelN) {
136                 synchronizerThread.addToQueue(new Runnable() {
137
138                     @Override
139                     public void run() {
140                         if (null == resourceURI || null == resourceModelN) {
141                             return;
142                         }
143
144                         Display.getDefault().asyncExec(new Runnable() {
145                             @Override
146                             public void run() {
147                                 Resource resource = data
148                                         .getResourceByURI(resourceURI);
149                                 if (null != resource) {
150                                     try {
151                                         resource.updateResourceRepresentation(resourceModelN);
152                                     } catch (NumberFormatException e) {
153                                         Activator
154                                                 .getDefault()
155                                                 .getLogManager()
156                                                 .log(Level.ERROR.ordinal(),
157                                                         new Date(),
158                                                         "Error while trying to update the attributes.\n"
159                                                                 + Utility
160                                                                         .getSimulatorErrorString(
161                                                                                 e,
162                                                                                 null));
163                                     }
164                                 }
165                             }
166                         });
167                     }
168                 });
169             }
170         };
171
172         automationListener = new AutoUpdateListener() {
173
174             @Override
175             public void onUpdateComplete(final String resourceURI,
176                     final int automationId) {
177                 synchronizerThread.addToQueue(new Runnable() {
178
179                     @Override
180                     public void run() {
181                         SingleResource resource = data
182                                 .getSingleResourceByURI(resourceURI);
183                         if (null == resource) {
184                             return;
185                         }
186                         // Checking whether this notification is for an
187                         // attribute or a resource
188                         if (resource.isResourceAutomationInProgress()) {
189                             changeResourceLevelAutomationStatus(resource, false);
190                             // Notify the UI listeners
191                             UiListenerHandler.getInstance()
192                                     .automationCompleteUINotification(resource,
193                                             null);
194                         } else if (resource.isAttributeAutomationInProgress()) {
195                             // Find the attribute with the given automation id
196                             final AttributeElement attribute = getAttributeWithGivenAutomationId(
197                                     resource, automationId);
198                             if (null != attribute) {
199                                 attribute.setAutoUpdateState(false);
200                                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
201                             } else {
202                                 // Setting the attribute automation status to
203                                 // false.
204                                 resource.setAttributeAutomationInProgress(false);
205                             }
206                         }
207                     }
208                 });
209             }
210         };
211
212         observer = new ObserverListener() {
213
214             public void onObserverChanged(final String resourceURI,
215                     final int status, final Observer observer) {
216                 new Thread() {
217                     @Override
218                     public void run() {
219                         if (null == resourceURI || null == observer) {
220                             return;
221                         }
222                         Resource resource = data.getResourceByURI(resourceURI);
223                         if (null == resource) {
224                             return;
225                         }
226                         // Update the observers information
227                         if (status == 0) {
228                             resource.addObserverInfo(observer);
229                         } else {
230                             resource.removeObserverInfo(observer);
231                         }
232                         // Notify the UI listeners
233                         UiListenerHandler.getInstance()
234                                 .observerListChangedUINotification(resource);
235                     }
236                 }.start();
237             }
238
239             @Override
240             public void onObserverAdded(String resourceURI, Observer observer) {
241                 onObserverChanged(resourceURI, 0, observer);
242             }
243
244             @Override
245             public void onObserverRemoved(String resourceURI, Observer observer) {
246                 onObserverChanged(resourceURI, 1, observer);
247             }
248         };
249
250         synchronizerThread = new NotificationSynchronizerThread();
251         threadHandle = new Thread(synchronizerThread);
252         threadHandle.setName("Simulator service provider event queue");
253         threadHandle.start();
254
255         // Set the default device name.
256         deviceName = "IoTivity Simulator";
257         try {
258             SimulatorManager.setDeviceInfo(deviceName);
259         } catch (SimulatorException e) {
260             Activator
261                     .getDefault()
262                     .getLogManager()
263                     .log(Level.ERROR.ordinal(),
264                             new Date(),
265                             "Error while registering the device info.\n"
266                                     + Utility.getSimulatorErrorString(e, null));
267         }
268
269         // Set the default platform information.
270         platformInfo = new PlatformInfo();
271         platformInfo.setPlatformID("Samsung Platform Identifier");
272         platformInfo.setManufacturerName("Samsung");
273         platformInfo.setManufacturerUrl("www.samsung.com");
274         platformInfo.setModelNumber("Samsung Model Num01");
275         platformInfo.setDateOfManufacture("2015-09-10T11:10:30Z");
276         platformInfo.setPlatformVersion("PlatformVersion01");
277         platformInfo.setOperationSystemVersion("OSVersion01");
278         platformInfo.setHardwareVersion("HardwareVersion01");
279         platformInfo.setFirmwareVersion("FirwareVersion01");
280         platformInfo.setSupportUrl("http://www.samsung.com/support");
281         platformInfo.setSystemTime("2015-09-10T11:10:30Z");
282         try {
283             SimulatorManager.setPlatformInfo(platformInfo);
284         } catch (SimulatorException e) {
285             Activator
286                     .getDefault()
287                     .getLogManager()
288                     .log(Level.ERROR.ordinal(),
289                             new Date(),
290                             "Error while registering the platform info.\n"
291                                     + Utility.getSimulatorErrorString(e, null));
292         }
293
294         // Get the device information to show other details of the device in UI.
295         try {
296             SimulatorManager.findDevices("", deviceListener);
297         } catch (SimulatorException e) {
298             Activator
299                     .getDefault()
300                     .getLogManager()
301                     .log(Level.ERROR.ordinal(),
302                             new Date(),
303                             "Failed to get the local device information.\n"
304                                     + Utility.getSimulatorErrorString(e, null));
305         }
306     }
307
308     private static class NotificationSynchronizerThread implements Runnable {
309
310         LinkedList<Runnable> notificationQueue = new LinkedList<Runnable>();
311
312         @Override
313         public void run() {
314             while (!Thread.interrupted()) {
315                 synchronized (this) {
316                     try {
317                         while (notificationQueue.isEmpty()) {
318                             this.wait();
319                             break;
320                         }
321                     } catch (InterruptedException e) {
322                         return;
323                     }
324                 }
325
326                 Runnable thread;
327                 synchronized (this) {
328                     thread = notificationQueue.pop();
329                 }
330                 try {
331                     thread.run();
332                 } catch (Exception e) {
333                     if (e instanceof InterruptedException) {
334                         return;
335                     }
336                     e.printStackTrace();
337                 }
338             }
339         }
340
341         public void addToQueue(Runnable event) {
342             synchronized (this) {
343                 notificationQueue.add(event);
344                 this.notify();
345             }
346         }
347     }
348
349     public void setDeviceInfo(List<MetaProperty> metaProperties) {
350         if (null == metaProperties || metaProperties.size() < 1) {
351             return;
352         }
353         Iterator<MetaProperty> itr = metaProperties.iterator();
354         MetaProperty prop;
355         String propName;
356         String propValue;
357         boolean found = false;
358         while (itr.hasNext()) {
359             prop = itr.next();
360             propName = prop.getPropName();
361             propValue = prop.getPropValue();
362             if (propName.equals(Constants.DEVICE_NAME)) {
363                 this.deviceName = propValue;
364                 found = true;
365                 break;
366             }
367         }
368
369         if (!found) {
370             return;
371         }
372
373         try {
374             SimulatorManager.setDeviceInfo(deviceName);
375         } catch (SimulatorException e) {
376             Activator
377                     .getDefault()
378                     .getLogManager()
379                     .log(Level.ERROR.ordinal(),
380                             new Date(),
381                             "Error while registering the device info.\n"
382                                     + Utility.getSimulatorErrorString(e, null));
383         }
384     }
385
386     public boolean isDeviceInfoValid(List<MetaProperty> metaProperties) {
387         if (null == metaProperties || metaProperties.size() < 1) {
388             return false;
389         }
390
391         Iterator<MetaProperty> itr = metaProperties.iterator();
392         MetaProperty prop;
393         String propName;
394         String propValue;
395         while (itr.hasNext()) {
396             prop = itr.next();
397             propName = prop.getPropName();
398             propValue = prop.getPropValue();
399             if (propName.equals(Constants.DEVICE_NAME)) {
400                 if (null == propValue || propValue.length() < 1) {
401                     return false;
402                 }
403                 break;
404             }
405         }
406         return true;
407     }
408
409     public List<MetaProperty> getDeviceInfo() {
410         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
411         metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, deviceName));
412         if (null != deviceInfo) {
413             metaProperties.add(new MetaProperty(Constants.DEVICE_ID, deviceInfo
414                     .getID()));
415             metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
416                     deviceInfo.getSpecVersion()));
417             metaProperties.add(new MetaProperty(Constants.DEVICE_DMV,
418                     deviceInfo.getDataModelVersion()));
419         }
420         return metaProperties;
421     }
422
423     public List<MetaProperty> getPlatformInfo() {
424         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
425         metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platformInfo
426                 .getPlatformID()));
427         metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME,
428                 platformInfo.getManufacturerName()));
429         metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
430                 platformInfo.getManufacturerUrl()));
431         metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
432                 platformInfo.getModelNumber()));
433         metaProperties.add(new MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC,
434                 platformInfo.getDateOfManufacture()));
435         metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
436                 platformInfo.getPlatformVersion()));
437         metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
438                 platformInfo.getOperationSystemVersion()));
439         metaProperties.add(new MetaProperty(
440                 Constants.PLATFORM_HARDWARE_VERSION, platformInfo
441                         .getHardwareVersion()));
442         metaProperties.add(new MetaProperty(
443                 Constants.PLATFORM_FIRMWARE_VERSION, platformInfo
444                         .getFirmwareVersion()));
445         metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
446                 platformInfo.getSupportUrl()));
447         metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
448                 platformInfo.getSystemTime()));
449         return metaProperties;
450     }
451
452     public void setPlatformInfo(List<MetaProperty> metaProperties) {
453         if (null == metaProperties || metaProperties.size() < 1) {
454             return;
455         }
456         Iterator<MetaProperty> itr = metaProperties.iterator();
457         MetaProperty prop;
458         String propName;
459         String propValue;
460         while (itr.hasNext()) {
461             prop = itr.next();
462             propName = prop.getPropName();
463             propValue = prop.getPropValue();
464             if (propName.equals(Constants.PLATFORM_ID)) {
465                 platformInfo.setPlatformID(propValue);
466             } else if (propName.equals(Constants.PLATFORM_MANUFAC_NAME)) {
467                 platformInfo.setManufacturerName(propValue);
468             } else if (propName.equals(Constants.PLATFORM_MANUFAC_URL)) {
469                 platformInfo.setManufacturerUrl(propValue);
470             } else if (propName.equals(Constants.PLATFORM_MODEL_NO)) {
471                 platformInfo.setModelNumber(propValue);
472             } else if (propName.equals(Constants.PLATFORM_DATE_OF_MANUFAC)) {
473                 platformInfo.setDateOfManufacture(propValue);
474             } else if (propName.equals(Constants.PLATFORM_VERSION)) {
475                 platformInfo.setPlatformVersion(propValue);
476             } else if (propName.equals(Constants.PLATFORM_OS_VERSION)) {
477                 platformInfo.setOperationSystemVersion(propValue);
478             } else if (propName.equals(Constants.PLATFORM_HARDWARE_VERSION)) {
479                 platformInfo.setHardwareVersion(propValue);
480             } else if (propName.equals(Constants.PLATFORM_FIRMWARE_VERSION)) {
481                 platformInfo.setFirmwareVersion(propValue);
482             } else if (propName.equals(Constants.PLATFORM_SUPPORT_URL)) {
483                 platformInfo.setSupportUrl(propValue);
484             } else if (propName.equals(Constants.PLATFORM_SYSTEM_TIME)) {
485                 platformInfo.setSystemTime(propValue);
486             }
487         }
488         try {
489             SimulatorManager.setPlatformInfo(platformInfo);
490         } catch (SimulatorException e) {
491             Activator
492                     .getDefault()
493                     .getLogManager()
494                     .log(Level.ERROR.ordinal(),
495                             new Date(),
496                             "Error while registering the platform info.\n"
497                                     + Utility.getSimulatorErrorString(e, null));
498         }
499     }
500
501     public boolean isPlatformInfoValid(List<MetaProperty> metaProperties) {
502         if (null == metaProperties || metaProperties.size() < 1) {
503             return false;
504         }
505         Iterator<MetaProperty> itr = metaProperties.iterator();
506         MetaProperty prop;
507         String propValue;
508         while (itr.hasNext()) {
509             prop = itr.next();
510             propValue = prop.getPropValue();
511             if (null == propValue || propValue.length() < 1) {
512                 return false;
513             }
514         }
515         return true;
516     }
517
518     public synchronized Resource getCurrentResourceInSelection() {
519         return currentResourceInSelection;
520     }
521
522     public synchronized void setCurrentResourceInSelection(Resource resource) {
523         this.currentResourceInSelection = resource;
524     }
525
526     public boolean isResourceExist(String resourceURI) {
527         return data.isResourceExist(resourceURI);
528     }
529
530     public boolean isAnyResourceExist() {
531         return data.isAnyResourceExist();
532     }
533
534     public boolean createSingleResource(SingleResource resource,
535             Map<String, SimulatorResourceAttribute> attributes)
536             throws SimulatorException {
537         if (null == resource) {
538             return false;
539         }
540
541         try {
542             // Create the resource.
543             SimulatorResource jSimulatorResource = SimulatorManager
544                     .createResource(SimulatorResource.Type.SINGLE,
545                             resource.getResourceName(),
546                             resource.getResourceURI(),
547                             resource.getResourceType());
548             if (null == jSimulatorResource
549                     || !(jSimulatorResource instanceof SimulatorSingleResource)) {
550                 return false;
551             }
552             SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) jSimulatorResource;
553             resource.setSimulatorResource(jSimulatorSingleResource);
554
555             // Cancel discoverable property if requested by user.
556             if (!resource.isDiscoverable()) {
557                 jSimulatorSingleResource.setDiscoverable(false);
558             }
559
560             // Cancel observable property if requested by user.
561             if (!resource.isObservable()) {
562                 jSimulatorSingleResource.setObservable(false);
563             }
564
565             // Set the model change listener.
566             jSimulatorSingleResource
567                     .setResourceModelChangeListener(resourceModelChangeListener);
568
569             // Set the observer listener if the resource is observable.
570             if (resource.isObservable()) {
571                 jSimulatorSingleResource.setObserverListener(observer);
572             }
573
574             // Add attributes.
575             if (null != attributes && !attributes.isEmpty()) {
576                 SimulatorResourceAttribute value;
577                 for (Map.Entry<String, SimulatorResourceAttribute> entry : attributes
578                         .entrySet()) {
579                     value = entry.getValue();
580                     if (null != value)
581                         jSimulatorSingleResource.addAttribute(value);
582                 }
583
584                 // Get the resource model java object reference.
585                 resource.setResourceModel(jSimulatorSingleResource
586                         .getResourceModel());
587
588                 resource.createResourceRepresentation(jSimulatorSingleResource
589                         .getAttributes());
590             }
591
592             // Set the resource interfaces.
593             jSimulatorSingleResource
594                     .setInterface(Utility.convertSetToVectorString(resource
595                             .getResourceInterfaces()));
596
597             // Register the resource with the platform.
598             jSimulatorSingleResource.start();
599             resource.setStarted(true);
600         } catch (SimulatorException e) {
601             Activator
602                     .getDefault()
603                     .getLogManager()
604                     .log(Level.ERROR.ordinal(), new Date(),
605                             Utility.getSimulatorErrorString(e, null));
606             throw e;
607         }
608
609         // Add to local cache.
610         data.addResource(resource);
611
612         // Update UI listeners
613         UiListenerHandler.getInstance().resourceCreatedUINotification(
614                 ResourceType.SINGLE);
615
616         Activator
617                 .getDefault()
618                 .getLogManager()
619                 .log(Level.INFO.ordinal(), new Date(),
620                         "Resource created [" + resource.getResourceURI() + "].");
621
622         return true;
623     }
624
625     public Resource createResourceByRAML(String configFilePath)
626             throws SimulatorException {
627         Resource resource = null;
628         try {
629             // Create the resource
630             SimulatorResource jSimulatorResource = SimulatorManager
631                     .createResource(configFilePath);
632             if (null == jSimulatorResource) {
633                 return null;
634             }
635             if (jSimulatorResource instanceof SimulatorSingleResource) {
636                 resource = new SingleResource();
637             } else {
638                 return null;
639             }
640             resource.setSimulatorResource(jSimulatorResource);
641
642             // Fetch and locally store the resource name and uri.
643             String uri = jSimulatorResource.getURI();
644             if (null == uri || uri.trim().isEmpty()) {
645                 return null;
646             }
647             resource.setResourceURI(uri.trim());
648
649             String name = jSimulatorResource.getName();
650             if (null == name || name.trim().isEmpty()) {
651                 return null;
652             }
653             resource.setResourceName(name.trim());
654         } catch (SimulatorException e) {
655             Activator
656                     .getDefault()
657                     .getLogManager()
658                     .log(Level.ERROR.ordinal(), new Date(),
659                             Utility.getSimulatorErrorString(e, null));
660             throw e;
661         }
662         return resource;
663     }
664
665     /**
666      * This method can set/change the resource uri and name of an already
667      * created resource which is not yet registered with the platform. This
668      * method registers the model change and observer listeners, registers the
669      * resource, fetches the resource attributes, updates the local cache and
670      * notifies the UI listeners.
671      */
672     public boolean completeSingleResourceCreationByRAML(Resource resource,
673             String uri, String name, boolean multiInstance)
674             throws SimulatorException {
675         if (null == resource || !(resource instanceof SingleResource)) {
676             return false;
677         }
678         try {
679             SingleResource singleRes = (SingleResource) resource;
680
681             SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) resource
682                     .getSimulatorResource();
683             if (null == jSimulatorSingleResource) {
684                 return false;
685             }
686
687             // Update resource URI and Name if they are changed.
688             String newUri = uri.trim();
689             String newName = name.trim();
690
691             if (multiInstance) {
692                 singleRes.setResourceURI(newUri);
693                 singleRes.setResourceName(newName);
694             } else {
695                 if (!singleRes.getResourceURI().equals(newUri)) {
696                     jSimulatorSingleResource.setURI(newUri);
697                     singleRes.setResourceURI(newUri);
698                 }
699                 if (!singleRes.getResourceName().equals(newName)) {
700                     jSimulatorSingleResource.setName(newName);
701                     singleRes.setResourceName(newName);
702                 }
703             }
704
705             // Set the model change listener.
706             jSimulatorSingleResource
707                     .setResourceModelChangeListener(resourceModelChangeListener);
708
709             // Set the observer listener if the resource is observable.
710             if (jSimulatorSingleResource.isObservable()) {
711                 jSimulatorSingleResource.setObserverListener(observer);
712                 singleRes.setObservable(true);
713             }
714
715             // Fetch the resource model.
716             SimulatorResourceModel jResModel = jSimulatorSingleResource
717                     .getResourceModel();
718             if (null == jResModel) {
719                 return false;
720             }
721             singleRes.setResourceModel(jResModel);
722
723             // Fetch the basic details of the resource.
724             singleRes.setResourceType(jSimulatorSingleResource
725                     .getResourceType());
726             singleRes
727                     .setResourceInterfaces(Utility
728                             .convertVectorToSet(jSimulatorSingleResource
729                                     .getInterface()));
730
731             // Fetch the resource attributes.
732             singleRes.createResourceRepresentation(jSimulatorSingleResource
733                     .getAttributes());
734
735             // Register the resource with the platform.
736             jSimulatorSingleResource.start();
737             singleRes.setStarted(true);
738
739             // Add to local cache.
740             data.addResource(singleRes);
741
742             // Update UI listeners for single instance creation
743             if (!multiInstance)
744                 UiListenerHandler.getInstance().resourceCreatedUINotification(
745                         ResourceType.SINGLE);
746         } catch (Exception e) {
747             Activator
748                     .getDefault()
749                     .getLogManager()
750                     .log(Level.ERROR.ordinal(), new Date(),
751                             Utility.getSimulatorErrorString(e, null));
752             throw e;
753         }
754
755         Activator
756                 .getDefault()
757                 .getLogManager()
758                 .log(Level.INFO.ordinal(), new Date(),
759                         "Resource created [" + resource.getResourceURI() + "].");
760         return true;
761     }
762
763     public Set<SingleResource> createSingleResourceMultiInstances(
764             String configFile, int count, IProgressMonitor progressMonitor)
765             throws SimulatorException {
766         Set<SingleResource> resultSet;
767         try {
768             resultSet = new HashSet<SingleResource>();
769             Vector<SimulatorResource> jSimulatorResources = SimulatorManager
770                     .createResource(configFile, count);
771             if (null == jSimulatorResources || jSimulatorResources.size() < 1) {
772                 return null;
773             }
774             SimulatorSingleResource jResource;
775             SingleResource resource;
776             boolean result;
777             for (SimulatorResource jSimulatorResource : jSimulatorResources) {
778                 // If the resource creation progress is canceled, then stop the
779                 // creation and stop/delete
780                 // the resources created already.
781                 if (progressMonitor.isCanceled()) {
782                     removeSingleResources(resultSet);
783                     return null;
784                 }
785                 jResource = (SimulatorSingleResource) jSimulatorResource;
786                 resource = new SingleResource();
787                 resource.setSimulatorResource(jResource);
788                 try {
789                     result = completeSingleResourceCreationByRAML(resource,
790                             jResource.getURI(), jResource.getName(), true);
791                     if (result) {
792                         resultSet.add(resource);
793                     }
794                 } catch (SimulatorException eInner) {
795                     Activator
796                             .getDefault()
797                             .getLogManager()
798                             .log(Level.ERROR.ordinal(),
799                                     new Date(),
800                                     Utility.getSimulatorErrorString(eInner,
801                                             null));
802                 }
803                 progressMonitor.worked(1);
804             }
805         } catch (SimulatorException eOuter) {
806             Activator
807                     .getDefault()
808                     .getLogManager()
809                     .log(Level.ERROR.ordinal(), new Date(),
810                             Utility.getSimulatorErrorString(eOuter, null));
811             throw eOuter;
812         }
813         return resultSet;
814     }
815
816     public List<Resource> getResourceList() {
817         List<Resource> resourceList = data.getResources();
818         if (null == resourceList) {
819             return null;
820         }
821         // Sort the list
822         Collections.sort(resourceList, Utility.resourceComparator);
823
824         return resourceList;
825     }
826
827     public List<SingleResource> getSingleResourceList() {
828         List<SingleResource> resourceList = data.getSingleResources();
829         if (null == resourceList) {
830             return null;
831         }
832         // Sort the list
833         Collections.sort(resourceList, Utility.singleResourceComparator);
834
835         return resourceList;
836     }
837
838     public void removeSingleResources(Set<SingleResource> resources)
839             throws SimulatorException {
840         if (null == resources) {
841             return;
842         }
843         Iterator<SingleResource> itr = resources.iterator();
844         while (itr.hasNext()) {
845             removeResource(itr.next());
846         }
847     }
848
849     public void removeResource(Resource res) throws SimulatorException {
850         // Unregister the resource from the platform.
851         SimulatorResource simRes = res.getSimulatorResource();
852         try {
853             simRes.stop();
854         } catch (SimulatorException e) {
855             Activator
856                     .getDefault()
857                     .getLogManager()
858                     .log(Level.ERROR.ordinal(), new Date(),
859                             Utility.getSimulatorErrorString(e, null));
860             throw e;
861         }
862
863         // Delete this resource
864         data.deleteResource(res);
865
866         Activator
867                 .getDefault()
868                 .getLogManager()
869                 .log(Level.INFO.ordinal(), new Date(),
870                         "Resource deleted [" + res.getResourceURI() + "].");
871     }
872
873     public boolean isUriUnique(List<MetaProperty> properties) {
874         if (null == properties) {
875             return false;
876         }
877         MetaProperty prop;
878         Iterator<MetaProperty> itr = properties.iterator();
879         while (itr.hasNext()) {
880             prop = itr.next();
881             if (prop.getPropName().equals(Constants.RESOURCE_URI)) {
882                 String uri = prop.getPropValue();
883                 return !data.isResourceExist(uri);
884             }
885         }
886         return false;
887     }
888
889     public void resourceSelectionChanged(final Resource selectedResource) {
890         new Thread() {
891             @Override
892             public void run() {
893                 if (null != selectedResource) {
894                     setCurrentResourceInSelection(selectedResource);
895                 } else {
896                     setCurrentResourceInSelection(null);
897                 }
898                 // Notify all observers for resource selection change event
899                 UiListenerHandler.getInstance()
900                         .resourceSelectionChangedUINotification(
901                                 selectedResource);
902             }
903         }.start();
904     }
905
906     public List<MetaProperty> getMetaProperties(Resource resource) {
907         if (null != resource) {
908             String propName;
909             String propValue;
910
911             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
912
913             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
914                 propName = Constants.META_PROPERTIES[index];
915                 if (propName.equals(Constants.RESOURCE_NAME)) {
916                     propValue = resource.getResourceName();
917                 } else if (propName.equals(Constants.RESOURCE_URI)) {
918                     propValue = resource.getResourceURI();
919                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
920                     propValue = resource.getResourceType();
921                 } else if (propName.equals(Constants.INTERFACE_TYPES)) {
922                     Set<String> ifTypes = resource.getResourceInterfaces();
923                     if (null != ifTypes && !ifTypes.isEmpty()) {
924                         propValue = "";
925                         Iterator<String> itr = ifTypes.iterator();
926                         while (itr.hasNext()) {
927                             propValue += itr.next();
928                             if (itr.hasNext()) {
929                                 propValue += ", ";
930                             }
931                         }
932                     } else {
933                         propValue = null;
934                     }
935                 } else {
936                     propValue = null;
937                 }
938                 if (null != propValue) {
939                     metaPropertyList.add(new MetaProperty(propName, propValue));
940                 }
941             }
942             return metaPropertyList;
943         }
944         return null;
945     }
946
947     public boolean startResource(Resource resource) throws SimulatorException {
948         if (null == resource) {
949             return false;
950         }
951         SimulatorResource server = resource.getSimulatorResource();
952         if (null == server) {
953             return false;
954         }
955         try {
956             server.start();
957             resource.setStarted(true);
958         } catch (SimulatorException e) {
959             Activator
960                     .getDefault()
961                     .getLogManager()
962                     .log(Level.ERROR.ordinal(),
963                             new Date(),
964                             "There is an error while starting the resource.\n"
965                                     + Utility.getSimulatorErrorString(e, null));
966             throw e;
967         }
968         return true;
969     }
970
971     public boolean stopResource(Resource resource) throws SimulatorException {
972         if (null == resource) {
973             return false;
974         }
975         SimulatorResource server = resource.getSimulatorResource();
976         if (null == server) {
977             return false;
978         }
979         try {
980             server.stop();
981             resource.setStarted(false);
982         } catch (SimulatorException e) {
983             Activator
984                     .getDefault()
985                     .getLogManager()
986                     .log(Level.ERROR.ordinal(),
987                             new Date(),
988                             "There is an error while stopping the resource.\n"
989                                     + Utility.getSimulatorErrorString(e, null));
990             throw e;
991         }
992         return true;
993     }
994
995     public boolean changeResourceName(Resource resource, String newName)
996             throws SimulatorException {
997         if (null == resource || null == newName) {
998             return false;
999         }
1000
1001         if (!stopResource(resource)) {
1002             return false;
1003         }
1004
1005         SimulatorResource server = resource.getSimulatorResource();
1006         try {
1007             server.setName(newName);
1008             resource.setResourceName(newName);
1009         } catch (SimulatorException e) {
1010             Activator
1011                     .getDefault()
1012                     .getLogManager()
1013                     .log(Level.ERROR.ordinal(),
1014                             new Date(),
1015                             "There is an error while changing the resource name.\n"
1016                                     + Utility.getSimulatorErrorString(e, null));
1017             throw e;
1018         }
1019
1020         if (!startResource(resource)) {
1021             return false;
1022         }
1023
1024         return true;
1025     }
1026
1027     public boolean changeResourceURI(Resource resource, String newURI)
1028             throws SimulatorException {
1029         if (null == resource || null == newURI) {
1030             return false;
1031         }
1032
1033         if (!stopResource(resource)) {
1034             return false;
1035         }
1036
1037         String curURI = resource.getResourceURI();
1038         setResourceURI(resource, newURI);
1039
1040         try {
1041             if (!startResource(resource)) {
1042                 return false;
1043             }
1044         } catch (SimulatorException e) {
1045             setResourceURI(resource, curURI);
1046         }
1047
1048         return true;
1049     }
1050
1051     public boolean changeResourceType(Resource resource, String newResourceType)
1052             throws SimulatorException {
1053         if (null == resource || null == newResourceType) {
1054             return false;
1055         }
1056
1057         if (!stopResource(resource)) {
1058             return false;
1059         }
1060
1061         String curResourceType = resource.getResourceType();
1062         setResourceType(resource, newResourceType);
1063
1064         try {
1065             if (!startResource(resource)) {
1066                 return false;
1067             }
1068         } catch (SimulatorException e) {
1069             setResourceType(resource, curResourceType);
1070         }
1071
1072         return true;
1073     }
1074
1075     public void setResourceURI(Resource resource, String newURI)
1076             throws SimulatorException {
1077         String curURI = resource.getResourceURI();
1078         SimulatorResource server = resource.getSimulatorResource();
1079         try {
1080             server.setURI(newURI);
1081             data.changeResourceURI(resource, curURI, newURI);
1082         } catch (SimulatorException e) {
1083             Activator
1084                     .getDefault()
1085                     .getLogManager()
1086                     .log(Level.ERROR.ordinal(),
1087                             new Date(),
1088                             "There is an error while changing the resource URI.\n"
1089                                     + Utility.getSimulatorErrorString(e, null));
1090             throw e;
1091         }
1092     }
1093
1094     public void setResourceType(Resource resource, String newResourceType)
1095             throws SimulatorException {
1096         SimulatorResource server = resource.getSimulatorResource();
1097         try {
1098             server.setResourceType(newResourceType);
1099             resource.setResourceType(newResourceType);
1100         } catch (SimulatorException e) {
1101             Activator
1102                     .getDefault()
1103                     .getLogManager()
1104                     .log(Level.ERROR.ordinal(),
1105                             new Date(),
1106                             "There is an error while changing the resource Type.\n"
1107                                     + Utility.getSimulatorErrorString(e, null));
1108             throw e;
1109         }
1110     }
1111
1112     public boolean updateResourceProperties(Resource resource,
1113             List<MetaProperty> properties, boolean uriChanged,
1114             boolean nameChanged, boolean resTypeChanged)
1115             throws SimulatorException {
1116         if (null == resource || null == properties) {
1117             return false;
1118         }
1119
1120         // Updating the properties
1121         Iterator<MetaProperty> itr = properties.iterator();
1122         MetaProperty property;
1123         String propName;
1124         String propValue;
1125         String resName = null;
1126         String resURI = null;
1127         String resType = null;
1128         while (itr.hasNext()) {
1129             property = itr.next();
1130             if (null == property) {
1131                 continue;
1132             }
1133             propName = property.getPropName();
1134             propValue = property.getPropValue();
1135             if (propName.equals(Constants.RESOURCE_NAME)) {
1136                 resName = propValue;
1137             } else if (propName.equals(Constants.RESOURCE_URI)) {
1138                 resURI = propValue;
1139             } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1140                 resType = propValue;
1141             }
1142         }
1143
1144         if (nameChanged) {
1145             if (!changeResourceName(resource, resName)) {
1146                 return false;
1147             }
1148
1149             // Notify UI Listeners
1150             UiListenerHandler.getInstance().propertiesChangedUINotification(
1151                     Resource.class);
1152         }
1153
1154         if (uriChanged) {
1155             if (!changeResourceURI(resource, resURI)) {
1156                 return false;
1157             }
1158         }
1159
1160         if (resTypeChanged) {
1161             if (!changeResourceType(resource, resType)) {
1162                 return false;
1163             }
1164         }
1165
1166         return true;
1167     }
1168
1169     public boolean updateResourceInterfaces(Resource resource,
1170             Set<String> newIfSet) throws SimulatorException {
1171         if (null == resource || null == newIfSet || newIfSet.isEmpty()) {
1172             return false;
1173         }
1174         SimulatorResource jResource = resource.getSimulatorResource();
1175         if (null == jResource) {
1176             return false;
1177         }
1178         Set<String> curIfSet = resource.getResourceInterfaces();
1179         Iterator<String> itr = curIfSet.iterator();
1180         String interfaceType;
1181         boolean resourceRestartRequired = false;
1182         while (itr.hasNext()) {
1183             interfaceType = itr.next();
1184             if (!newIfSet.contains(interfaceType)) {
1185                 resourceRestartRequired = true;
1186                 break;
1187             }
1188         }
1189
1190         try {
1191             // As there is no support from native layer for interface removal,
1192             // supporting it from the simulator requires restarting the resource
1193             // if any existing interfaces are removed.
1194
1195             if (resourceRestartRequired) {
1196                 stopResource(resource);
1197                 jResource.setInterface(Utility
1198                         .convertSetToVectorString(newIfSet));
1199                 startResource(resource);
1200             } else {
1201                 // Existing interfaces are not removed.
1202                 itr = newIfSet.iterator();
1203                 while (itr.hasNext()) {
1204                     interfaceType = itr.next();
1205                     if (!curIfSet.contains(interfaceType)) {
1206                         jResource.addInterface(interfaceType);
1207                     }
1208                 }
1209             }
1210         } catch (SimulatorException e) {
1211             Activator
1212                     .getDefault()
1213                     .getLogManager()
1214                     .log(Level.ERROR.ordinal(),
1215                             new Date(),
1216                             "There is an error while changing the interface types."
1217                                     + Utility.getSimulatorErrorString(e, null));
1218             throw e;
1219         }
1220
1221         // Set the resource interfaces.
1222         resource.setResourceInterfaces(newIfSet);
1223
1224         return true;
1225     }
1226
1227     public boolean attributeValueUpdated(SingleResource resource,
1228             String attributeName, AttributeValue value) {
1229         if (null != resource && null != attributeName && null != value) {
1230             SimulatorSingleResource simRes = (SimulatorSingleResource) resource
1231                     .getSimulatorResource();
1232             if (null != simRes) {
1233                 try {
1234                     simRes.updateAttribute(attributeName, value);
1235                     return true;
1236                 } catch (SimulatorException e) {
1237                     Activator
1238                             .getDefault()
1239                             .getLogManager()
1240                             .log(Level.ERROR.ordinal(), new Date(),
1241                                     Utility.getSimulatorErrorString(e, null));
1242                 }
1243             }
1244         }
1245         return false;
1246     }
1247
1248     public boolean isResourceStarted(Resource resource) {
1249         if (null == resource) {
1250             return false;
1251         }
1252         return resource.isStarted();
1253     }
1254
1255     public boolean isPropertyValueInvalid(Resource resource,
1256             List<MetaProperty> properties, String propName) {
1257         if (null == resource || null == properties || null == propName) {
1258             return false;
1259         }
1260         boolean invalid = false;
1261         MetaProperty prop;
1262         Iterator<MetaProperty> itr = properties.iterator();
1263         while (itr.hasNext()) {
1264             prop = itr.next();
1265             if (prop.getPropName().equals(propName)) {
1266                 String value = prop.getPropValue();
1267                 if (propName.equals(Constants.RESOURCE_URI)) {
1268                     if (!Utility.isUriValid(value)) {
1269                         invalid = true;
1270                     }
1271                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1272                     if (!Utility.isResourceTypeValid(value)) {
1273                         invalid = true;
1274                     }
1275                 } else {
1276                     if (null == value || value.trim().isEmpty()) {
1277                         invalid = true;
1278                     }
1279                 }
1280             }
1281         }
1282         return invalid;
1283     }
1284
1285     public boolean isPropValueChanged(Resource resource,
1286             List<MetaProperty> properties, String propName) {
1287         if (null == resource || null == properties || null == propName) {
1288             return false;
1289         }
1290         boolean changed = false;
1291         MetaProperty prop;
1292         String oldValue;
1293         Iterator<MetaProperty> itr = properties.iterator();
1294         while (itr.hasNext()) {
1295             prop = itr.next();
1296             if (prop.getPropName().equals(propName)) {
1297                 oldValue = getPropertyValueFromResource(resource, propName);
1298                 if (null != oldValue && !prop.getPropValue().equals(oldValue)) {
1299                     changed = true;
1300                 }
1301                 break;
1302             }
1303         }
1304         return changed;
1305     }
1306
1307     private String getPropertyValueFromResource(Resource resource,
1308             String propName) {
1309         if (null == resource || null == propName) {
1310             return null;
1311         }
1312         if (propName.equals(Constants.RESOURCE_URI)) {
1313             return resource.getResourceURI();
1314         } else if (propName.equals(Constants.RESOURCE_NAME)) {
1315             return resource.getResourceName();
1316         } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1317             return resource.getResourceType();
1318         } else {
1319             return null;
1320         }
1321     }
1322
1323     public boolean isAttHasRangeOrAllowedValues(SimulatorResourceAttribute att) {
1324         if (null == att) {
1325             return false;
1326         }
1327         AttributeProperty prop = att.property();
1328         if (null == prop) {
1329             return false;
1330         }
1331
1332         if (prop.getType() == Type.INTEGER) {
1333             IntegerProperty intProperty = prop.asInteger();
1334             if (null != intProperty) {
1335                 return (intProperty.hasRange() || intProperty.hasValues());
1336             } else {
1337                 return false;
1338             }
1339         } else if (prop.getType() == Type.DOUBLE) {
1340             DoubleProperty dblProperty = prop.asDouble();
1341             if (null != dblProperty) {
1342                 return (dblProperty.hasRange() || dblProperty.hasValues());
1343             } else {
1344                 return false;
1345             }
1346         } else if (prop.getType() == Type.STRING) {
1347             StringProperty stringProperty = prop.asString();
1348             if (null != stringProperty) {
1349                 return stringProperty.hasValues();
1350             } else {
1351                 return false;
1352             }
1353         }
1354
1355         return true;
1356     }
1357
1358     public int startAutomation(SingleResource resource,
1359             AttributeElement attribute, AutoUpdateType autoType,
1360             int autoUpdateInterval) {
1361         int autoId = -1;
1362         if (null != resource && null != attribute) {
1363             SimulatorSingleResource server = (SimulatorSingleResource) resource
1364                     .getSimulatorResource();
1365             if (null != server) {
1366                 String attrName = attribute.getSimulatorResourceAttribute()
1367                         .name();
1368                 try {
1369                     autoId = server.startAttributeUpdation(attrName, autoType,
1370                             autoUpdateInterval, automationListener);
1371                 } catch (SimulatorException e) {
1372                     Activator
1373                             .getDefault()
1374                             .getLogManager()
1375                             .log(Level.ERROR.ordinal(),
1376                                     new Date(),
1377                                     "[" + e.getClass().getSimpleName() + "]"
1378                                             + e.code().toString() + "-"
1379                                             + e.message());
1380                     return -1;
1381                 }
1382                 if (-1 != autoId) {
1383                     attribute.setAutoUpdateId(autoId);
1384                     attribute.setAutoUpdateType(autoType);
1385                     attribute.setAutoUpdateInterval(autoUpdateInterval);
1386                     attribute.setAutoUpdateState(true);
1387                     resource.setAttributeAutomationInProgress(true);
1388                 }
1389             }
1390         }
1391         return autoId;
1392     }
1393
1394     public void stopAutomation(SingleResource resource, AttributeElement att,
1395             int autoId) {
1396         if (null != resource) {
1397             SimulatorSingleResource server = (SimulatorSingleResource) resource
1398                     .getSimulatorResource();
1399             if (null != server) {
1400                 try {
1401                     server.stopUpdation(autoId);
1402                 } catch (SimulatorException e) {
1403                     Activator
1404                             .getDefault()
1405                             .getLogManager()
1406                             .log(Level.ERROR.ordinal(),
1407                                     new Date(),
1408                                     "[" + e.getClass().getSimpleName() + "]"
1409                                             + e.code().toString() + "-"
1410                                             + e.message());
1411                     return;
1412                 }
1413                 // Change the automation status
1414                 att.setAutoUpdateState(false);
1415                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
1416             }
1417         }
1418     }
1419
1420     public boolean startResourceAutomationUIRequest(AutoUpdateType autoType,
1421             int autoUpdateInterval, final SingleResource resource) {
1422         if (null == resource) {
1423             return false;
1424         }
1425         boolean status = false;
1426         // Invoke the native automation method
1427         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
1428                 .getSimulatorResource();
1429         if (null != resourceServer) {
1430             int autoId = -1;
1431             try {
1432                 autoId = resourceServer.startResourceUpdation(autoType,
1433                         autoUpdateInterval, automationListener);
1434             } catch (SimulatorException e) {
1435                 Activator
1436                         .getDefault()
1437                         .getLogManager()
1438                         .log(Level.ERROR.ordinal(), new Date(),
1439                                 Utility.getSimulatorErrorString(e, null));
1440                 autoId = -1;
1441             }
1442             if (-1 != autoId) {
1443                 // Automation request accepted.
1444                 changeResourceLevelAutomationStatus(resource, true);
1445
1446                 resource.setAutomationId(autoId);
1447
1448                 // Notify the UI listeners in a different thread.
1449                 Thread notifyThread = new Thread() {
1450                     public void run() {
1451                         UiListenerHandler.getInstance()
1452                                 .resourceAutomationStartedUINotification(
1453                                         resource);
1454                     };
1455                 };
1456                 notifyThread.setPriority(Thread.MAX_PRIORITY);
1457                 notifyThread.start();
1458
1459                 status = true;
1460             }
1461         }
1462         return status;
1463     }
1464
1465     public boolean stopResourceAutomationUIRequest(final SingleResource resource) {
1466         if (null == resource) {
1467             return false;
1468         }
1469         final int autoId = resource.getAutomationId();
1470         if (-1 == autoId) {
1471             return false;
1472         }
1473         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
1474                 .getSimulatorResource();
1475         if (null == resourceServer) {
1476             return false;
1477         }
1478         // Call native method
1479         try {
1480             resourceServer.stopUpdation(autoId);
1481         } catch (SimulatorException e) {
1482             Activator
1483                     .getDefault()
1484                     .getLogManager()
1485                     .log(Level.ERROR.ordinal(), new Date(),
1486                             Utility.getSimulatorErrorString(e, null));
1487             return false;
1488         }
1489
1490         // Notify the UI Listeners. Invoke the automation complete callback.
1491         Thread stopThread = new Thread() {
1492             public void run() {
1493                 automationListener.onUpdateComplete(resource.getResourceURI(),
1494                         autoId);
1495             }
1496         };
1497         stopThread.start();
1498         return true;
1499     }
1500
1501     private boolean isAnyAttributeInAutomation(SingleResource resource) {
1502         if (null == resource || null == resource.getResourceRepresentation()) {
1503             return false;
1504         }
1505
1506         Map<String, AttributeElement> attributes = resource
1507                 .getResourceRepresentation().getAttributes();
1508         if (null == attributes || 0 == attributes.size())
1509             return false;
1510
1511         for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
1512             if (entry.getValue().isAutoUpdateInProgress())
1513                 return true;
1514         }
1515
1516         return false;
1517     }
1518
1519     // Changes the automation state of the resource and its attributes
1520     private void changeResourceLevelAutomationStatus(SingleResource resource,
1521             boolean status) {
1522
1523         if (null == resource || null == resource.getResourceRepresentation()) {
1524             return;
1525         }
1526
1527         Map<String, AttributeElement> attributes = resource
1528                 .getResourceRepresentation().getAttributes();
1529         if (null == attributes || 0 == attributes.size())
1530             return;
1531
1532         for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
1533             entry.getValue().setAutoUpdateState(status);
1534         }
1535
1536         resource.setResourceAutomationInProgress(status);
1537     }
1538
1539     private AttributeElement getAttributeWithGivenAutomationId(
1540             SingleResource resource, int automationId) {
1541         if (null == resource || null == resource.getResourceRepresentation()) {
1542             return null;
1543         }
1544
1545         Map<String, AttributeElement> attributes = resource
1546                 .getResourceRepresentation().getAttributes();
1547         if (null == attributes || 0 == attributes.size())
1548             return null;
1549
1550         for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
1551             if (automationId == entry.getValue().getAutoUpdateId())
1552                 return entry.getValue();
1553         }
1554
1555         return null;
1556     }
1557
1558     public boolean isResourceAutomationStarted(SingleResource resource) {
1559         boolean status = false;
1560         if (null != resource) {
1561             status = resource.isResourceAutomationInProgress();
1562         }
1563         return status;
1564     }
1565
1566     public boolean isAttributeAutomationStarted(SingleResource resource) {
1567         if (null == resource) {
1568             return false;
1569         }
1570         return resource.isAttributeAutomationInProgress();
1571     }
1572
1573     public void notifyObserverRequest(Resource resource, int observerId) {
1574         if (null == resource) {
1575             return;
1576         }
1577         SimulatorResource simulatorResource = resource.getSimulatorResource();
1578         if (null == simulatorResource) {
1579             return;
1580         }
1581         try {
1582             simulatorResource.notifyObserver(observerId);
1583         } catch (SimulatorException e) {
1584             Activator
1585                     .getDefault()
1586                     .getLogManager()
1587                     .log(Level.ERROR.ordinal(), new Date(),
1588                             Utility.getSimulatorErrorString(e, null));
1589         }
1590     }
1591
1592     public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
1593         if (null == att) {
1594             return null;
1595         }
1596
1597         AttributeValue value = att.value();
1598         if (null == value || null == value.get()) {
1599             return null;
1600         }
1601
1602         TypeInfo type = value.typeInfo();
1603
1604         if (type.mBaseType == ValueType.RESOURCEMODEL) {
1605             return null;
1606         }
1607
1608         List<String> values = new ArrayList<String>();
1609
1610         AttributeProperty prop = att.property();
1611         if (null == prop) {
1612             // Adding the current value of the attribute.
1613             values.add(new AttributeValueStringConverter(value).toString());
1614             return values;
1615         }
1616
1617         if (type.mType == ValueType.ARRAY) {
1618             if (type.mDepth == 1) {
1619                 ArrayProperty arrayProperty = prop.asArray();
1620                 if (null != arrayProperty) {
1621                     AttributeProperty childProp = arrayProperty
1622                             .getElementProperty();
1623                     switch (childProp.getType()) {
1624                         case INTEGER:
1625                             IntegerProperty intProperty = childProp.asInteger();
1626                             if (null != intProperty) {
1627                                 values.addAll(getAllValues(att, intProperty,
1628                                         Type.INTEGER));
1629                             }
1630                             break;
1631                         case DOUBLE:
1632                             DoubleProperty dblProperty = childProp.asDouble();
1633                             if (null != dblProperty) {
1634                                 values.addAll(getAllValues(att, dblProperty,
1635                                         Type.DOUBLE));
1636                             }
1637                             break;
1638                         case BOOLEAN:
1639                             BooleanProperty boolProperty = childProp
1640                                     .asBoolean();
1641                             if (null != boolProperty) {
1642                                 values.addAll(getAllValues(att, boolProperty,
1643                                         Type.BOOLEAN));
1644                             }
1645                             break;
1646                         case STRING:
1647                             StringProperty stringProperty = childProp
1648                                     .asString();
1649                             if (null != stringProperty) {
1650                                 values.addAll(getAllValues(att, stringProperty,
1651                                         Type.STRING));
1652                             }
1653                             break;
1654                         default:
1655                             break;
1656                     }
1657                 }
1658             }
1659         } else {
1660             switch (prop.getType()) {
1661                 case INTEGER:
1662                     IntegerProperty intProperty = prop.asInteger();
1663                     if (null != intProperty) {
1664                         values.addAll(getAllValues(att, intProperty,
1665                                 Type.INTEGER));
1666                     }
1667                     break;
1668                 case DOUBLE:
1669                     DoubleProperty dblProperty = prop.asDouble();
1670                     if (null != dblProperty) {
1671                         values.addAll(getAllValues(att, dblProperty,
1672                                 Type.DOUBLE));
1673                     }
1674                     break;
1675                 case BOOLEAN:
1676                     BooleanProperty boolProperty = prop.asBoolean();
1677                     if (null != boolProperty) {
1678                         values.addAll(getAllValues(att, boolProperty,
1679                                 Type.BOOLEAN));
1680                     }
1681                     break;
1682                 case STRING:
1683                     StringProperty stringProperty = prop.asString();
1684                     if (null != stringProperty) {
1685                         values.addAll(getAllValues(att, stringProperty,
1686                                 Type.STRING));
1687                     }
1688                     break;
1689                 default:
1690                     break;
1691             }
1692         }
1693
1694         return values;
1695     }
1696
1697     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1698             IntegerProperty intProperty, AttributeProperty.Type type) {
1699         List<String> values = new ArrayList<String>();
1700
1701         if (intProperty.hasRange()) {
1702             int min = (int) intProperty.min();
1703             int max = (int) intProperty.max();
1704             for (int iVal = min; iVal <= max; iVal++) {
1705                 values.add(String.valueOf(iVal));
1706             }
1707         } else if (intProperty.hasValues()) {
1708             for (Integer val : intProperty.getValues()) {
1709                 values.add(String.valueOf(val));
1710             }
1711         } else {
1712             AttributeValue value = attribute.value();
1713             if (null != value && null != value.get()) {
1714                 // Adding the current value of the attribute.
1715                 values.add(String.valueOf(value.get()));
1716             }
1717         }
1718         return values;
1719     }
1720
1721     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1722             DoubleProperty dblProperty, AttributeProperty.Type type) {
1723         NumberFormat formatter = NumberFormat.getInstance();
1724         List<String> values = new ArrayList<String>();
1725
1726         if (dblProperty.hasRange()) {
1727             double min = (double) dblProperty.min();
1728             double max = (double) dblProperty.max();
1729             for (double val = min; val <= max; val += 0.1) {
1730                 formatter.setMaximumFractionDigits(1);
1731                 formatter.setMinimumFractionDigits(1);
1732                 values.add(formatter.format(val));
1733             }
1734         } else if (dblProperty.hasValues()) {
1735             for (Double val : dblProperty.getValues()) {
1736                 values.add(String.valueOf(val));
1737             }
1738         } else {
1739             AttributeValue value = attribute.value();
1740             if (null != value && null != value.get()) {
1741                 // Adding the current value of the attribute.
1742                 values.add(String.valueOf(value.get()));
1743             }
1744         }
1745         return values;
1746     }
1747
1748     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1749             BooleanProperty boolProperty, AttributeProperty.Type type) {
1750         List<String> values = new ArrayList<String>();
1751         values.add("true");
1752         values.add("false");
1753         return values;
1754     }
1755
1756     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1757             StringProperty stringProperty, AttributeProperty.Type type) {
1758         List<String> values = new ArrayList<String>();
1759
1760         if (stringProperty.hasValues()) {
1761             for (String val : stringProperty.getValues()) {
1762                 values.add(String.valueOf(val));
1763             }
1764         } else {
1765             AttributeValue value = attribute.value();
1766             if (null != value && null != value.get()) {
1767                 // Adding the current value of the attribute.
1768                 values.add(String.valueOf(value.get()));
1769             }
1770         }
1771         return values;
1772     }
1773
1774     public int getResourceCount() {
1775         return data.getResourceCount();
1776     }
1777
1778     public void shutdown() {
1779         threadHandle.interrupt();
1780     }
1781 }