3e80941878f40ed3b27b278859a0d09c8c188587
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / manager / ResourceManager.java
1 /*
2  * Copyright 2015 Samsung Electronics All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package oic.simulator.serviceprovider.manager;
18
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.Vector;
29
30 import oic.simulator.serviceprovider.Activator;
31 import oic.simulator.serviceprovider.model.CollectionResource;
32 import oic.simulator.serviceprovider.model.Device;
33 import oic.simulator.serviceprovider.model.LocalResourceAttribute;
34 import oic.simulator.serviceprovider.model.MetaProperty;
35 import oic.simulator.serviceprovider.model.Resource;
36 import oic.simulator.serviceprovider.model.ResourceType;
37 import oic.simulator.serviceprovider.model.SRMItem;
38 import oic.simulator.serviceprovider.model.SingleResource;
39 import oic.simulator.serviceprovider.utils.Constants;
40 import oic.simulator.serviceprovider.utils.Utility;
41
42 import org.oic.simulator.AttributeProperty;
43 import org.oic.simulator.AttributeProperty.Type;
44 import org.oic.simulator.AttributeValue;
45 import org.oic.simulator.AttributeValue.TypeInfo;
46 import org.oic.simulator.AttributeValue.ValueType;
47 import org.oic.simulator.ILogger.Level;
48 import org.oic.simulator.PlatformInfo;
49 import org.oic.simulator.SimulatorException;
50 import org.oic.simulator.SimulatorManager;
51 import org.oic.simulator.SimulatorResourceAttribute;
52 import org.oic.simulator.SimulatorResourceModel;
53 import org.oic.simulator.server.Observer;
54 import org.oic.simulator.server.SimulatorCollectionResource;
55 import org.oic.simulator.server.SimulatorResource;
56 import org.oic.simulator.server.SimulatorResource.AutoUpdateListener;
57 import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
58 import org.oic.simulator.server.SimulatorResource.ObserverListener;
59 import org.oic.simulator.server.SimulatorResource.ResourceModelChangeListener;
60 import org.oic.simulator.server.SimulatorSingleResource;
61
62 /**
63  * This class acts as an interface between the simulator java SDK and the
64  * various UI modules. It maintains all the details of resources and provides
65  * other UI modules with the information required. It also handles model change,
66  * automation, and observer related events from native layer and propagates
67  * those events to the registered UI listeners.
68  */
69 public class ResourceManager {
70
71     private Data                           data;
72
73     private Resource                       currentResourceInSelection;
74
75     private Device                         currentDeviceInSelection;
76
77     private ResourceModelChangeListener    resourceModelChangeListener;
78
79     private AutoUpdateListener             automationListener;
80
81     private ObserverListener               observer;
82
83     private NotificationSynchronizerThread synchronizerThread;
84
85     private Thread                         threadHandle;
86
87     private String                         deviceName;
88     private PlatformInfo                   platformInfo;
89
90     public ResourceManager() {
91         data = new Data();
92
93         // Set the default device and platform information
94         deviceName = "IoTivity Simulator";
95         try {
96             SimulatorManager.setDeviceInfo(deviceName);
97         } catch (SimulatorException e) {
98             Activator
99                     .getDefault()
100                     .getLogManager()
101                     .log(Level.ERROR.ordinal(),
102                             new Date(),
103                             "Error while registering the device info.\n"
104                                     + Utility.getSimulatorErrorString(e, null));
105         }
106
107         platformInfo = new PlatformInfo();
108         platformInfo.setPlatformID("Samsung Platform Identifier");
109         platformInfo.setManufacturerName("Samsung");
110         platformInfo.setManufacturerUrl("www.samsung.com");
111         platformInfo.setModelNumber("Samsung Model Num01");
112         platformInfo.setDateOfManufacture("2015-09-10T11:10:30Z");
113         platformInfo.setPlatformVersion("PlatformVersion01");
114         platformInfo.setOperationSystemVersion("OSVersion01");
115         platformInfo.setHardwareVersion("HardwareVersion01");
116         platformInfo.setFirmwareVersion("FirwareVersion01");
117         platformInfo.setSupportUrl("http://www.samsung.com/support");
118         platformInfo.setSystemTime("2015-09-10T11:10:30Z");
119         try {
120             SimulatorManager.setPlatformInfo(platformInfo);
121         } catch (SimulatorException e) {
122             Activator
123                     .getDefault()
124                     .getLogManager()
125                     .log(Level.ERROR.ordinal(),
126                             new Date(),
127                             "Error while registering the platform info.\n"
128                                     + Utility.getSimulatorErrorString(e, null));
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                         Resource resource = data.getResourceByURI(resourceURI);
145                         if (null == resource) {
146                             return;
147                         }
148
149                         resource.setResourceModel(resourceModelN);
150
151                         // 7. Fetch the resource attributes.
152                         Map<String, LocalResourceAttribute> resourceAttributeMap;
153                         try {
154                             resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
155                             if (null != resourceAttributeMap) {
156                                 resource.setResourceAttributes(resourceAttributeMap);
157                             }
158                         } catch (SimulatorException e) {
159                             // TODO Auto-generated catch block
160                             e.printStackTrace();
161                         }
162
163                         UiListenerHandler.getInstance()
164                                 .resourceModelChangedUINotification(resource);
165                     }
166                 });
167             }
168         };
169
170         automationListener = new AutoUpdateListener() {
171
172             @Override
173             public void onUpdateComplete(final String resourceURI,
174                     final int automationId) {
175                 synchronizerThread.addToQueue(new Runnable() {
176
177                     @Override
178                     public void run() {
179                         SingleResource resource = data
180                                 .getSingleResourceByURI(resourceURI);
181                         if (null == resource) {
182                             return;
183                         }
184                         // Checking whether this notification is for an
185                         // attribute or a resource
186                         if (resource.isResourceAutomationInProgress()) {
187                             changeResourceLevelAutomationStatus(resource, false);
188                             // Notify the UI listeners
189                             UiListenerHandler.getInstance()
190                                     .automationCompleteUINotification(resource,
191                                             null);
192                         } else if (resource.isAttributeAutomationInProgress()) {
193                             // Find the attribute with the given automation id
194                             LocalResourceAttribute attribute;
195                             attribute = getAttributeWithGivenAutomationId(
196                                     resource, automationId);
197                             if (null != attribute) {
198                                 attribute.setAutomationInProgress(false);
199                                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
200                                 // Notify the UI listeners
201                                 UiListenerHandler
202                                         .getInstance()
203                                         .automationCompleteUINotification(
204                                                 resource,
205                                                 attribute
206                                                         .getResourceAttributeRef()
207                                                         .name());
208                             } else {
209                                 // TODO: Temporarily reset the attribute
210                                 // automation status to false for making
211                                 // resource-level automation work after
212                                 // attribute-level automations.
213                                 resource.setAttributeAutomationInProgress(false);
214                             }
215                         }
216                     }
217                 });
218             }
219         };
220
221         observer = new ObserverListener() {
222
223             public void onObserverChanged(final String resourceURI,
224                     final int status, final Observer observer) {
225                 new Thread() {
226                     @Override
227                     public void run() {
228                         if (null == resourceURI || null == observer) {
229                             return;
230                         }
231                         Resource resource = data.getResourceByURI(resourceURI);
232                         if (null == resource) {
233                             return;
234                         }
235                         // Update the observers information
236                         if (status == 0) {
237                             resource.addObserverInfo(observer);
238                         } else {
239                             resource.removeObserverInfo(observer);
240                         }
241                         // Notify the UI listeners
242                         UiListenerHandler.getInstance()
243                                 .observerListChangedUINotification(resource);
244                     }
245                 }.start();
246             }
247
248             @Override
249             public void onObserverAdded(String resourceURI, Observer observer) {
250                 onObserverChanged(resourceURI, 0, observer);
251             }
252
253             @Override
254             public void onObserverRemoved(String resourceURI, Observer observer) {
255                 onObserverChanged(resourceURI, 1, observer);
256             }
257         };
258
259         synchronizerThread = new NotificationSynchronizerThread();
260         threadHandle = new Thread(synchronizerThread);
261         threadHandle.setName("Simulator service provider event queue");
262         threadHandle.start();
263     }
264
265     private static class NotificationSynchronizerThread implements Runnable {
266
267         LinkedList<Runnable> notificationQueue = new LinkedList<Runnable>();
268
269         @Override
270         public void run() {
271             while (!Thread.interrupted()) {
272                 synchronized (this) {
273                     try {
274                         while (notificationQueue.isEmpty()) {
275                             this.wait();
276                             break;
277                         }
278                     } catch (InterruptedException e) {
279                         return;
280                     }
281                 }
282
283                 Runnable thread;
284                 synchronized (this) {
285                     thread = notificationQueue.pop();
286                 }
287                 try {
288                     thread.run();
289                 } catch (Exception e) {
290                     if (e instanceof InterruptedException) {
291                         return;
292                     }
293                     e.printStackTrace();
294                 }
295             }
296         }
297
298         public void addToQueue(Runnable event) {
299             synchronized (this) {
300                 notificationQueue.add(event);
301                 this.notify();
302             }
303         }
304     }
305
306     public String getDeviceName() {
307         return deviceName;
308     }
309
310     public void setDeviceName(String deviceName) {
311         this.deviceName = deviceName;
312         try {
313             SimulatorManager.setDeviceInfo(deviceName);
314         } catch (SimulatorException e) {
315             Activator
316                     .getDefault()
317                     .getLogManager()
318                     .log(Level.ERROR.ordinal(),
319                             new Date(),
320                             "Error while registering the device info.\n"
321                                     + Utility.getSimulatorErrorString(e, null));
322         }
323     }
324
325     public List<MetaProperty> getPlatformInfo() {
326         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
327         metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platformInfo
328                 .getPlatformID()));
329         metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME,
330                 platformInfo.getManufacturerName()));
331         metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
332                 platformInfo.getManufacturerUrl()));
333         metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
334                 platformInfo.getModelNumber()));
335         metaProperties.add(new MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC,
336                 platformInfo.getDateOfManufacture()));
337         metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
338                 platformInfo.getPlatformVersion()));
339         metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
340                 platformInfo.getOperationSystemVersion()));
341         metaProperties.add(new MetaProperty(
342                 Constants.PLATFORM_HARDWARE_VERSION, platformInfo
343                         .getHardwareVersion()));
344         metaProperties.add(new MetaProperty(
345                 Constants.PLATFORM_FIRMWARE_VERSION, platformInfo
346                         .getFirmwareVersion()));
347         metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
348                 platformInfo.getSupportUrl()));
349         metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
350                 platformInfo.getSystemTime()));
351         return metaProperties;
352     }
353
354     public void setPlatformInfo(List<MetaProperty> metaProperties) {
355         if (null == metaProperties || metaProperties.size() < 1) {
356             return;
357         }
358         Iterator<MetaProperty> itr = metaProperties.iterator();
359         MetaProperty prop;
360         String propName;
361         String propValue;
362         while (itr.hasNext()) {
363             prop = itr.next();
364             propName = prop.getPropName();
365             propValue = prop.getPropValue();
366             if (propName.equals(Constants.PLATFORM_ID)) {
367                 platformInfo.setPlatformID(propValue);
368             } else if (propName.equals(Constants.PLATFORM_MANUFAC_NAME)) {
369                 platformInfo.setManufacturerName(propValue);
370             } else if (propName.equals(Constants.PLATFORM_MANUFAC_URL)) {
371                 platformInfo.setManufacturerUrl(propValue);
372             } else if (propName.equals(Constants.PLATFORM_MODEL_NO)) {
373                 platformInfo.setModelNumber(propValue);
374             } else if (propName.equals(Constants.PLATFORM_DATE_OF_MANUFAC)) {
375                 platformInfo.setDateOfManufacture(propValue);
376             } else if (propName.equals(Constants.PLATFORM_VERSION)) {
377                 platformInfo.setPlatformVersion(propValue);
378             } else if (propName.equals(Constants.PLATFORM_OS_VERSION)) {
379                 platformInfo.setOperationSystemVersion(propValue);
380             } else if (propName.equals(Constants.PLATFORM_HARDWARE_VERSION)) {
381                 platformInfo.setHardwareVersion(propValue);
382             } else if (propName.equals(Constants.PLATFORM_FIRMWARE_VERSION)) {
383                 platformInfo.setFirmwareVersion(propValue);
384             } else if (propName.equals(Constants.PLATFORM_SUPPORT_URL)) {
385                 platformInfo.setSupportUrl(propValue);
386             } else if (propName.equals(Constants.PLATFORM_SYSTEM_TIME)) {
387                 platformInfo.setSystemTime(propValue);
388             }
389         }
390         try {
391             SimulatorManager.setPlatformInfo(platformInfo);
392         } catch (SimulatorException e) {
393             Activator
394                     .getDefault()
395                     .getLogManager()
396                     .log(Level.ERROR.ordinal(),
397                             new Date(),
398                             "Error while registering the platform info.\n"
399                                     + Utility.getSimulatorErrorString(e, null));
400         }
401     }
402
403     public synchronized Resource getCurrentResourceInSelection() {
404         return currentResourceInSelection;
405     }
406
407     public synchronized void setCurrentResourceInSelection(Resource resource) {
408         this.currentResourceInSelection = resource;
409     }
410
411     public synchronized Device getCurrentDeviceInSelection() {
412         return currentDeviceInSelection;
413     }
414
415     public synchronized void setCurrentDeviceInSelection(Device dev) {
416         this.currentDeviceInSelection = dev;
417     }
418
419     public boolean isResourceExist(String resourceURI) {
420         return data.isResourceExist(resourceURI);
421     }
422
423     public boolean isAnyResourceExist() {
424         return data.isAnyResourceExist();
425     }
426
427     public boolean createSingleResource(SingleResource resource)
428             throws SimulatorException {
429         if (null == resource) {
430             return false;
431         }
432         String resType = (String) resource.getResourceTypes().toArray()[0];
433         try {
434             // 1. Create the resource.
435             SimulatorResource jSimulatorResource = SimulatorManager
436                     .createResource(SimulatorResource.Type.SINGLE,
437                             resource.getResourceName(),
438                             resource.getResourceURI(), resType);
439             if (null == jSimulatorResource
440                     || !(jSimulatorResource instanceof SimulatorSingleResource)) {
441                 return false;
442             }
443             SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) jSimulatorResource;
444             resource.setSimulatorResource(jSimulatorSingleResource);
445
446             // 2. Cancel observable property if requested by user.
447             if (!resource.isObservable()) {
448                 jSimulatorSingleResource.setObservable(false);
449             }
450
451             // 3. Set the model change listener.
452             jSimulatorSingleResource
453                     .setResourceModelChangeListener(resourceModelChangeListener);
454
455             // 4. Set the observer listener if the resource is observable.
456             if (resource.isObservable()) {
457                 jSimulatorSingleResource.setObserverListener(observer);
458             }
459
460             // 5. Add attributes.
461             Map<String, LocalResourceAttribute> attributes = resource
462                     .getResourceAttributes();
463             if (null != attributes && !attributes.isEmpty()) {
464                 Set<String> keySet = attributes.keySet();
465                 Iterator<String> itr = keySet.iterator();
466
467                 String attName;
468                 LocalResourceAttribute localAtt;
469                 SimulatorResourceAttribute simResAtt;
470
471                 while (itr.hasNext()) {
472                     attName = itr.next();
473                     localAtt = attributes.get(attName);
474                     if (null == localAtt) {
475                         continue;
476                     }
477                     simResAtt = localAtt.getResourceAttributeRef();
478                     if (null == simResAtt) {
479                         continue;
480                     }
481                     jSimulatorSingleResource.addAttribute(simResAtt);
482                 }
483
484                 // 6. Get the resource model java object reference.
485                 resource.setResourceModel(jSimulatorSingleResource
486                         .getResourceModel());
487             }
488
489             // 7. Register the resource with the platform.
490             jSimulatorSingleResource.start();
491             resource.setStarted(true);
492         } catch (SimulatorException e) {
493             Activator
494                     .getDefault()
495                     .getLogManager()
496                     .log(Level.ERROR.ordinal(), new Date(),
497                             Utility.getSimulatorErrorString(e, null));
498             throw e;
499         }
500
501         // 8. Add to local cache.
502         data.addResource(resource);
503
504         // 9. Update UI listeners
505         UiListenerHandler.getInstance().resourceCreatedUINotification(
506                 ResourceType.SINGLE);
507
508         return true;
509     }
510
511     public boolean createCollectionResource(CollectionResource resource)
512             throws SimulatorException {
513         if (null == resource) {
514             return false;
515         }
516         String resType = (String) resource.getResourceTypes().toArray()[0];
517         try {
518             // 1. Create the resource.
519             SimulatorResource jSimulatorResource = SimulatorManager
520                     .createResource(SimulatorResource.Type.COLLECTION,
521                             resource.getResourceName(),
522                             resource.getResourceURI(), resType);
523             if (null == jSimulatorResource
524                     || !(jSimulatorResource instanceof SimulatorCollectionResource)) {
525                 return false;
526             }
527             SimulatorCollectionResource jSimulatorCollectionResource = (SimulatorCollectionResource) jSimulatorResource;
528             resource.setSimulatorResource(jSimulatorCollectionResource);
529
530             // 2. Cancel observable property if requested by user.
531             if (!resource.isObservable()) {
532                 jSimulatorCollectionResource.setObservable(false);
533             }
534
535             // 3. Set the observer listener if the resource is observable.
536             if (resource.isObservable()) {
537                 jSimulatorCollectionResource.setObserverListener(observer);
538             }
539
540             // 4. Set the model change listener.
541             jSimulatorCollectionResource
542                     .setResourceModelChangeListener(resourceModelChangeListener);
543
544             // 5. Register the resource with the platform.
545             jSimulatorCollectionResource.start();
546             resource.setStarted(true);
547         } catch (SimulatorException e) {
548             Activator
549                     .getDefault()
550                     .getLogManager()
551                     .log(Level.ERROR.ordinal(), new Date(),
552                             Utility.getSimulatorErrorString(e, null));
553             throw e;
554         }
555
556         // 6. Add to local cache.
557         data.addResource(resource);
558
559         // 7. Update UI listeners
560         UiListenerHandler.getInstance().resourceCreatedUINotification(
561                 ResourceType.COLLECTION);
562
563         return true;
564     }
565
566     public Resource createResourceByRAML(String configFilePath)
567             throws SimulatorException {
568         Resource resource = null;
569         try {
570             // 1. Create the resource
571             SimulatorResource jSimulatorResource = SimulatorManager
572                     .createResource(configFilePath);
573             if (null == jSimulatorResource) {
574                 return null;
575             }
576             if (jSimulatorResource instanceof SimulatorSingleResource) {
577                 resource = new SingleResource();
578             } else {
579                 resource = new CollectionResource();
580             }
581             resource.setSimulatorResource(jSimulatorResource);
582
583             // 2. Fetch and locally store the resource name and uri.
584             String uri = jSimulatorResource.getURI();
585             if (null == uri || uri.trim().isEmpty()) {
586                 return null;
587             }
588             resource.setResourceURI(uri.trim());
589
590             String name = jSimulatorResource.getName();
591             if (null == name || name.trim().isEmpty()) {
592                 return null;
593             }
594             resource.setResourceName(name.trim());
595         } catch (SimulatorException e) {
596             Activator
597                     .getDefault()
598                     .getLogManager()
599                     .log(Level.ERROR.ordinal(), new Date(),
600                             Utility.getSimulatorErrorString(e, null));
601             throw e;
602         }
603         return resource;
604     }
605
606     /**
607      * This method can set/change the resource uri and name of an already
608      * created resource which is not yet registered with the platform. This
609      * method registers the model change and observer listeners, registers the
610      * resource, fetches the resource attributes, updates the local cache and
611      * notifies the UI listeners.
612      */
613     public boolean completeSingleResourceCreationByRAML(Resource resource,
614             String uri, String name, boolean multiInstance)
615             throws SimulatorException {
616         if (null == resource || !(resource instanceof SingleResource)) {
617             return false;
618         }
619         try {
620             SingleResource singleRes = (SingleResource) resource;
621
622             SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) resource
623                     .getSimulatorResource();
624             if (null == jSimulatorSingleResource) {
625                 return false;
626             }
627
628             // 1. Update resource URI and Name if they are changed.
629             String newUri = uri.trim();
630             String newName = name.trim();
631
632             if (multiInstance) {
633                 singleRes.setResourceURI(newUri);
634                 singleRes.setResourceName(newName);
635             } else {
636                 if (!singleRes.getResourceURI().equals(newUri)) {
637                     jSimulatorSingleResource.setURI(newUri);
638                     singleRes.setResourceURI(newUri);
639                 }
640                 if (!singleRes.getResourceName().equals(newName)) {
641                     jSimulatorSingleResource.setName(newName);
642                     singleRes.setResourceName(newName);
643                 }
644             }
645
646             // 2. Set the model change listener.
647             jSimulatorSingleResource
648                     .setResourceModelChangeListener(resourceModelChangeListener);
649
650             // 3. Set the observer listener if the resource is observable.
651             if (jSimulatorSingleResource.isObservable()) {
652                 jSimulatorSingleResource.setObserverListener(observer);
653                 singleRes.setObservable(true);
654             }
655
656             // 4. Fetch the resource model.
657             SimulatorResourceModel jResModel = jSimulatorSingleResource
658                     .getResourceModel();
659             if (null == jResModel) {
660                 return false;
661             }
662             singleRes.setResourceModel(jResModel);
663
664             // 5. Fetch the basic details of the resource.
665             singleRes.addResourceType(jSimulatorSingleResource
666                     .getResourceType());
667             singleRes
668                     .setResourceInterfaces(Utility
669                             .convertVectorToSet(jSimulatorSingleResource
670                                     .getInterface()));
671
672             // 6. Register the resource with the platform.
673             jSimulatorSingleResource.start();
674             singleRes.setStarted(true);
675
676             // 7. Fetch the resource attributes.
677             Map<String, LocalResourceAttribute> resourceAttributeMap;
678             resourceAttributeMap = fetchResourceAttributesFromModel(jResModel);
679             if (null != resourceAttributeMap) {
680                 singleRes.setResourceAttributes(resourceAttributeMap);
681             }
682
683             // 8. Add to local cache.
684             data.addResource(singleRes);
685
686             // 9. Update UI listeners for single instance creation
687             if (!multiInstance)
688                 UiListenerHandler.getInstance().resourceCreatedUINotification(
689                         ResourceType.SINGLE);
690         } catch (SimulatorException e) {
691             Activator
692                     .getDefault()
693                     .getLogManager()
694                     .log(Level.ERROR.ordinal(), new Date(),
695                             Utility.getSimulatorErrorString(e, null));
696             throw e;
697         }
698         return true;
699     }
700
701     /**
702      * This method can set/change the resource uri and name of an already
703      * created resource which is not yet registered with the platform. This
704      * method registers the model change and observer listeners, registers the
705      * resource, fetches the resource attributes, updates the local cache and
706      * notifies the UI listeners.
707      */
708     public boolean completeCollectionResourceCreationByRAML(Resource resource,
709             String uri, String name) throws SimulatorException {
710         if (null == resource || !(resource instanceof CollectionResource)) {
711             return false;
712         }
713         try {
714             CollectionResource collectionRes = (CollectionResource) resource;
715
716             SimulatorCollectionResource jSimulatorCollectionResource = (SimulatorCollectionResource) resource
717                     .getSimulatorResource();
718             if (null == jSimulatorCollectionResource) {
719                 return false;
720             }
721
722             // 1. Update resource URI and Name if they are changed.
723             String newUri = uri.trim();
724             String newName = name.trim();
725
726             if (!collectionRes.getResourceURI().equals(newUri)) {
727                 jSimulatorCollectionResource.setURI(newUri);
728                 collectionRes.setResourceURI(newUri);
729             }
730             if (!collectionRes.getResourceName().equals(newName)) {
731                 jSimulatorCollectionResource.setName(newName);
732                 collectionRes.setResourceName(newName);
733             }
734
735             // 2. Set the model change listener.
736             jSimulatorCollectionResource
737                     .setResourceModelChangeListener(resourceModelChangeListener);
738
739             // 3. Fetch the resource model.
740             SimulatorResourceModel jResModel = jSimulatorCollectionResource
741                     .getResourceModel();
742             if (null == jResModel) {
743                 return false;
744             }
745             collectionRes.setResourceModel(jResModel);
746
747             // 4. Fetch the basic details of the resource.
748             collectionRes.addResourceType(jSimulatorCollectionResource
749                     .getResourceType());
750             collectionRes.setResourceInterfaces(Utility
751                     .convertVectorToSet(jSimulatorCollectionResource
752                             .getInterface()));
753
754             // 5. Set the observer listener if the resource is observable.
755             if (jSimulatorCollectionResource.isObservable()) {
756                 jSimulatorCollectionResource.setObserverListener(observer);
757                 collectionRes.setObservable(true);
758             }
759
760             // 6. Register the resource with the platform.
761             jSimulatorCollectionResource.start();
762             collectionRes.setStarted(true);
763
764             // 7. Fetch the resource attributes.
765             Map<String, LocalResourceAttribute> resourceAttributeMap;
766             resourceAttributeMap = fetchResourceAttributesFromModel(jResModel);
767             if (null != resourceAttributeMap) {
768                 collectionRes.setResourceAttributes(resourceAttributeMap);
769             }
770
771             // 6. Add to local cache.
772             data.addResource(collectionRes);
773
774             // 7. Update UI listeners for single instance creation
775             UiListenerHandler.getInstance().resourceCreatedUINotification(
776                     ResourceType.COLLECTION);
777         } catch (SimulatorException e) {
778             Activator
779                     .getDefault()
780                     .getLogManager()
781                     .log(Level.ERROR.ordinal(), new Date(),
782                             Utility.getSimulatorErrorString(e, null));
783             throw e;
784         }
785         return true;
786     }
787
788     public int createSingleResourceMultiInstances(String configFile, int count)
789             throws SimulatorException {
790         int createCount = 0;
791         try {
792             Vector<SimulatorResource> jSimulatorResources = SimulatorManager
793                     .createResource(configFile, count);
794             if (null == jSimulatorResources || jSimulatorResources.size() < 1) {
795                 return 0;
796             }
797             SimulatorSingleResource jResource;
798             SingleResource resource;
799             boolean result;
800             for (SimulatorResource jSimulatorResource : jSimulatorResources) {
801                 jResource = (SimulatorSingleResource) jSimulatorResource;
802                 resource = new SingleResource();
803                 resource.setSimulatorResource(jResource);
804                 try {
805                     result = completeSingleResourceCreationByRAML(resource,
806                             jResource.getURI(), jResource.getName(), true);
807                     if (result) {
808                         createCount++;
809                     }
810                 } catch (SimulatorException eInner) {
811                     Activator
812                             .getDefault()
813                             .getLogManager()
814                             .log(Level.ERROR.ordinal(),
815                                     new Date(),
816                                     Utility.getSimulatorErrorString(eInner,
817                                             null));
818                 }
819             }
820             if (createCount > 0) {
821                 UiListenerHandler.getInstance().resourceCreatedUINotification(
822                         ResourceType.SINGLE);
823             }
824         } catch (SimulatorException eOuter) {
825             Activator
826                     .getDefault()
827                     .getLogManager()
828                     .log(Level.ERROR.ordinal(), new Date(),
829                             Utility.getSimulatorErrorString(eOuter, null));
830             throw eOuter;
831         }
832         return createCount;
833     }
834
835     public void createDevice(String deviceName, Set<Resource> childs) {
836         // 1. Create device
837         Device dev = new Device();
838         dev.setDeviceName(deviceName);
839         data.addDevice(dev);
840
841         // 2. Add children to device
842         if (null != childs && !childs.isEmpty())
843             addResourceToDevice(dev, childs);
844
845         // 3. Update ui listeners
846         UiListenerHandler.getInstance().resourceListUpdateUINotification(
847                 ResourceType.DEVICE);
848     }
849
850     private Map<String, LocalResourceAttribute> fetchResourceAttributesFromModel(
851             SimulatorResourceModel jResModel) throws SimulatorException {
852         Map<String, LocalResourceAttribute> resourceAttributeMap = null;
853         if (null != jResModel) {
854             Map<String, SimulatorResourceAttribute> jAttributeMap;
855             jAttributeMap = jResModel.getAttributes();
856             if (null != jAttributeMap) {
857                 resourceAttributeMap = new HashMap<String, LocalResourceAttribute>();
858                 Iterator<String> itr = jAttributeMap.keySet().iterator();
859                 String attName;
860                 SimulatorResourceAttribute jResAtt;
861                 LocalResourceAttribute localAtt;
862                 while (itr.hasNext()) {
863                     attName = itr.next();
864                     if (null != attName) {
865                         jResAtt = jAttributeMap.get(attName);
866                         if (null != jResAtt) {
867                             localAtt = new LocalResourceAttribute();
868
869                             localAtt.setResourceAttributeRef(jResAtt);
870
871                             // Initially disabling the automation
872                             localAtt.setAutomationInProgress(false);
873
874                             // Assigning the default automation interval
875                             localAtt.setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
876
877                             // Setting the default automation type
878                             localAtt.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
879
880                             resourceAttributeMap.put(attName, localAtt);
881                         }
882                     }
883                 }
884             }
885         }
886         return resourceAttributeMap;
887
888     }
889
890     // This method gives all known possible values of the attribute in string
891     // format. It takes allowed values or range of values whichever is available
892     private List<String> getValueList(SimulatorResourceAttribute attributeN) {
893         AttributeProperty attProp = attributeN.property();
894         if (null == attProp) {
895             return null;
896         }
897         List<String> valueList = new ArrayList<String>();
898         Type valuesType = attProp.type();
899         if (valuesType == Type.VALUESET) {
900             Object[] allowedValues = attProp.valueSet();
901             if (null != allowedValues && allowedValues.length > 0) {
902                 for (Object value : allowedValues) {
903                     if (null != value) {
904                         valueList.add(String.valueOf(((AttributeValue) value)
905                                 .get()));
906                     }
907                 }
908             }
909         } else if (valuesType == Type.RANGE) {
910             double minD = attProp.min();
911             double maxD = attProp.max();
912             for (double value = minD; value <= maxD; value++) {
913                 valueList.add(String.valueOf(value));
914             }
915         }
916         Object attValue = attributeN.value().get();
917         if (valueList.size() < 1 && null != attValue) {
918             valueList.add(String.valueOf(attValue));
919         }
920         return valueList;
921     }
922
923     public List<Resource> getResourceList() {
924         List<Resource> resourceList = data.getResources();
925         if (null == resourceList) {
926             return null;
927         }
928         // Sort the list
929         Collections.sort(resourceList, Utility.resourceComparator);
930
931         return resourceList;
932     }
933
934     public List<SingleResource> getSingleResourceList() {
935         List<SingleResource> resourceList = data.getSingleResources();
936         if (null == resourceList) {
937             return null;
938         }
939         // Sort the list
940         Collections.sort(resourceList, Utility.singleResourceComparator);
941
942         return resourceList;
943     }
944
945     public List<CollectionResource> getCollectionResourceList() {
946         List<CollectionResource> resourceList = data.getCollectionResources();
947         if (null == resourceList) {
948             return null;
949         }
950         // Sort the list
951         Collections.sort(resourceList, Utility.collectionResourceComparator);
952
953         return resourceList;
954     }
955
956     public List<Device> getDeviceList() {
957         List<Device> deviceList = data.getDevices();
958         if (null == deviceList) {
959             return null;
960         }
961         // Sort the list
962         Collections.sort(deviceList, Utility.deviceComparator);
963         return deviceList;
964     }
965
966     // Returns the number of resources which are added properly to the
967     // collection.
968     public int addResourceToCollection(CollectionResource collectionParent,
969             Set<Resource> childs) {
970         if (null == collectionParent || null == childs || childs.isEmpty()) {
971             return -1;
972         }
973         Iterator<Resource> itr = childs.iterator();
974         Resource res;
975         int count = childs.size();
976         while (itr.hasNext()) {
977             res = itr.next();
978             try {
979                 addResourceToCollection(collectionParent, res);
980             } catch (SimulatorException e) {
981                 count--;
982             }
983         }
984         return count;
985     }
986
987     public void addResourceToCollection(CollectionResource collectionParent,
988             Resource child) throws SimulatorException {
989         if (null == collectionParent || null == child) {
990             return;
991         }
992         try {
993             // 1. Add child to collection
994             collectionParent.addChildResource(child);
995
996             // 2. Add a reference to the collection in the child
997             if (child instanceof SingleResource) {
998                 ((SingleResource) child)
999                         .addCollectionMembership(collectionParent);
1000             } else {
1001                 ((CollectionResource) child).addMembership(collectionParent);
1002             }
1003         } catch (SimulatorException e) {
1004             Activator
1005                     .getDefault()
1006                     .getLogManager()
1007                     .log(Level.ERROR.ordinal(), new Date(),
1008                             Utility.getSimulatorErrorString(e, null));
1009             throw e;
1010         }
1011     }
1012
1013     public int addResourceToCollection(Set<CollectionResource> collections,
1014             Resource child) {
1015         if (null == collections || collections.isEmpty() || null == child) {
1016             return -1;
1017         }
1018         Iterator<CollectionResource> itr = collections.iterator();
1019         CollectionResource res;
1020         int count = collections.size();
1021         while (itr.hasNext()) {
1022             res = itr.next();
1023             try {
1024                 addResourceToCollection(res, child);
1025             } catch (SimulatorException e) {
1026                 count--;
1027             }
1028         }
1029         return count;
1030     }
1031
1032     public void addResourceToDevice(Device dev, Set<Resource> childs) {
1033         // 1. Add children to the device.
1034         dev.addChildResource(childs);
1035
1036         // 2. Add a reference to the device in all children.
1037         Iterator<Resource> itr = childs.iterator();
1038         Resource res;
1039         while (itr.hasNext()) {
1040             res = itr.next();
1041             if (res instanceof SingleResource) {
1042                 ((SingleResource) res).addDeviceMembership(dev);
1043             } else {
1044                 ((CollectionResource) res).addDeviceMembership(dev);
1045             }
1046         }
1047     }
1048
1049     public void addResourceToDevice(Device dev, Resource child) {
1050         // 1. Add child to the device.
1051         dev.addChildResource(child);
1052
1053         // 2. Add a reference to the device in the child.
1054         if (child instanceof SingleResource) {
1055             ((SingleResource) child).addDeviceMembership(dev);
1056         } else {
1057             ((CollectionResource) child).addDeviceMembership(dev);
1058         }
1059     }
1060
1061     public void addResourceToDevice(Set<Device> devices, Resource child) {
1062         // 1. Add device reference in child.
1063         if (child instanceof SingleResource)
1064             ((SingleResource) child).addDeviceMembership(devices);
1065         else
1066             ((CollectionResource) child).addDeviceMembership(devices);
1067
1068         // 2. Add a reference to the child in all devices.
1069         Iterator<Device> itr = devices.iterator();
1070         Device dev;
1071         while (itr.hasNext()) {
1072             dev = itr.next();
1073             dev.addChildResource(child);
1074         }
1075     }
1076
1077     public int removeResourceFromCollection(
1078             Set<CollectionResource> collections, Resource resource) {
1079         // 1. Remove the reference of resource from all the collections.
1080         Iterator<CollectionResource> itr = collections.iterator();
1081         CollectionResource colRes;
1082         int count = collections.size();
1083         while (itr.hasNext()) {
1084             colRes = itr.next();
1085             try {
1086                 removeResourceFromCollection(colRes, resource);
1087             } catch (SimulatorException e) {
1088                 count--;
1089             }
1090         }
1091         return count;
1092
1093     }
1094
1095     public void removeResourceFromDevice(Set<Device> devices, Resource resource) {
1096         // 1. Remove the reference of resource from all the devices.
1097         Iterator<Device> itr = devices.iterator();
1098         Device dev;
1099         while (itr.hasNext()) {
1100             dev = itr.next();
1101             dev.removeChildResource(resource);
1102         }
1103
1104         // 2. Remove the reference of devices from the resource.
1105         resource.removeDeviceMembership(devices);
1106     }
1107
1108     // Returns the count of resources removed from the collection
1109     public int removeResourcesFromCollection(CollectionResource colRes,
1110             Set<Resource> resources) {
1111         Iterator<Resource> itr = resources.iterator();
1112         Resource res;
1113         int count = resources.size();
1114         while (itr.hasNext()) {
1115             res = itr.next();
1116             try {
1117                 removeResourceFromCollection(colRes, res);
1118             } catch (SimulatorException e) {
1119                 count--;
1120             }
1121         }
1122         return count;
1123     }
1124
1125     public void removeResourcesFromDevice(Device dev, Set<Resource> resources) {
1126         Iterator<Resource> itr = resources.iterator();
1127         Resource res;
1128         while (itr.hasNext()) {
1129             res = itr.next();
1130             res.removeDeviceMembership(dev);
1131         }
1132         dev.removeChildResource(resources);
1133     }
1134
1135     public void removeResourceFromCollection(CollectionResource parent,
1136             Resource child) throws SimulatorException {
1137         try {
1138             // 1. Remove the child from the parent
1139             parent.removeChildResource(child);
1140
1141             // 2. Remove the reference to parent from child
1142             if (child instanceof SingleResource) {
1143                 ((SingleResource) child).removeCollectionMembership(parent);
1144             } else {
1145                 ((CollectionResource) child).removeMembership(parent);
1146             }
1147         } catch (SimulatorException e) {
1148             Activator
1149                     .getDefault()
1150                     .getLogManager()
1151                     .log(Level.ERROR.ordinal(), new Date(),
1152                             Utility.getSimulatorErrorString(e, null));
1153             throw e;
1154         }
1155     }
1156
1157     public void removeResourceFromDevice(Device parent, Resource child) {
1158         // 1. Remove the reference to parent from child
1159         child.removeDeviceMembership(parent);
1160
1161         // 2. Remove the child from the parent
1162         parent.removeChildResource(child);
1163     }
1164
1165     public void removeSingleResources(Set<SingleResource> resources)
1166             throws SimulatorException {
1167         if (null == resources) {
1168             return;
1169         }
1170         Iterator<SingleResource> itr = resources.iterator();
1171         while (itr.hasNext()) {
1172             removeResource(itr.next());
1173         }
1174     }
1175
1176     public void removeCollectionResources(Set<CollectionResource> resources)
1177             throws SimulatorException {
1178         if (null == resources) {
1179             return;
1180         }
1181         Iterator<CollectionResource> itr = resources.iterator();
1182         while (itr.hasNext()) {
1183             removeResource(itr.next());
1184         }
1185     }
1186
1187     public void removeResource(Resource res) throws SimulatorException {
1188         // 1. Unregister the resource from the platform.
1189         SimulatorResource simRes = res.getSimulatorResource();
1190         try {
1191             simRes.stop();
1192         } catch (SimulatorException e) {
1193             Activator
1194                     .getDefault()
1195                     .getLogManager()
1196                     .log(Level.ERROR.ordinal(), new Date(),
1197                             Utility.getSimulatorErrorString(e, null));
1198             throw e;
1199         }
1200
1201         Set<CollectionResource> collectionMembership;
1202         Set<Device> deviceMembership;
1203
1204         if (res instanceof SingleResource) {
1205             collectionMembership = ((SingleResource) res)
1206                     .getCollectionMembership();
1207             deviceMembership = ((SingleResource) res).getDeviceMembership();
1208         } else {
1209             collectionMembership = ((CollectionResource) res).getMembership();
1210             deviceMembership = ((CollectionResource) res).getDeviceMembership();
1211         }
1212
1213         // 2. Delete from the collections to which this resource is a member.
1214         if (null != collectionMembership && !collectionMembership.isEmpty()) {
1215             removeResourceFromCollection(collectionMembership, res);
1216         }
1217
1218         // 3. Delete from the devices to which this resource is a member.
1219         if (null != deviceMembership && !deviceMembership.isEmpty()) {
1220             removeResourceFromDevice(deviceMembership, res);
1221         }
1222
1223         // 4. Delete this resource
1224         data.deleteResource(res);
1225     }
1226
1227     public void removeDevice(Device dev) {
1228         Set<Resource> childs = dev.getChildResources();
1229         if (null != childs && !childs.isEmpty()) {
1230             // 1. Remove the reference from all the children.
1231             Iterator<Resource> itr = childs.iterator();
1232             Resource res;
1233             while (itr.hasNext()) {
1234                 res = itr.next();
1235                 res.removeDeviceMembership(dev);
1236             }
1237         }
1238         // 2. Delete the device.
1239         data.deleteDevice(dev);
1240     }
1241
1242     public boolean isUriUnique(List<MetaProperty> properties) {
1243         if (null == properties) {
1244             return false;
1245         }
1246         MetaProperty prop;
1247         Iterator<MetaProperty> itr = properties.iterator();
1248         while (itr.hasNext()) {
1249             prop = itr.next();
1250             if (prop.getPropName().equals(Constants.RESOURCE_URI)) {
1251                 String uri = prop.getPropValue();
1252                 return !data.isResourceExist(uri);
1253             }
1254         }
1255         return false;
1256     }
1257
1258     public List<CollectionResource> getCollectionsForAddingToSingleResource(
1259             SingleResource resource) {
1260         List<CollectionResource> collectionResources = data
1261                 .getCollectionResources();
1262         if (null == collectionResources || collectionResources.isEmpty()) {
1263             return null;
1264         }
1265
1266         Set<CollectionResource> collectionMembership;
1267         collectionMembership = resource.getCollectionMembership();
1268         if (null == collectionMembership || collectionMembership.isEmpty()) {
1269             return collectionResources;
1270         }
1271
1272         if (collectionMembership.size() == collectionResources.size()) {
1273             return null;
1274         }
1275
1276         collectionResources.removeAll(collectionMembership);
1277
1278         // Sort the list
1279         Collections.sort(collectionResources,
1280                 Utility.collectionResourceComparator);
1281
1282         return collectionResources;
1283     }
1284
1285     public List<SingleResource> getSingleTypeResourcesForAddingToCollectionResource(
1286             CollectionResource colRes) {
1287         List<SingleResource> singleResources = data.getSingleResources();
1288         if (null == singleResources || singleResources.isEmpty()) {
1289             return null;
1290         }
1291
1292         Set<SingleResource> childs;
1293         childs = colRes.getSingleTypeChildResources();
1294         if (null == childs || childs.isEmpty()) {
1295             return singleResources;
1296         }
1297
1298         if (childs.size() == singleResources.size()) {
1299             return null;
1300         }
1301
1302         singleResources.removeAll(childs);
1303
1304         // Sort the list
1305         Collections.sort(singleResources, Utility.singleResourceComparator);
1306
1307         return singleResources;
1308     }
1309
1310     public List<SingleResource> getSingleTypeResourcesForAddingToDevice(
1311             Device dev) {
1312         List<SingleResource> singleResources = data.getSingleResources();
1313         if (null == singleResources || singleResources.isEmpty()) {
1314             return null;
1315         }
1316
1317         Set<SingleResource> childs;
1318         childs = dev.getSingleTypeChildResources();
1319         if (null == childs || childs.isEmpty()) {
1320             return singleResources;
1321         }
1322
1323         if (childs.size() == singleResources.size()) {
1324             return null;
1325         }
1326
1327         singleResources.removeAll(childs);
1328
1329         // Sort the list
1330         Collections.sort(singleResources, Utility.singleResourceComparator);
1331
1332         return singleResources;
1333     }
1334
1335     public List<CollectionResource> getCollectionTypeResourcesForAddingToCollectionResource(
1336             CollectionResource colRes) {
1337         List<CollectionResource> collectionResources = data
1338                 .getCollectionResources();
1339         if (null == collectionResources || collectionResources.isEmpty()) {
1340             return null;
1341         }
1342
1343         // Remove the colRes from the list
1344         collectionResources.remove(colRes);
1345
1346         Set<CollectionResource> childs;
1347         childs = colRes.getCollectionTypeChildResources();
1348         if (null == childs || childs.isEmpty()) {
1349             return collectionResources;
1350         }
1351
1352         if (childs.size() == collectionResources.size()) {
1353             return null;
1354         }
1355
1356         collectionResources.removeAll(childs);
1357
1358         // Sort the list
1359         Collections.sort(collectionResources,
1360                 Utility.collectionResourceComparator);
1361
1362         return collectionResources;
1363     }
1364
1365     public List<CollectionResource> getCollectionTypeResourcesForAddingToDevice(
1366             Device dev) {
1367         List<CollectionResource> collectionResources = data
1368                 .getCollectionResources();
1369         if (null == collectionResources || collectionResources.isEmpty()) {
1370             return null;
1371         }
1372
1373         Set<CollectionResource> childs;
1374         childs = dev.getCollectionTypeChildResources();
1375         if (null == childs || childs.isEmpty()) {
1376             return collectionResources;
1377         }
1378
1379         if (childs.size() == collectionResources.size()) {
1380             return null;
1381         }
1382
1383         collectionResources.removeAll(childs);
1384
1385         // Sort the list
1386         Collections.sort(collectionResources,
1387                 Utility.collectionResourceComparator);
1388
1389         return collectionResources;
1390     }
1391
1392     public List<Device> getDevicesForAddingToResource(Resource resource) {
1393         List<Device> devices = data.getDevices();
1394         if (null == devices || devices.isEmpty()) {
1395             return null;
1396         }
1397
1398         Set<Device> deviceMembership;
1399         if (resource instanceof SingleResource) {
1400             deviceMembership = ((SingleResource) resource)
1401                     .getDeviceMembership();
1402         } else {
1403             deviceMembership = ((CollectionResource) resource)
1404                     .getDeviceMembership();
1405         }
1406         if (null == deviceMembership || deviceMembership.isEmpty()) {
1407             return devices;
1408         }
1409
1410         if (devices.size() == deviceMembership.size()) {
1411             return null;
1412         }
1413
1414         devices.removeAll(deviceMembership);
1415
1416         // Sort the list
1417         Collections.sort(devices, Utility.deviceComparator);
1418
1419         return devices;
1420     }
1421
1422     public List<CollectionResource> getResourceReferences(
1423             SingleResource resource) {
1424         List<CollectionResource> resources = Utility
1425                 .getCollectionResourceListFromSet(resource
1426                         .getCollectionMembership());
1427         if (null == resources || resources.isEmpty()) {
1428             return null;
1429         }
1430
1431         Collections.sort(resources, Utility.collectionResourceComparator);
1432
1433         return resources;
1434     }
1435
1436     public List<Device> getDeviceReferences(Resource resource) {
1437         Set<Device> deviceMembership;
1438         if (resource instanceof SingleResource) {
1439             deviceMembership = ((SingleResource) resource)
1440                     .getDeviceMembership();
1441         } else {
1442             deviceMembership = ((CollectionResource) resource)
1443                     .getDeviceMembership();
1444         }
1445
1446         List<Device> devices = Utility.getDeviceListFromSet(deviceMembership);
1447         if (null == devices || devices.isEmpty()) {
1448             return null;
1449         }
1450
1451         Collections.sort(devices, Utility.deviceComparator);
1452
1453         return devices;
1454     }
1455
1456     public List<SingleResource> getSingleTypeChilds(CollectionResource colRes) {
1457         Set<SingleResource> childs = colRes.getSingleTypeChildResources();
1458         return Utility.getSingleResourceListFromSet(childs);
1459     }
1460
1461     public List<SingleResource> getSingleTypeChilds(Device dev) {
1462         Set<SingleResource> childs = dev.getSingleTypeChildResources();
1463         return Utility.getSingleResourceListFromSet(childs);
1464     }
1465
1466     public List<CollectionResource> getCollectionTypeChilds(
1467             CollectionResource colRes) {
1468         Set<CollectionResource> childs = colRes
1469                 .getCollectionTypeChildResources();
1470         return Utility.getCollectionResourceListFromSet(childs);
1471     }
1472
1473     public List<CollectionResource> getCollectionTypeChilds(Device dev) {
1474         Set<CollectionResource> childs = dev.getCollectionTypeChildResources();
1475         return Utility.getCollectionResourceListFromSet(childs);
1476     }
1477
1478     /*
1479      * public void deleteResourceByURI(String resourceURI) { if (null !=
1480      * resourceURI) { Resource resource =
1481      * getSimulatorResourceByURI(resourceURI); if (null != resource) { //
1482      * Unregister the resource from the platform deleteResource(resource);
1483      * 
1484      * // Delete from the local data structure deleteLocalResourceDetails(null,
1485      * resourceURI);
1486      * 
1487      * // Notify the UI listener for removing this resource // from UI //
1488      * resourceDeletedUINotification(); if (resource ==
1489      * getCurrentResourceInSelection()) { // Listeners might query the resource
1490      * being deleted // if exists. So set the currently selection to // null.
1491      * setCurrentResourceInSelection(null);
1492      * 
1493      * // Notify all observers for resource selection // change event //
1494      * resourceSelectionChangedUINotification(); } } } }
1495      * 
1496      * private SingleResource getSimulatorResourceByURI(String resourceURI) {
1497      * SingleResource resource = null; if (null != resourceURI) { synchronized
1498      * (resourceMap) { resource = resourceMap.get(resourceURI); } } return
1499      * resource; }
1500      * 
1501      * private void deleteResource(SingleResource resource) { if (null !=
1502      * resource) { SimulatorResourceServer resourceServerN = resource
1503      * .getResourceServer(); if (null != resourceServerN) { try {
1504      * SimulatorManager.deleteResource(resourceServerN); } catch
1505      * (SimulatorException e) { Activator .getDefault() .getLogManager()
1506      * .log(Level.ERROR.ordinal(), new Date(),
1507      * Utility.getSimulatorErrorString(e, null)); } } } }
1508      * 
1509      * public void deleteResourceByType(final String resourceType) {
1510      * System.out.println(resourceType + "to be deleted."); if (null !=
1511      * resourceType) { new Thread() {
1512      * 
1513      * @Override public void run() { // Unregister the resources from the
1514      * platform deleteResource(resourceType);
1515      * 
1516      * // Delete from the local data structure
1517      * deleteLocalResourceDetails(resourceType, null);
1518      * 
1519      * // Notify the UI listener for removing this resource from UI
1520      * resourceDeletedUINotification();
1521      * 
1522      * if (null != currentResourceInSelection &&
1523      * currentResourceInSelection.getResourceTypes() .contains(resourceType)) {
1524      * // Listeners might query the resource being deleted if // exists. So set
1525      * the currently selection to null. setCurrentResourceInSelection(null);
1526      * 
1527      * // Notify all observers for resource selection change // event
1528      * resourceSelectionChangedUINotification(null); } } }.start(); } }
1529      * 
1530      * private void deleteResource(String resourceType) { if (null !=
1531      * resourceType) { try { SimulatorManager.deleteResources(resourceType); }
1532      * catch (SimulatorException e) { Activator .getDefault() .getLogManager()
1533      * .log(Level.ERROR.ordinal(), new Date(),
1534      * Utility.getSimulatorErrorString(e, null)); } } }
1535      * 
1536      * public void deleteAllResources() { new Thread() {
1537      * 
1538      * @Override public void run() { // Unregister the resources from the
1539      * platform deleteResource();
1540      * 
1541      * // Delete from the local data structure deleteLocalResourceDetails(null,
1542      * null);
1543      * 
1544      * // Notify the UI listener for removing this resource from UI
1545      * resourceDeletedUINotification();
1546      * 
1547      * // Listeners might query the resource being deleted if exists. // So set
1548      * the currently selection to null. setCurrentResourceInSelection(null);
1549      * 
1550      * // Notify all observers for resource selection change event
1551      * resourceSelectionChangedUINotification(null); } }.start(); }
1552      * 
1553      * private void deleteResource() { try {
1554      * SimulatorManager.deleteResources(null); } catch (SimulatorException e) {
1555      * Activator .getDefault() .getLogManager() .log(Level.ERROR.ordinal(), new
1556      * Date(), Utility.getSimulatorErrorString(e, null)); } }
1557      * 
1558      * private void deleteLocalResourceDetails(String resourceType, String
1559      * resourceURI) { synchronized (resourceMap) { if (null == resourceType &&
1560      * null == resourceURI) { resourceMap.clear(); } else if (null !=
1561      * resourceType) { Set<String> uriSet = resourceMap.keySet(); if (null ==
1562      * uriSet) { return; } String uri; SingleResource simpleRes;
1563      * Iterator<String> uriItr = uriSet.iterator(); while (uriItr.hasNext()) {
1564      * uri = uriItr.next(); simpleRes = resourceMap.get(uri); if
1565      * (simpleRes.getResourceTypes().contains(resourceType)) { uriItr.remove();
1566      * } } } else { removeResourceFromMap(resourceURI); } } }
1567      * 
1568      * 
1569      * 
1570      * public Set<String> getResourceTypeList() { Set<String> types = null;
1571      * synchronized (resourceMap) { if (resourceMap.size() > 0) { types = new
1572      * TreeSet<String>(); Set<String> typeSet = resourceMap.keySet();
1573      * Iterator<String> typeItr = typeSet.iterator(); SingleResource resource;
1574      * while (typeItr.hasNext()) { resource = resourceMap.get(typeItr.next());
1575      * Set<String> subTypes = resource.getResourceTypes();
1576      * types.addAll(subTypes); } } } return types; }
1577      */
1578
1579     public void resourceSelectionChanged(final Resource selectedResource) {
1580         new Thread() {
1581             @Override
1582             public void run() {
1583
1584                 setCurrentDeviceInSelection(null);
1585
1586                 if (null != selectedResource) {
1587                     setCurrentResourceInSelection(selectedResource);
1588                 } else {
1589                     setCurrentResourceInSelection(null);
1590                 }
1591                 // Notify all observers for resource selection change event
1592                 UiListenerHandler.getInstance()
1593                         .resourceSelectionChangedUINotification(
1594                                 selectedResource);
1595             }
1596         }.start();
1597     }
1598
1599     public void deviceSelectionChanged(final Device selectedDevice) {
1600         new Thread() {
1601             @Override
1602             public void run() {
1603
1604                 setCurrentResourceInSelection(null);
1605
1606                 if (null != selectedDevice) {
1607                     setCurrentDeviceInSelection(selectedDevice);
1608                 } else {
1609                     setCurrentDeviceInSelection(null);
1610                 }
1611                 // Notify all observers for resource selection change event
1612                 UiListenerHandler.getInstance()
1613                         .deviceSelectionChangedUINotification(selectedDevice);
1614             }
1615         }.start();
1616     }
1617
1618     public List<MetaProperty> getMetaProperties(Resource resource) {
1619         if (null != resource) {
1620             String propName;
1621             String propValue;
1622
1623             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
1624
1625             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
1626                 propName = Constants.META_PROPERTIES[index];
1627                 if (propName.equals(Constants.RESOURCE_NAME)) {
1628                     propValue = resource.getResourceName();
1629                 } else if (propName.equals(Constants.RESOURCE_URI)) {
1630                     propValue = resource.getResourceURI();
1631                 } else if (propName.equals(Constants.RESOURCE_TYPE)) {
1632                     propValue = resource.getResourceTypes().toString();
1633                 } else {
1634                     propValue = null;
1635                 }
1636                 if (null != propValue) {
1637                     metaPropertyList.add(new MetaProperty(propName, propValue));
1638                 }
1639             }
1640             return metaPropertyList;
1641         }
1642         return null;
1643     }
1644
1645     public List<MetaProperty> getMetaProperties(Device dev) {
1646         if (null != dev) {
1647             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
1648             metaPropertyList.add(new MetaProperty(Constants.DEVICE_NAME, dev
1649                     .getDeviceName()));
1650             return metaPropertyList;
1651         }
1652         return null;
1653     }
1654
1655     public boolean startResource(Resource resource) throws SimulatorException {
1656         if (null == resource) {
1657             return false;
1658         }
1659         SimulatorResource server = resource.getSimulatorResource();
1660         if (null == server) {
1661             return false;
1662         }
1663         try {
1664             server.start();
1665             resource.setStarted(true);
1666         } catch (SimulatorException e) {
1667             Activator
1668                     .getDefault()
1669                     .getLogManager()
1670                     .log(Level.ERROR.ordinal(),
1671                             new Date(),
1672                             "There is an error while starting the resource.\n"
1673                                     + Utility.getSimulatorErrorString(e, null));
1674             throw e;
1675         }
1676         return true;
1677     }
1678
1679     public boolean stopResource(Resource resource) throws SimulatorException {
1680         if (null == resource) {
1681             return false;
1682         }
1683         SimulatorResource server = resource.getSimulatorResource();
1684         if (null == server) {
1685             return false;
1686         }
1687         try {
1688             server.stop();
1689             resource.setStarted(false);
1690         } catch (SimulatorException e) {
1691             Activator
1692                     .getDefault()
1693                     .getLogManager()
1694                     .log(Level.ERROR.ordinal(),
1695                             new Date(),
1696                             "There is an error while stopping the resource.\n"
1697                                     + Utility.getSimulatorErrorString(e, null));
1698             throw e;
1699         }
1700         return true;
1701     }
1702
1703     public boolean changeResourceName(Resource resource, String newName)
1704             throws SimulatorException {
1705         if (null == resource || null == newName) {
1706             return false;
1707         }
1708
1709         if (!stopResource(resource)) {
1710             return false;
1711         }
1712
1713         SimulatorResource server = resource.getSimulatorResource();
1714         try {
1715             server.setName(newName);
1716             resource.setResourceName(newName);
1717         } catch (SimulatorException e) {
1718             Activator
1719                     .getDefault()
1720                     .getLogManager()
1721                     .log(Level.ERROR.ordinal(),
1722                             new Date(),
1723                             "There is an error while changing the resource name.\n"
1724                                     + Utility.getSimulatorErrorString(e, null));
1725             throw e;
1726         }
1727
1728         if (!startResource(resource)) {
1729             return false;
1730         }
1731
1732         return true;
1733     }
1734
1735     public boolean changeDeviceName(Device dev, String newName) {
1736         if (null == dev || null == newName) {
1737             return false;
1738         }
1739         data.changeDeviceName(dev, dev.getDeviceName(), newName);
1740         return true;
1741     }
1742
1743     public boolean changeResourceURI(Resource resource, String newURI)
1744             throws SimulatorException {
1745         if (null == resource || null == newURI) {
1746             return false;
1747         }
1748
1749         if (!stopResource(resource)) {
1750             return false;
1751         }
1752
1753         String curURI = resource.getResourceURI();
1754         SimulatorResource server = resource.getSimulatorResource();
1755         try {
1756             server.setURI(newURI);
1757             data.changeResourceURI(resource, curURI, newURI);
1758         } catch (SimulatorException e) {
1759             Activator
1760                     .getDefault()
1761                     .getLogManager()
1762                     .log(Level.ERROR.ordinal(),
1763                             new Date(),
1764                             "There is an error while changing the resource URI.\n"
1765                                     + Utility.getSimulatorErrorString(e, null));
1766             throw e;
1767         }
1768
1769         if (!startResource(resource)) {
1770             return false;
1771         }
1772         return true;
1773     }
1774
1775     public boolean updateResourceProperties(Resource resource,
1776             List<MetaProperty> properties, boolean uriChanged,
1777             boolean nameChanged) throws SimulatorException {
1778         if (null == resource || null == properties) {
1779             return false;
1780         }
1781
1782         // Updating the properties
1783         Iterator<MetaProperty> itr = properties.iterator();
1784         MetaProperty property;
1785         String propName;
1786         String propValue;
1787         String resName = null;
1788         String resURI = null;
1789         while (itr.hasNext()) {
1790             property = itr.next();
1791             if (null == property) {
1792                 continue;
1793             }
1794             propName = property.getPropName();
1795             propValue = property.getPropValue();
1796             if (propName.equals(Constants.RESOURCE_NAME)) {
1797                 resName = propValue;
1798             } else if (propName.equals(Constants.RESOURCE_URI)) {
1799                 resURI = propValue;
1800             }
1801         }
1802
1803         if (nameChanged) {
1804             if (!changeResourceName(resource, resName)) {
1805                 return false;
1806             }
1807
1808             // Notify UI Listeners
1809             UiListenerHandler.getInstance().propertiesChangedUINotification(
1810                     Resource.class);
1811         }
1812
1813         if (uriChanged) {
1814             if (!changeResourceURI(resource, resURI)) {
1815                 return false;
1816             }
1817         }
1818
1819         return true;
1820     }
1821
1822     public boolean updateDeviceProperties(Device dev,
1823             List<MetaProperty> properties) {
1824         if (null == dev || null == properties) {
1825             return false;
1826         }
1827
1828         // Updating the properties
1829         Iterator<MetaProperty> itr = properties.iterator();
1830         MetaProperty property;
1831         String propName;
1832         String propValue;
1833         String devName = null;
1834         while (itr.hasNext()) {
1835             property = itr.next();
1836             if (null == property) {
1837                 continue;
1838             }
1839             propName = property.getPropName();
1840             propValue = property.getPropValue();
1841             if (propName.equals(Constants.DEVICE_NAME)) {
1842                 devName = propValue;
1843             }
1844         }
1845
1846         if (!changeDeviceName(dev, devName)) {
1847             return false;
1848         }
1849
1850         // Notify UI Listeners
1851         UiListenerHandler.getInstance().propertiesChangedUINotification(
1852                 Device.class);
1853
1854         return true;
1855     }
1856
1857     public List<LocalResourceAttribute> getAttributes(Resource resource) {
1858         List<LocalResourceAttribute> attList = null;
1859         if (null != resource) {
1860             Map<String, LocalResourceAttribute> attMap = resource
1861                     .getResourceAttributes();
1862             if (null != attMap && attMap.size() > 0) {
1863                 attList = new ArrayList<LocalResourceAttribute>();
1864                 Set<String> attNameSet = attMap.keySet();
1865                 String attName;
1866                 LocalResourceAttribute attribute;
1867                 Iterator<String> attNameItr = attNameSet.iterator();
1868                 while (attNameItr.hasNext()) {
1869                     attName = attNameItr.next();
1870                     attribute = attMap.get(attName);
1871                     if (null != attribute) {
1872                         attList.add(attribute);
1873                     }
1874                 }
1875             }
1876         }
1877         return attList;
1878     }
1879
1880     public List<SimulatorResourceAttribute> getAttributes(
1881             SimulatorResourceModel model) {
1882         List<SimulatorResourceAttribute> attList = null;
1883         if (null != model) {
1884             Map<String, SimulatorResourceAttribute> attMap = model
1885                     .getAttributes();
1886             if (null != attMap && attMap.size() > 0) {
1887                 attList = new ArrayList<SimulatorResourceAttribute>();
1888                 Set<String> attNameSet = attMap.keySet();
1889                 String attName;
1890                 SimulatorResourceAttribute attribute;
1891                 Iterator<String> attNameItr = attNameSet.iterator();
1892                 while (attNameItr.hasNext()) {
1893                     attName = attNameItr.next();
1894                     attribute = attMap.get(attName);
1895                     if (null != attribute) {
1896                         attList.add(attribute);
1897                     }
1898                 }
1899             }
1900         }
1901         return attList;
1902     }
1903
1904     public List<SRMItem> getIndexedAttributes(SimulatorResourceModel[] model) {
1905         List<SRMItem> indexedAttList = null;
1906         if (null != model && model.length > 0) {
1907             indexedAttList = new ArrayList<SRMItem>();
1908             int i = 0;
1909             for (SimulatorResourceModel m : model) {
1910                 indexedAttList.add(new SRMItem(i++, m));
1911             }
1912         }
1913         return indexedAttList;
1914     }
1915
1916     public void attributeValueUpdated(SingleResource resource,
1917             String attributeName, AttributeValue value) {
1918         if (null != resource && null != attributeName && null != value) {
1919             SimulatorSingleResource simRes = (SimulatorSingleResource) resource
1920                     .getSimulatorResource();
1921             if (null != simRes) {
1922                 try {
1923                     simRes.updateAttribute(attributeName, value);
1924                 } catch (SimulatorException e) {
1925                     Activator
1926                             .getDefault()
1927                             .getLogManager()
1928                             .log(Level.ERROR.ordinal(), new Date(),
1929                                     Utility.getSimulatorErrorString(e, null));
1930                 }
1931             }
1932         }
1933     }
1934
1935     /*
1936      * private ModelChangeNotificationType compareAndUpdateLocalAttributes(
1937      * Map<String, LocalResourceAttribute> resourceAttributeMapOld, Map<String,
1938      * LocalResourceAttribute> resourceAttributeMapNew,
1939      * Set<LocalResourceAttribute> valueChangeSet) { ModelChangeNotificationType
1940      * notificationType = ModelChangeNotificationType.NONE; if (null !=
1941      * resourceAttributeMapOld && null != resourceAttributeMapNew) { Set<String>
1942      * oldMapKeySet = resourceAttributeMapOld.keySet(); Iterator<String>
1943      * attributeMapOldItr = oldMapKeySet.iterator(); String attName;
1944      * LocalResourceAttribute attributeOld; LocalResourceAttribute attributeNew;
1945      * Object attValueOld; Object attValueNew; String oldValueStr; String
1946      * newValueStr; while (attributeMapOldItr.hasNext()) { attName =
1947      * attributeMapOldItr.next(); if
1948      * (resourceAttributeMapNew.containsKey(attName)) { attributeOld =
1949      * resourceAttributeMapOld.get(attName); attributeNew =
1950      * resourceAttributeMapNew.get(attName); // Copy the attribute value from
1951      * new to old if the value // has been changed // Comparing only the
1952      * attribute's value considering the // fact that only the value can be
1953      * changed if (null != attributeOld && null != attributeNew) { attValueOld =
1954      * attributeOld.getAttributeValue(); attValueNew =
1955      * attributeNew.getAttributeValue();
1956      * 
1957      * oldValueStr = String.valueOf(attValueOld); newValueStr =
1958      * String.valueOf(attValueNew);
1959      * 
1960      * if (null != oldValueStr && null != newValueStr) { if
1961      * (!oldValueStr.equals(newValueStr)) {
1962      * attributeOld.setAttributeValue(attValueNew); notificationType =
1963      * ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED;
1964      * valueChangeSet.add(attributeOld); } } }
1965      * resourceAttributeMapNew.remove(attName); } else { // Attribute doesn't
1966      * exist in the new model. Hence // removing it from the model.
1967      * resourceAttributeMapOld.remove(attName); notificationType =
1968      * ModelChangeNotificationType.ATTRIBUTE_REMOVED; } } // Check for new
1969      * attributes in the new model if (resourceAttributeMapNew.size() > 0) {
1970      * Set<String> remainingAttSet = resourceAttributeMapNew.keySet();
1971      * Iterator<String> remainingAttItr = remainingAttSet.iterator();
1972      * LocalResourceAttribute attribute; while (remainingAttItr.hasNext()) {
1973      * attName = remainingAttItr.next(); if (null != attName) { attribute =
1974      * resourceAttributeMapNew.get(attName); if (null != attribute) {
1975      * resourceAttributeMapOld.put(attName, attribute); } } } notificationType =
1976      * ModelChangeNotificationType.ATTRIBUTE_ADDED; } } return notificationType;
1977      * }
1978      */
1979
1980     // TODO: This method should get the status from the native layer.
1981     public boolean isResourceStarted(Resource resource) {
1982         if (null == resource) {
1983             return false;
1984         }
1985         return resource.isStarted();
1986     }
1987
1988     public boolean isPropertyValueInvalid(Resource resource,
1989             List<MetaProperty> properties, String propName) {
1990         if (null == resource || null == properties || null == propName) {
1991             return false;
1992         }
1993         boolean invalid = false;
1994         MetaProperty prop;
1995         Iterator<MetaProperty> itr = properties.iterator();
1996         while (itr.hasNext()) {
1997             prop = itr.next();
1998             if (prop.getPropName().equals(propName)) {
1999                 String value = prop.getPropValue();
2000                 if (null == value || value.trim().isEmpty()) {
2001                     invalid = true;
2002                 }
2003             }
2004         }
2005         return invalid;
2006     }
2007
2008     public boolean isPropertyValueInvalid(Device dev,
2009             List<MetaProperty> properties, String propName) {
2010         if (null == dev || null == properties || null == propName) {
2011             return false;
2012         }
2013         boolean invalid = false;
2014         MetaProperty prop;
2015         Iterator<MetaProperty> itr = properties.iterator();
2016         while (itr.hasNext()) {
2017             prop = itr.next();
2018             if (prop.getPropName().equals(propName)) {
2019                 String value = prop.getPropValue();
2020                 if (null == value || value.trim().isEmpty()) {
2021                     invalid = true;
2022                 }
2023             }
2024         }
2025         return invalid;
2026     }
2027
2028     public boolean isPropValueChanged(Resource resource,
2029             List<MetaProperty> properties, String propName) {
2030         if (null == resource || null == properties || null == propName) {
2031             return false;
2032         }
2033         boolean changed = false;
2034         MetaProperty prop;
2035         String oldValue;
2036         Iterator<MetaProperty> itr = properties.iterator();
2037         while (itr.hasNext()) {
2038             prop = itr.next();
2039             if (prop.getPropName().equals(propName)) {
2040                 oldValue = getPropertyValueFromResource(resource, propName);
2041                 if (null != oldValue && !prop.getPropValue().equals(oldValue)) {
2042                     changed = true;
2043                 }
2044                 break;
2045             }
2046         }
2047         return changed;
2048     }
2049
2050     public boolean isPropValueChanged(Device dev,
2051             List<MetaProperty> properties, String propName) {
2052         if (null == dev || null == properties || null == propName) {
2053             return false;
2054         }
2055         boolean changed = false;
2056         MetaProperty prop;
2057         String oldValue;
2058         Iterator<MetaProperty> itr = properties.iterator();
2059         while (itr.hasNext()) {
2060             prop = itr.next();
2061             if (prop.getPropName().equals(propName)) {
2062                 oldValue = dev.getDeviceName();
2063                 if (null != oldValue && !prop.getPropValue().equals(oldValue)) {
2064                     changed = true;
2065                 }
2066                 break;
2067             }
2068         }
2069         return changed;
2070     }
2071
2072     private String getPropertyValueFromResource(Resource resource,
2073             String propName) {
2074         if (null == resource || null == propName) {
2075             return null;
2076         }
2077         if (propName.equals(Constants.RESOURCE_URI)) {
2078             return resource.getResourceURI();
2079         } else if (propName.equals(Constants.RESOURCE_NAME)) {
2080             return resource.getResourceName();
2081         } else if (propName.equals(Constants.RESOURCE_TYPE)) {
2082             return resource.getResourceTypes().toString();
2083         } else {
2084             return null;
2085         }
2086     }
2087
2088     public boolean isURIChanged(Resource resource, List<MetaProperty> properties) {
2089         if (null == resource || null == properties) {
2090             return false;
2091         }
2092         boolean changed = false;
2093         MetaProperty prop;
2094         Iterator<MetaProperty> itr = properties.iterator();
2095         while (itr.hasNext()) {
2096             prop = itr.next();
2097             if (prop.getPropName().equals(Constants.RESOURCE_URI)) {
2098                 if (!prop.getPropValue().equals(resource.getResourceURI())) {
2099                     changed = true;
2100                 }
2101                 break;
2102             }
2103         }
2104         return changed;
2105     }
2106
2107     public boolean startResource(SingleResource resource) {
2108         if (null == resource || resource.isStarted()) {
2109             return false;
2110         }
2111         boolean result;
2112         SimulatorResource server = resource.getSimulatorResource();
2113         if (null == server) {
2114             result = false;
2115         } else {
2116             try {
2117                 server.start();
2118                 resource.setStarted(true);
2119                 result = true;
2120             } catch (SimulatorException e) {
2121                 Activator
2122                         .getDefault()
2123                         .getLogManager()
2124                         .log(Level.ERROR.ordinal(), new Date(),
2125                                 Utility.getSimulatorErrorString(e, null));
2126                 result = false;
2127             }
2128         }
2129         return result;
2130     }
2131
2132     public boolean stopResource(SingleResource resource) {
2133         if (null == resource || !resource.isStarted()) {
2134             return false;
2135         }
2136         boolean result;
2137         SimulatorResource server = resource.getSimulatorResource();
2138         if (null == server) {
2139             result = false;
2140         } else {
2141             try {
2142                 server.stop();
2143                 resource.setStarted(false);
2144                 result = true;
2145             } catch (SimulatorException e) {
2146                 Activator
2147                         .getDefault()
2148                         .getLogManager()
2149                         .log(Level.ERROR.ordinal(), new Date(),
2150                                 Utility.getSimulatorErrorString(e, null));
2151                 result = false;
2152             }
2153         }
2154         return result;
2155     }
2156
2157     public boolean isAttHasRangeOrAllowedValues(SimulatorResourceAttribute att) {
2158         if (null == att) {
2159             return false;
2160         }
2161         AttributeProperty prop = att.property();
2162         if (null == prop) {
2163             return false;
2164         }
2165         Type attProp = prop.type();
2166         if (attProp == Type.UNKNOWN) {
2167             return false;
2168         }
2169         return true;
2170     }
2171
2172     public int startAutomation(SingleResource resource,
2173             LocalResourceAttribute attribute, AutoUpdateType autoType,
2174             int autoUpdateInterval) {
2175         int autoId = -1;
2176         if (null != resource && null != attribute) {
2177             SimulatorSingleResource server = (SimulatorSingleResource) resource
2178                     .getSimulatorResource();
2179             if (null != server) {
2180                 String attrName = attribute.getResourceAttributeRef().name();
2181                 try {
2182                     autoId = server.startAttributeUpdation(attrName, autoType,
2183                             autoUpdateInterval, automationListener);
2184                 } catch (SimulatorException e) {
2185                     Activator
2186                             .getDefault()
2187                             .getLogManager()
2188                             .log(Level.ERROR.ordinal(),
2189                                     new Date(),
2190                                     "[" + e.getClass().getSimpleName() + "]"
2191                                             + e.code().toString() + "-"
2192                                             + e.message());
2193                     return -1;
2194                 }
2195                 if (-1 != autoId) {
2196                     attribute.setAutomationId(autoId);
2197                     attribute.setAutomationType(autoType);
2198                     attribute.setAutomationUpdateInterval(autoUpdateInterval);
2199                     attribute.setAutomationInProgress(true);
2200                     resource.setAttributeAutomationInProgress(true);
2201                 } else {
2202                     attribute.setAutomationInProgress(false);
2203                 }
2204             }
2205         }
2206         return autoId;
2207     }
2208
2209     public void stopAutomation(SingleResource resource,
2210             LocalResourceAttribute att, int autoId) {
2211         if (null != resource) {
2212             SimulatorSingleResource server = (SimulatorSingleResource) resource
2213                     .getSimulatorResource();
2214             if (null != server) {
2215                 try {
2216                     server.stopUpdation(autoId);
2217                 } catch (SimulatorException e) {
2218                     Activator
2219                             .getDefault()
2220                             .getLogManager()
2221                             .log(Level.ERROR.ordinal(),
2222                                     new Date(),
2223                                     "[" + e.getClass().getSimpleName() + "]"
2224                                             + e.code().toString() + "-"
2225                                             + e.message());
2226                     return;
2227                 }
2228                 // Change the automation status
2229                 att.setAutomationInProgress(false);
2230                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
2231             }
2232         }
2233     }
2234
2235     public boolean startResourceAutomationUIRequest(AutoUpdateType autoType,
2236             int autoUpdateInterval, final SingleResource resource) {
2237         if (null == resource) {
2238             return false;
2239         }
2240         boolean status = false;
2241         changeResourceLevelAutomationStatus(resource, true);
2242         // Invoke the native automation method
2243         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
2244                 .getSimulatorResource();
2245         if (null != resourceServer) {
2246             int autoId = -1;
2247             try {
2248                 autoId = resourceServer.startResourceUpdation(autoType,
2249                         autoUpdateInterval, automationListener);
2250             } catch (SimulatorException e) {
2251                 Activator
2252                         .getDefault()
2253                         .getLogManager()
2254                         .log(Level.ERROR.ordinal(), new Date(),
2255                                 Utility.getSimulatorErrorString(e, null));
2256                 autoId = -1;
2257             }
2258             if (-1 == autoId) {
2259                 // Automation request failed and hence status is being
2260                 // rolled back
2261                 changeResourceLevelAutomationStatus(resource, false);
2262             } else {
2263                 // Automation request accepted.
2264                 resource.setAutomationId(autoId);
2265
2266                 // Notify the UI listeners in a different thread.
2267                 Thread notifyThread = new Thread() {
2268                     public void run() {
2269                         UiListenerHandler.getInstance()
2270                                 .resourceAutomationStartedUINotification(
2271                                         resource);
2272                     };
2273                 };
2274                 notifyThread.setPriority(Thread.MAX_PRIORITY);
2275                 notifyThread.start();
2276
2277                 status = true;
2278             }
2279         }
2280         return status;
2281     }
2282
2283     public boolean stopResourceAutomationUIRequest(final SingleResource resource) {
2284         if (null == resource) {
2285             return false;
2286         }
2287         final int autoId = resource.getAutomationId();
2288         if (-1 == autoId) {
2289             return false;
2290         }
2291         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
2292                 .getSimulatorResource();
2293         if (null == resourceServer) {
2294             return false;
2295         }
2296         // Call native method
2297         try {
2298             resourceServer.stopUpdation(autoId);
2299         } catch (SimulatorException e) {
2300             Activator
2301                     .getDefault()
2302                     .getLogManager()
2303                     .log(Level.ERROR.ordinal(), new Date(),
2304                             Utility.getSimulatorErrorString(e, null));
2305             return false;
2306         }
2307
2308         // Notify the UI Listeners. Invoke the automation complete callback.
2309         Thread stopThread = new Thread() {
2310             public void run() {
2311                 automationListener.onUpdateComplete(resource.getResourceURI(),
2312                         autoId);
2313             }
2314         };
2315         stopThread.start();
2316         return true;
2317     }
2318
2319     private boolean isAnyAttributeInAutomation(SingleResource resource) {
2320         if (null == resource) {
2321             return false;
2322         }
2323         Map<String, LocalResourceAttribute> attMap = resource
2324                 .getResourceAttributes();
2325         if (null == attMap) {
2326             return false;
2327         }
2328         boolean status = false;
2329         Set<String> keySet = attMap.keySet();
2330         Iterator<String> attItr = keySet.iterator();
2331         while (attItr.hasNext()) {
2332             LocalResourceAttribute attribute = attMap.get(attItr.next());
2333             if (attribute.isAutomationInProgress()) {
2334                 status = true;
2335                 break;
2336             }
2337         }
2338         return status;
2339     }
2340
2341     // Changes the automation state of the resource and its attributes
2342     private void changeResourceLevelAutomationStatus(SingleResource resource,
2343             boolean status) {
2344
2345         Map<String, LocalResourceAttribute> attributeMap = resource
2346                 .getResourceAttributes();
2347         if (null != attributeMap) {
2348             Set<String> attrNameSet = attributeMap.keySet();
2349             Iterator<String> attrNameItr = attrNameSet.iterator();
2350             String attrName;
2351             LocalResourceAttribute attribute;
2352             while (attrNameItr.hasNext()) {
2353                 attrName = attrNameItr.next();
2354                 attribute = attributeMap.get(attrName);
2355                 if (null != attribute) {
2356                     attribute.setAutomationInProgress(status);
2357                 }
2358             }
2359         }
2360         resource.setResourceAutomationInProgress(status);
2361     }
2362
2363     private LocalResourceAttribute getAttributeWithGivenAutomationId(
2364             SingleResource resource, int automationId) {
2365         LocalResourceAttribute targetAttribute = null;
2366         if (null != resource) {
2367             Map<String, LocalResourceAttribute> attributeMap = resource
2368                     .getResourceAttributes();
2369             if (null != attributeMap) {
2370                 Set<String> attNameSet = attributeMap.keySet();
2371                 Iterator<String> attNameItr = attNameSet.iterator();
2372                 String attName;
2373                 LocalResourceAttribute attribute;
2374                 while (attNameItr.hasNext()) {
2375                     attName = attNameItr.next();
2376                     if (null != attName) {
2377                         attribute = attributeMap.get(attName);
2378                         if (null != attribute) {
2379                             if (attribute.isAutomationInProgress()
2380                                     && (attribute.getAutomationId() == automationId)) {
2381                                 targetAttribute = attribute;
2382                                 break;
2383                             }
2384                         }
2385                     }
2386                 }
2387             }
2388         }
2389         return targetAttribute;
2390     }
2391
2392     public boolean isResourceAutomationStarted(SingleResource resource) {
2393         boolean status = false;
2394         if (null != resource) {
2395             status = resource.isResourceAutomationInProgress();
2396         }
2397         return status;
2398     }
2399
2400     public boolean isAttributeAutomationStarted(SingleResource resource) {
2401         if (null == resource) {
2402             return false;
2403         }
2404         return resource.isAttributeAutomationInProgress();
2405     }
2406
2407     public LocalResourceAttribute getAttributeByResourceURI(
2408             SingleResource resource, String attName) {
2409         if (null == resource || null == attName) {
2410             return null;
2411         }
2412         Map<String, LocalResourceAttribute> attMap = resource
2413                 .getResourceAttributes();
2414         if (null == attMap) {
2415             return null;
2416         }
2417         return attMap.get(attName);
2418     }
2419
2420     public void notifyObserverRequest(Resource resource, int observerId) {
2421         if (null == resource) {
2422             return;
2423         }
2424         SimulatorResource simulatorResource = resource.getSimulatorResource();
2425         if (null == simulatorResource) {
2426             return;
2427         }
2428         try {
2429             simulatorResource.notifyObserver(observerId);
2430         } catch (SimulatorException e) {
2431             Activator
2432                     .getDefault()
2433                     .getLogManager()
2434                     .log(Level.ERROR.ordinal(), new Date(),
2435                             Utility.getSimulatorErrorString(e, null));
2436         }
2437     }
2438
2439     public void shutdown() {
2440         threadHandle.interrupt();
2441     }
2442
2443     public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
2444         if (null == att) {
2445             return null;
2446         }
2447
2448         AttributeValue val = att.value();
2449         if (null == val) {
2450             return null;
2451         }
2452
2453         TypeInfo type = val.typeInfo();
2454
2455         AttributeProperty prop = att.property();
2456         if (null == prop) {
2457             return null;
2458         }
2459
2460         List<String> values = new ArrayList<String>();
2461
2462         Type valuesType = prop.type();
2463
2464         if (valuesType == Type.UNKNOWN) {
2465             // Adding the default value
2466             values.add(Utility.getAttributeValueAsString(val));
2467             return values;
2468         }
2469
2470         if (type.mType != ValueType.RESOURCEMODEL) {
2471             if (type.mType == ValueType.ARRAY) {
2472                 if (type.mDepth == 1) {
2473                     AttributeProperty childProp = prop.getChildProperty();
2474                     if (null != childProp) {
2475                         valuesType = childProp.type();
2476                         if (valuesType == Type.RANGE) {
2477                             List<String> list = getRangeForPrimitiveNonArrayAttributes(
2478                                     childProp, type.mBaseType);
2479                             if (null != list) {
2480                                 values.addAll(list);
2481                             }
2482                         } else if (valuesType == Type.VALUESET) {
2483                             List<String> list = getAllowedValuesForPrimitiveNonArrayAttributes(
2484                                     childProp.valueSet(), type.mBaseType);
2485                             if (null != list) {
2486                                 values.addAll(list);
2487                             }
2488                         }
2489                     }
2490                 }
2491             } else {
2492                 if (valuesType == Type.RANGE) {
2493                     List<String> list = getRangeForPrimitiveNonArrayAttributes(
2494                             prop, type.mType);
2495                     if (null != list) {
2496                         values.addAll(list);
2497                     }
2498                 } else if (valuesType == Type.VALUESET) {
2499                     List<String> list = getAllowedValuesForPrimitiveNonArrayAttributes(
2500                             prop.valueSet(), type.mType);
2501                     if (null != list) {
2502                         values.addAll(list);
2503                     }
2504                 }
2505             }
2506         }
2507
2508         return values;
2509     }
2510
2511     public List<String> getRangeForPrimitiveNonArrayAttributes(
2512             AttributeProperty prop, ValueType type) {
2513         if (null == prop) {
2514             return null;
2515         }
2516
2517         if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) {
2518             return null;
2519         }
2520
2521         List<String> values = new ArrayList<String>();
2522         switch (type) {
2523             case INTEGER:
2524                 int min = (int) prop.min();
2525                 int max = (int) prop.max();
2526                 for (int iVal = min; iVal <= max; iVal++) {
2527                     values.add(String.valueOf(iVal));
2528                 }
2529                 break;
2530             case DOUBLE:
2531                 double minD = (double) prop.min();
2532                 double maxD = (double) prop.max();
2533                 for (double iVal = minD; iVal <= maxD; iVal = iVal + 1.0) {
2534                     values.add(String.valueOf(iVal));
2535                 }
2536                 break;
2537             default:
2538         }
2539         return values;
2540     }
2541
2542     public List<String> getAllowedValuesForPrimitiveNonArrayAttributes(
2543             AttributeValue[] attValues, ValueType type) {
2544         if (null == attValues || attValues.length < 1) {
2545             return null;
2546         }
2547
2548         if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) {
2549             return null;
2550         }
2551
2552         Object obj;
2553         List<String> values = new ArrayList<String>();
2554         for (AttributeValue val : attValues) {
2555             if (null == val) {
2556                 continue;
2557             }
2558             obj = val.get();
2559             if (null == obj) {
2560                 continue;
2561             }
2562             values.add(String.valueOf(obj));
2563         }
2564         return values;
2565     }
2566 }