Imported Upstream version 1.1.0
[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         SimulatorResource jSimulatorResource;
628         try {
629             // Create the resource
630             jSimulatorResource = SimulatorManager
631                     .createResource(configFilePath);
632             if (null == jSimulatorResource) {
633                 return null;
634             }
635         } catch (SimulatorException e) {
636             Activator
637                     .getDefault()
638                     .getLogManager()
639                     .log(Level.ERROR.ordinal(), new Date(),
640                             Utility.getSimulatorErrorString(e, null));
641             throw e;
642         }
643
644         if (!(jSimulatorResource instanceof SimulatorSingleResource)) {
645             return null;
646         }
647
648         Resource resource = new SingleResource();
649         resource.setSimulatorResource(jSimulatorResource);
650
651         // Fetch and locally store the resource name and uri.
652         String uri = jSimulatorResource.getURI();
653         if (null == uri || uri.trim().isEmpty()) {
654             return null;
655         }
656         resource.setResourceURI(uri.trim());
657
658         String name = jSimulatorResource.getName();
659         if (null == name || name.trim().isEmpty()) {
660             return null;
661         }
662
663         resource.setResourceName(name.trim());
664
665         return resource;
666     }
667
668     /**
669      * This method can set/change the resource uri and name of an already
670      * created resource which is not yet registered with the platform. This
671      * method registers the model change and observer listeners, registers the
672      * resource, fetches the resource attributes, updates the local cache and
673      * notifies the UI listeners.
674      */
675     public boolean completeSingleResourceCreationByRAML(Resource resource,
676             String uri, String name, boolean multiInstance)
677             throws SimulatorException {
678         if (null == resource || !(resource instanceof SingleResource)) {
679             return false;
680         }
681         try {
682             SingleResource singleRes = (SingleResource) resource;
683
684             SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) resource
685                     .getSimulatorResource();
686             if (null == jSimulatorSingleResource) {
687                 return false;
688             }
689
690             // Update resource URI and Name if they are changed.
691             String newUri = uri.trim();
692             String newName = name.trim();
693
694             if (multiInstance) {
695                 singleRes.setResourceURI(newUri);
696                 singleRes.setResourceName(newName);
697             } else {
698                 if (!singleRes.getResourceURI().equals(newUri)) {
699                     jSimulatorSingleResource.setURI(newUri);
700                     singleRes.setResourceURI(newUri);
701                 }
702                 if (!singleRes.getResourceName().equals(newName)) {
703                     jSimulatorSingleResource.setName(newName);
704                     singleRes.setResourceName(newName);
705                 }
706             }
707
708             // Set the model change listener.
709             jSimulatorSingleResource
710                     .setResourceModelChangeListener(resourceModelChangeListener);
711
712             // Set the observer listener if the resource is observable.
713             if (jSimulatorSingleResource.isObservable()) {
714                 jSimulatorSingleResource.setObserverListener(observer);
715                 singleRes.setObservable(true);
716             }
717
718             // Fetch the resource model.
719             SimulatorResourceModel jResModel = jSimulatorSingleResource
720                     .getResourceModel();
721             if (null == jResModel) {
722                 return false;
723             }
724             singleRes.setResourceModel(jResModel);
725
726             // Fetch the basic details of the resource.
727             singleRes.setResourceType(jSimulatorSingleResource
728                     .getResourceType());
729             singleRes
730                     .setResourceInterfaces(Utility
731                             .convertVectorToSet(jSimulatorSingleResource
732                                     .getInterface()));
733
734             // Fetch the resource attributes.
735             singleRes.createResourceRepresentation(jSimulatorSingleResource
736                     .getAttributes());
737
738             // Register the resource with the platform.
739             jSimulatorSingleResource.start();
740             singleRes.setStarted(true);
741
742             // Add to local cache.
743             data.addResource(singleRes);
744
745             // Update UI listeners for single instance creation
746             if (!multiInstance)
747                 UiListenerHandler.getInstance().resourceCreatedUINotification(
748                         ResourceType.SINGLE);
749         } catch (Exception e) {
750             Activator
751                     .getDefault()
752                     .getLogManager()
753                     .log(Level.ERROR.ordinal(), new Date(),
754                             Utility.getSimulatorErrorString(e, null));
755             throw e;
756         }
757
758         Activator
759                 .getDefault()
760                 .getLogManager()
761                 .log(Level.INFO.ordinal(), new Date(),
762                         "Resource created [" + resource.getResourceURI() + "].");
763         return true;
764     }
765
766     public Set<SingleResource> createSingleResourceMultiInstances(
767             String configFile, int count, IProgressMonitor progressMonitor)
768             throws SimulatorException {
769         Set<SingleResource> resultSet;
770         try {
771             resultSet = new HashSet<SingleResource>();
772             Vector<SimulatorResource> jSimulatorResources = SimulatorManager
773                     .createResource(configFile, count);
774             if (null == jSimulatorResources || jSimulatorResources.size() < 1) {
775                 return null;
776             }
777             SimulatorSingleResource jResource;
778             SingleResource resource;
779             boolean result;
780             for (SimulatorResource jSimulatorResource : jSimulatorResources) {
781                 // If the resource creation progress is canceled, then stop the
782                 // creation and stop/delete
783                 // the resources created already.
784                 if (progressMonitor.isCanceled()) {
785                     removeSingleResources(resultSet);
786                     return null;
787                 }
788                 jResource = (SimulatorSingleResource) jSimulatorResource;
789                 resource = new SingleResource();
790                 resource.setSimulatorResource(jResource);
791                 try {
792                     result = completeSingleResourceCreationByRAML(resource,
793                             jResource.getURI(), jResource.getName(), true);
794                     if (result) {
795                         resultSet.add(resource);
796                     }
797                 } catch (SimulatorException eInner) {
798                     Activator
799                             .getDefault()
800                             .getLogManager()
801                             .log(Level.ERROR.ordinal(),
802                                     new Date(),
803                                     Utility.getSimulatorErrorString(eInner,
804                                             null));
805                 }
806                 progressMonitor.worked(1);
807             }
808         } catch (SimulatorException eOuter) {
809             Activator
810                     .getDefault()
811                     .getLogManager()
812                     .log(Level.ERROR.ordinal(), new Date(),
813                             Utility.getSimulatorErrorString(eOuter, null));
814             throw eOuter;
815         }
816         return resultSet;
817     }
818
819     public List<Resource> getResourceList() {
820         List<Resource> resourceList = data.getResources();
821         if (null == resourceList) {
822             return null;
823         }
824         // Sort the list
825         Collections.sort(resourceList, Utility.resourceComparator);
826
827         return resourceList;
828     }
829
830     public List<SingleResource> getSingleResourceList() {
831         List<SingleResource> resourceList = data.getSingleResources();
832         if (null == resourceList) {
833             return null;
834         }
835         // Sort the list
836         Collections.sort(resourceList, Utility.singleResourceComparator);
837
838         return resourceList;
839     }
840
841     public void removeSingleResources(Set<SingleResource> resources)
842             throws SimulatorException {
843         if (null == resources) {
844             return;
845         }
846         Iterator<SingleResource> itr = resources.iterator();
847         while (itr.hasNext()) {
848             removeResource(itr.next());
849         }
850     }
851
852     public void removeResource(Resource res) throws SimulatorException {
853         // Unregister the resource from the platform.
854         SimulatorResource simRes = res.getSimulatorResource();
855         try {
856             simRes.stop();
857         } catch (SimulatorException e) {
858             Activator
859                     .getDefault()
860                     .getLogManager()
861                     .log(Level.ERROR.ordinal(), new Date(),
862                             Utility.getSimulatorErrorString(e, null));
863             throw e;
864         }
865
866         // Delete this resource
867         data.deleteResource(res);
868
869         Activator
870                 .getDefault()
871                 .getLogManager()
872                 .log(Level.INFO.ordinal(), new Date(),
873                         "Resource deleted [" + res.getResourceURI() + "].");
874     }
875
876     public boolean isUriUnique(List<MetaProperty> properties) {
877         if (null == properties) {
878             return false;
879         }
880         MetaProperty prop;
881         Iterator<MetaProperty> itr = properties.iterator();
882         while (itr.hasNext()) {
883             prop = itr.next();
884             if (prop.getPropName().equals(Constants.RESOURCE_URI)) {
885                 String uri = prop.getPropValue();
886                 return !data.isResourceExist(uri);
887             }
888         }
889         return false;
890     }
891
892     public void resourceSelectionChanged(final Resource selectedResource) {
893         new Thread() {
894             @Override
895             public void run() {
896                 if (null != selectedResource) {
897                     setCurrentResourceInSelection(selectedResource);
898                 } else {
899                     setCurrentResourceInSelection(null);
900                 }
901                 // Notify all observers for resource selection change event
902                 UiListenerHandler.getInstance()
903                         .resourceSelectionChangedUINotification(
904                                 selectedResource);
905             }
906         }.start();
907     }
908
909     public List<MetaProperty> getMetaProperties(Resource resource) {
910         if (null != resource) {
911             String propName;
912             StringBuilder propValue;
913             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
914
915             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
916                 propName = Constants.META_PROPERTIES[index];
917                 propValue = new StringBuilder();
918                 if (propName.equals(Constants.RESOURCE_NAME)) {
919                     propValue.append(resource.getResourceName());
920                 } else if (propName.equals(Constants.RESOURCE_URI)) {
921                     propValue.append(resource.getResourceURI());
922                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
923                     propValue.append(resource.getResourceType());
924                 } else if (propName.equals(Constants.INTERFACE_TYPES)) {
925                     Set<String> ifTypes = resource.getResourceInterfaces();
926                     if (null != ifTypes && !ifTypes.isEmpty()) {
927                         Iterator<String> itr = ifTypes.iterator();
928                         while (itr.hasNext()) {
929                             propValue.append(itr.next());
930                             if (itr.hasNext()) {
931                                 propValue.append(", ");
932                             }
933                         }
934                     } else {
935                         propValue = null;
936                     }
937                 } else {
938                     propValue = null;
939                 }
940                 if (null != propValue) {
941                     metaPropertyList.add(new MetaProperty(propName, propValue
942                             .toString()));
943                 }
944             }
945             return metaPropertyList;
946         }
947         return null;
948     }
949
950     public boolean startResource(Resource resource) throws SimulatorException {
951         if (null == resource) {
952             return false;
953         }
954         SimulatorResource server = resource.getSimulatorResource();
955         if (null == server) {
956             return false;
957         }
958         try {
959             server.start();
960             resource.setStarted(true);
961         } catch (SimulatorException e) {
962             Activator
963                     .getDefault()
964                     .getLogManager()
965                     .log(Level.ERROR.ordinal(),
966                             new Date(),
967                             "There is an error while starting the resource.\n"
968                                     + Utility.getSimulatorErrorString(e, null));
969             throw e;
970         }
971         return true;
972     }
973
974     public boolean stopResource(Resource resource) throws SimulatorException {
975         if (null == resource) {
976             return false;
977         }
978         SimulatorResource server = resource.getSimulatorResource();
979         if (null == server) {
980             return false;
981         }
982         try {
983             server.stop();
984             resource.setStarted(false);
985         } catch (SimulatorException e) {
986             Activator
987                     .getDefault()
988                     .getLogManager()
989                     .log(Level.ERROR.ordinal(),
990                             new Date(),
991                             "There is an error while stopping the resource.\n"
992                                     + Utility.getSimulatorErrorString(e, null));
993             throw e;
994         }
995         return true;
996     }
997
998     public boolean changeResourceName(Resource resource, String newName)
999             throws SimulatorException {
1000         if (null == resource || null == newName) {
1001             return false;
1002         }
1003
1004         if (!stopResource(resource)) {
1005             return false;
1006         }
1007
1008         SimulatorResource server = resource.getSimulatorResource();
1009         try {
1010             server.setName(newName);
1011             resource.setResourceName(newName);
1012         } catch (SimulatorException e) {
1013             Activator
1014                     .getDefault()
1015                     .getLogManager()
1016                     .log(Level.ERROR.ordinal(),
1017                             new Date(),
1018                             "There is an error while changing the resource name.\n"
1019                                     + Utility.getSimulatorErrorString(e, null));
1020             throw e;
1021         }
1022
1023         if (!startResource(resource)) {
1024             return false;
1025         }
1026
1027         return true;
1028     }
1029
1030     public boolean changeResourceURI(Resource resource, String newURI)
1031             throws SimulatorException {
1032         if (null == resource || null == newURI) {
1033             return false;
1034         }
1035
1036         if (!stopResource(resource)) {
1037             return false;
1038         }
1039
1040         String curURI = resource.getResourceURI();
1041         setResourceURI(resource, newURI);
1042
1043         try {
1044             if (!startResource(resource)) {
1045                 return false;
1046             }
1047         } catch (SimulatorException e) {
1048             setResourceURI(resource, curURI);
1049         }
1050
1051         return true;
1052     }
1053
1054     public boolean changeResourceType(Resource resource, String newResourceType)
1055             throws SimulatorException {
1056         if (null == resource || null == newResourceType) {
1057             return false;
1058         }
1059
1060         if (!stopResource(resource)) {
1061             return false;
1062         }
1063
1064         String curResourceType = resource.getResourceType();
1065         setResourceType(resource, newResourceType);
1066
1067         try {
1068             if (!startResource(resource)) {
1069                 return false;
1070             }
1071         } catch (SimulatorException e) {
1072             setResourceType(resource, curResourceType);
1073         }
1074
1075         return true;
1076     }
1077
1078     public void setResourceURI(Resource resource, String newURI)
1079             throws SimulatorException {
1080         String curURI = resource.getResourceURI();
1081         SimulatorResource server = resource.getSimulatorResource();
1082         try {
1083             server.setURI(newURI);
1084             data.changeResourceURI(resource, curURI, newURI);
1085         } catch (SimulatorException e) {
1086             Activator
1087                     .getDefault()
1088                     .getLogManager()
1089                     .log(Level.ERROR.ordinal(),
1090                             new Date(),
1091                             "There is an error while changing the resource URI.\n"
1092                                     + Utility.getSimulatorErrorString(e, null));
1093             throw e;
1094         }
1095     }
1096
1097     public void setResourceType(Resource resource, String newResourceType)
1098             throws SimulatorException {
1099         SimulatorResource server = resource.getSimulatorResource();
1100         try {
1101             server.setResourceType(newResourceType);
1102             resource.setResourceType(newResourceType);
1103         } catch (SimulatorException e) {
1104             Activator
1105                     .getDefault()
1106                     .getLogManager()
1107                     .log(Level.ERROR.ordinal(),
1108                             new Date(),
1109                             "There is an error while changing the resource Type.\n"
1110                                     + Utility.getSimulatorErrorString(e, null));
1111             throw e;
1112         }
1113     }
1114
1115     public boolean updateResourceProperties(Resource resource,
1116             List<MetaProperty> properties, boolean uriChanged,
1117             boolean nameChanged, boolean resTypeChanged)
1118             throws SimulatorException {
1119         if (null == resource || null == properties) {
1120             return false;
1121         }
1122
1123         // Updating the properties
1124         Iterator<MetaProperty> itr = properties.iterator();
1125         MetaProperty property;
1126         String propName;
1127         String propValue;
1128         String resName = null;
1129         String resURI = null;
1130         String resType = null;
1131         while (itr.hasNext()) {
1132             property = itr.next();
1133             if (null == property) {
1134                 continue;
1135             }
1136             propName = property.getPropName();
1137             propValue = property.getPropValue();
1138             if (propName.equals(Constants.RESOURCE_NAME)) {
1139                 resName = propValue;
1140             } else if (propName.equals(Constants.RESOURCE_URI)) {
1141                 resURI = propValue;
1142             } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1143                 resType = propValue;
1144             }
1145         }
1146
1147         if (nameChanged) {
1148             if (!changeResourceName(resource, resName)) {
1149                 return false;
1150             }
1151
1152             // Notify UI Listeners
1153             UiListenerHandler.getInstance().propertiesChangedUINotification(
1154                     Resource.class);
1155         }
1156
1157         if (uriChanged) {
1158             if (!changeResourceURI(resource, resURI)) {
1159                 return false;
1160             }
1161         }
1162
1163         if (resTypeChanged) {
1164             if (!changeResourceType(resource, resType)) {
1165                 return false;
1166             }
1167         }
1168
1169         return true;
1170     }
1171
1172     public boolean updateResourceInterfaces(Resource resource,
1173             Set<String> newIfSet) throws SimulatorException {
1174         if (null == resource || null == newIfSet || newIfSet.isEmpty()) {
1175             return false;
1176         }
1177
1178         SimulatorResource jResource = resource.getSimulatorResource();
1179         if (null == jResource) {
1180             return false;
1181         }
1182
1183         Set<String> curIfSet = resource.getResourceInterfaces();
1184         if (null == curIfSet || curIfSet.isEmpty()) {
1185             return false;
1186         }
1187
1188         Iterator<String> itr = curIfSet.iterator();
1189         String interfaceType;
1190         boolean resourceRestartRequired = false;
1191         while (itr.hasNext()) {
1192             interfaceType = itr.next();
1193             if (!newIfSet.contains(interfaceType)) {
1194                 resourceRestartRequired = true;
1195                 break;
1196             }
1197         }
1198
1199         try {
1200             // As there is no support from native layer for interface removal,
1201             // supporting it from the simulator requires restarting the resource
1202             // if any existing interfaces are removed.
1203
1204             if (resourceRestartRequired) {
1205                 stopResource(resource);
1206                 jResource.setInterface(Utility
1207                         .convertSetToVectorString(newIfSet));
1208                 startResource(resource);
1209             } else {
1210                 // Existing interfaces are not removed.
1211                 itr = newIfSet.iterator();
1212                 while (itr.hasNext()) {
1213                     interfaceType = itr.next();
1214                     if (!curIfSet.contains(interfaceType)) {
1215                         jResource.addInterface(interfaceType);
1216                     }
1217                 }
1218             }
1219         } catch (SimulatorException e) {
1220             Activator
1221                     .getDefault()
1222                     .getLogManager()
1223                     .log(Level.ERROR.ordinal(),
1224                             new Date(),
1225                             "There is an error while changing the interface types."
1226                                     + Utility.getSimulatorErrorString(e, null));
1227             throw e;
1228         }
1229
1230         // Set the resource interfaces.
1231         resource.setResourceInterfaces(newIfSet);
1232
1233         return true;
1234     }
1235
1236     public boolean attributeValueUpdated(SingleResource resource,
1237             String attributeName, AttributeValue value) {
1238         if (null != resource && null != attributeName && null != value) {
1239             SimulatorSingleResource simRes = (SimulatorSingleResource) resource
1240                     .getSimulatorResource();
1241             if (null != simRes) {
1242                 try {
1243                     simRes.updateAttribute(attributeName, value);
1244                     return true;
1245                 } catch (SimulatorException e) {
1246                     Activator
1247                             .getDefault()
1248                             .getLogManager()
1249                             .log(Level.ERROR.ordinal(), new Date(),
1250                                     Utility.getSimulatorErrorString(e, null));
1251                 }
1252             }
1253         }
1254         return false;
1255     }
1256
1257     public boolean isResourceStarted(Resource resource) {
1258         if (null == resource) {
1259             return false;
1260         }
1261         return resource.isStarted();
1262     }
1263
1264     public boolean isPropertyValueInvalid(Resource resource,
1265             List<MetaProperty> properties, String propName) {
1266         if (null == resource || null == properties || null == propName) {
1267             return false;
1268         }
1269         boolean invalid = false;
1270         MetaProperty prop;
1271         Iterator<MetaProperty> itr = properties.iterator();
1272         while (itr.hasNext()) {
1273             prop = itr.next();
1274             if (prop.getPropName().equals(propName)) {
1275                 String value = prop.getPropValue();
1276                 if (propName.equals(Constants.RESOURCE_URI)) {
1277                     if (!Utility.isUriValid(value)) {
1278                         invalid = true;
1279                     }
1280                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1281                     if (!Utility.isResourceTypeValid(value)) {
1282                         invalid = true;
1283                     }
1284                 } else {
1285                     if (null == value || value.trim().isEmpty()) {
1286                         invalid = true;
1287                     }
1288                 }
1289             }
1290         }
1291         return invalid;
1292     }
1293
1294     public boolean isPropValueChanged(Resource resource,
1295             List<MetaProperty> properties, String propName) {
1296         if (null == resource || null == properties || null == propName) {
1297             return false;
1298         }
1299         boolean changed = false;
1300         MetaProperty prop;
1301         String oldValue;
1302         Iterator<MetaProperty> itr = properties.iterator();
1303         while (itr.hasNext()) {
1304             prop = itr.next();
1305             if (prop.getPropName().equals(propName)) {
1306                 oldValue = getPropertyValueFromResource(resource, propName);
1307                 if (null != oldValue && !prop.getPropValue().equals(oldValue)) {
1308                     changed = true;
1309                 }
1310                 break;
1311             }
1312         }
1313         return changed;
1314     }
1315
1316     private String getPropertyValueFromResource(Resource resource,
1317             String propName) {
1318         if (null == resource || null == propName) {
1319             return null;
1320         }
1321         if (propName.equals(Constants.RESOURCE_URI)) {
1322             return resource.getResourceURI();
1323         } else if (propName.equals(Constants.RESOURCE_NAME)) {
1324             return resource.getResourceName();
1325         } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1326             return resource.getResourceType();
1327         } else {
1328             return null;
1329         }
1330     }
1331
1332     public boolean isAttHasRangeOrAllowedValues(SimulatorResourceAttribute att) {
1333         if (null == att) {
1334             return false;
1335         }
1336         AttributeProperty prop = att.property();
1337         if (null == prop) {
1338             return false;
1339         }
1340
1341         if (prop.getType() == Type.INTEGER) {
1342             IntegerProperty intProperty = prop.asInteger();
1343             if (null != intProperty) {
1344                 return (intProperty.hasRange() || intProperty.hasValues());
1345             } else {
1346                 return false;
1347             }
1348         } else if (prop.getType() == Type.DOUBLE) {
1349             DoubleProperty dblProperty = prop.asDouble();
1350             if (null != dblProperty) {
1351                 return (dblProperty.hasRange() || dblProperty.hasValues());
1352             } else {
1353                 return false;
1354             }
1355         } else if (prop.getType() == Type.STRING) {
1356             StringProperty stringProperty = prop.asString();
1357             if (null != stringProperty) {
1358                 return stringProperty.hasValues();
1359             } else {
1360                 return false;
1361             }
1362         }
1363
1364         return true;
1365     }
1366
1367     public int startAutomation(SingleResource resource,
1368             AttributeElement attribute, AutoUpdateType autoType,
1369             int autoUpdateInterval) {
1370         int autoId = -1;
1371         if (null != resource && null != attribute) {
1372             SimulatorSingleResource server = (SimulatorSingleResource) resource
1373                     .getSimulatorResource();
1374             if (null != server) {
1375                 String attrName = attribute.getSimulatorResourceAttribute()
1376                         .name();
1377                 try {
1378                     autoId = server.startAttributeUpdation(attrName, autoType,
1379                             autoUpdateInterval, automationListener);
1380                 } catch (SimulatorException e) {
1381                     Activator
1382                             .getDefault()
1383                             .getLogManager()
1384                             .log(Level.ERROR.ordinal(),
1385                                     new Date(),
1386                                     "[" + e.getClass().getSimpleName() + "]"
1387                                             + e.code().toString() + "-"
1388                                             + e.message());
1389                     return -1;
1390                 }
1391                 if (-1 != autoId) {
1392                     attribute.setAutoUpdateId(autoId);
1393                     attribute.setAutoUpdateType(autoType);
1394                     attribute.setAutoUpdateInterval(autoUpdateInterval);
1395                     attribute.setAutoUpdateState(true);
1396                     resource.setAttributeAutomationInProgress(true);
1397                 }
1398             }
1399         }
1400         return autoId;
1401     }
1402
1403     public void stopAutomation(SingleResource resource, AttributeElement att,
1404             int autoId) {
1405         if (null != resource) {
1406             SimulatorSingleResource server = (SimulatorSingleResource) resource
1407                     .getSimulatorResource();
1408             if (null != server) {
1409                 try {
1410                     server.stopUpdation(autoId);
1411                 } catch (SimulatorException e) {
1412                     Activator
1413                             .getDefault()
1414                             .getLogManager()
1415                             .log(Level.ERROR.ordinal(),
1416                                     new Date(),
1417                                     "[" + e.getClass().getSimpleName() + "]"
1418                                             + e.code().toString() + "-"
1419                                             + e.message());
1420                     return;
1421                 }
1422                 // Change the automation status
1423                 att.setAutoUpdateState(false);
1424                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
1425             }
1426         }
1427     }
1428
1429     public boolean startResourceAutomationUIRequest(AutoUpdateType autoType,
1430             int autoUpdateInterval, final SingleResource resource) {
1431         if (null == resource) {
1432             return false;
1433         }
1434         boolean status = false;
1435         // Invoke the native automation method
1436         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
1437                 .getSimulatorResource();
1438         if (null != resourceServer) {
1439             int autoId = -1;
1440             try {
1441                 autoId = resourceServer.startResourceUpdation(autoType,
1442                         autoUpdateInterval, automationListener);
1443             } catch (SimulatorException e) {
1444                 Activator
1445                         .getDefault()
1446                         .getLogManager()
1447                         .log(Level.ERROR.ordinal(), new Date(),
1448                                 Utility.getSimulatorErrorString(e, null));
1449                 autoId = -1;
1450             }
1451             if (-1 != autoId) {
1452                 // Automation request accepted.
1453                 changeResourceLevelAutomationStatus(resource, true);
1454
1455                 resource.setAutomationId(autoId);
1456
1457                 // Notify the UI listeners in a different thread.
1458                 Thread notifyThread = new Thread() {
1459                     public void run() {
1460                         UiListenerHandler.getInstance()
1461                                 .resourceAutomationStartedUINotification(
1462                                         resource);
1463                     };
1464                 };
1465                 notifyThread.setPriority(Thread.MAX_PRIORITY);
1466                 notifyThread.start();
1467
1468                 status = true;
1469             }
1470         }
1471         return status;
1472     }
1473
1474     public boolean stopResourceAutomationUIRequest(final SingleResource resource) {
1475         if (null == resource) {
1476             return false;
1477         }
1478         final int autoId = resource.getAutomationId();
1479         if (-1 == autoId) {
1480             return false;
1481         }
1482         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
1483                 .getSimulatorResource();
1484         if (null == resourceServer) {
1485             return false;
1486         }
1487         // Call native method
1488         try {
1489             resourceServer.stopUpdation(autoId);
1490         } catch (SimulatorException e) {
1491             Activator
1492                     .getDefault()
1493                     .getLogManager()
1494                     .log(Level.ERROR.ordinal(), new Date(),
1495                             Utility.getSimulatorErrorString(e, null));
1496             return false;
1497         }
1498
1499         // Notify the UI Listeners. Invoke the automation complete callback.
1500         Thread stopThread = new Thread() {
1501             public void run() {
1502                 automationListener.onUpdateComplete(resource.getResourceURI(),
1503                         autoId);
1504             }
1505         };
1506         stopThread.start();
1507         return true;
1508     }
1509
1510     private boolean isAnyAttributeInAutomation(SingleResource resource) {
1511         if (null == resource || null == resource.getResourceRepresentation()) {
1512             return false;
1513         }
1514
1515         Map<String, AttributeElement> attributes = resource
1516                 .getResourceRepresentation().getAttributes();
1517         if (null == attributes || 0 == attributes.size())
1518             return false;
1519
1520         for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
1521             if (entry.getValue().isAutoUpdateInProgress())
1522                 return true;
1523         }
1524
1525         return false;
1526     }
1527
1528     // Changes the automation state of the resource and its attributes
1529     private void changeResourceLevelAutomationStatus(SingleResource resource,
1530             boolean status) {
1531
1532         if (null == resource || null == resource.getResourceRepresentation()) {
1533             return;
1534         }
1535
1536         Map<String, AttributeElement> attributes = resource
1537                 .getResourceRepresentation().getAttributes();
1538         if (null == attributes || 0 == attributes.size())
1539             return;
1540
1541         for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
1542             entry.getValue().setAutoUpdateState(status);
1543         }
1544
1545         resource.setResourceAutomationInProgress(status);
1546     }
1547
1548     private AttributeElement getAttributeWithGivenAutomationId(
1549             SingleResource resource, int automationId) {
1550         if (null == resource || null == resource.getResourceRepresentation()) {
1551             return null;
1552         }
1553
1554         Map<String, AttributeElement> attributes = resource
1555                 .getResourceRepresentation().getAttributes();
1556         if (null == attributes || 0 == attributes.size())
1557             return null;
1558
1559         for (Map.Entry<String, AttributeElement> entry : attributes.entrySet()) {
1560             if (automationId == entry.getValue().getAutoUpdateId())
1561                 return entry.getValue();
1562         }
1563
1564         return null;
1565     }
1566
1567     public boolean isResourceAutomationStarted(SingleResource resource) {
1568         boolean status = false;
1569         if (null != resource) {
1570             status = resource.isResourceAutomationInProgress();
1571         }
1572         return status;
1573     }
1574
1575     public boolean isAttributeAutomationStarted(SingleResource resource) {
1576         if (null == resource) {
1577             return false;
1578         }
1579         return resource.isAttributeAutomationInProgress();
1580     }
1581
1582     public void notifyObserverRequest(Resource resource, int observerId) {
1583         if (null == resource) {
1584             return;
1585         }
1586         SimulatorResource simulatorResource = resource.getSimulatorResource();
1587         if (null == simulatorResource) {
1588             return;
1589         }
1590         try {
1591             simulatorResource.notifyObserver(observerId);
1592         } catch (SimulatorException e) {
1593             Activator
1594                     .getDefault()
1595                     .getLogManager()
1596                     .log(Level.ERROR.ordinal(), new Date(),
1597                             Utility.getSimulatorErrorString(e, null));
1598         }
1599     }
1600
1601     public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
1602         if (null == att) {
1603             return null;
1604         }
1605
1606         AttributeValue value = att.value();
1607         if (null == value || null == value.get()) {
1608             return null;
1609         }
1610
1611         TypeInfo type = value.typeInfo();
1612
1613         if (type.mBaseType == ValueType.RESOURCEMODEL) {
1614             return null;
1615         }
1616
1617         List<String> values = new ArrayList<String>();
1618
1619         AttributeProperty prop = att.property();
1620         if (null == prop) {
1621             // Adding the current value of the attribute.
1622             values.add(new AttributeValueStringConverter(value).toString());
1623             return values;
1624         }
1625
1626         if (type.mType == ValueType.ARRAY) {
1627             if (type.mDepth == 1) {
1628                 ArrayProperty arrayProperty = prop.asArray();
1629                 if (null != arrayProperty) {
1630                     AttributeProperty childProp = arrayProperty
1631                             .getElementProperty();
1632                     switch (childProp.getType()) {
1633                         case INTEGER:
1634                             IntegerProperty intProperty = childProp.asInteger();
1635                             if (null != intProperty) {
1636                                 values.addAll(getAllValues(att, intProperty,
1637                                         Type.INTEGER));
1638                             }
1639                             break;
1640                         case DOUBLE:
1641                             DoubleProperty dblProperty = childProp.asDouble();
1642                             if (null != dblProperty) {
1643                                 values.addAll(getAllValues(att, dblProperty,
1644                                         Type.DOUBLE));
1645                             }
1646                             break;
1647                         case BOOLEAN:
1648                             BooleanProperty boolProperty = childProp
1649                                     .asBoolean();
1650                             if (null != boolProperty) {
1651                                 values.addAll(getAllValues(att, boolProperty,
1652                                         Type.BOOLEAN));
1653                             }
1654                             break;
1655                         case STRING:
1656                             StringProperty stringProperty = childProp
1657                                     .asString();
1658                             if (null != stringProperty) {
1659                                 values.addAll(getAllValues(att, stringProperty,
1660                                         Type.STRING));
1661                             }
1662                             break;
1663                         default:
1664                             break;
1665                     }
1666                 }
1667             }
1668         } else {
1669             switch (prop.getType()) {
1670                 case INTEGER:
1671                     IntegerProperty intProperty = prop.asInteger();
1672                     if (null != intProperty) {
1673                         values.addAll(getAllValues(att, intProperty,
1674                                 Type.INTEGER));
1675                     }
1676                     break;
1677                 case DOUBLE:
1678                     DoubleProperty dblProperty = prop.asDouble();
1679                     if (null != dblProperty) {
1680                         values.addAll(getAllValues(att, dblProperty,
1681                                 Type.DOUBLE));
1682                     }
1683                     break;
1684                 case BOOLEAN:
1685                     BooleanProperty boolProperty = prop.asBoolean();
1686                     if (null != boolProperty) {
1687                         values.addAll(getAllValues(att, boolProperty,
1688                                 Type.BOOLEAN));
1689                     }
1690                     break;
1691                 case STRING:
1692                     StringProperty stringProperty = prop.asString();
1693                     if (null != stringProperty) {
1694                         values.addAll(getAllValues(att, stringProperty,
1695                                 Type.STRING));
1696                     }
1697                     break;
1698                 default:
1699                     break;
1700             }
1701         }
1702
1703         return values;
1704     }
1705
1706     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1707             IntegerProperty intProperty, AttributeProperty.Type type) {
1708         List<String> values = new ArrayList<String>();
1709
1710         if (intProperty.hasRange()) {
1711             int min = (int) intProperty.min();
1712             int max = (int) intProperty.max();
1713             for (int iVal = min; iVal <= max; iVal++) {
1714                 values.add(String.valueOf(iVal));
1715             }
1716         } else if (intProperty.hasValues()) {
1717             for (Integer val : intProperty.getValues()) {
1718                 values.add(String.valueOf(val));
1719             }
1720         } else {
1721             AttributeValue value = attribute.value();
1722             if (null != value && null != value.get()) {
1723                 // Adding the current value of the attribute.
1724                 values.add(String.valueOf(value.get()));
1725             }
1726         }
1727         return values;
1728     }
1729
1730     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1731             DoubleProperty dblProperty, AttributeProperty.Type type) {
1732         NumberFormat formatter = NumberFormat.getInstance();
1733         List<String> values = new ArrayList<String>();
1734
1735         if (dblProperty.hasRange()) {
1736             double min = (double) dblProperty.min();
1737             double max = (double) dblProperty.max();
1738             for (double val = min; val <= max; val += 0.1) {
1739                 formatter.setMaximumFractionDigits(1);
1740                 formatter.setMinimumFractionDigits(1);
1741                 values.add(formatter.format(val));
1742             }
1743         } else if (dblProperty.hasValues()) {
1744             for (Double val : dblProperty.getValues()) {
1745                 values.add(String.valueOf(val));
1746             }
1747         } else {
1748             AttributeValue value = attribute.value();
1749             if (null != value && null != value.get()) {
1750                 // Adding the current value of the attribute.
1751                 values.add(String.valueOf(value.get()));
1752             }
1753         }
1754         return values;
1755     }
1756
1757     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1758             BooleanProperty boolProperty, AttributeProperty.Type type) {
1759         List<String> values = new ArrayList<String>();
1760         values.add("true");
1761         values.add("false");
1762         return values;
1763     }
1764
1765     public List<String> getAllValues(SimulatorResourceAttribute attribute,
1766             StringProperty stringProperty, AttributeProperty.Type type) {
1767         List<String> values = new ArrayList<String>();
1768
1769         if (stringProperty.hasValues()) {
1770             for (String val : stringProperty.getValues()) {
1771                 values.add(String.valueOf(val));
1772             }
1773         } else {
1774             AttributeValue value = attribute.value();
1775             if (null != value && null != value.get()) {
1776                 // Adding the current value of the attribute.
1777                 values.add(String.valueOf(value.get()));
1778             }
1779         }
1780         return values;
1781     }
1782
1783     public int getResourceCount() {
1784         return data.getResourceCount();
1785     }
1786
1787     public void shutdown() {
1788         threadHandle.interrupt();
1789     }
1790 }