bcadd4a7f9aea69115dee3b5e0f78e31f2f4a2f4
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ClientControllerPlugin / src / oic / simulator / clientcontroller / 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.clientcontroller.manager;
18
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.Vector;
30
31 import oic.simulator.clientcontroller.Activator;
32 import oic.simulator.clientcontroller.listener.IConfigurationUpload;
33 import oic.simulator.clientcontroller.listener.IDevicePlatformInfoUIListener;
34 import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
35 import oic.simulator.clientcontroller.listener.IGetUIListener;
36 import oic.simulator.clientcontroller.listener.IObserveUIListener;
37 import oic.simulator.clientcontroller.listener.IPostUIListener;
38 import oic.simulator.clientcontroller.listener.IPutUIListener;
39 import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
40 import oic.simulator.clientcontroller.listener.IVerificationUIListener;
41 import oic.simulator.clientcontroller.remoteresource.MetaProperty;
42 import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
43 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
44 import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
45 import oic.simulator.clientcontroller.utils.AttributeValueBuilder;
46 import oic.simulator.clientcontroller.utils.Constants;
47 import oic.simulator.clientcontroller.utils.Utility;
48
49 import org.oic.simulator.AttributeProperty;
50 import org.oic.simulator.AttributeProperty.Type;
51 import org.oic.simulator.AttributeValue;
52 import org.oic.simulator.AttributeValue.TypeInfo;
53 import org.oic.simulator.AttributeValue.ValueType;
54 import org.oic.simulator.DeviceInfo;
55 import org.oic.simulator.DeviceListener;
56 import org.oic.simulator.ILogger.Level;
57 import org.oic.simulator.PlatformInfo;
58 import org.oic.simulator.PlatformListener;
59 import org.oic.simulator.SimulatorException;
60 import org.oic.simulator.SimulatorManager;
61 import org.oic.simulator.SimulatorResourceAttribute;
62 import org.oic.simulator.SimulatorResourceModel;
63 import org.oic.simulator.SimulatorResult;
64 import org.oic.simulator.client.FindResourceListener;
65 import org.oic.simulator.client.SimulatorRemoteResource;
66 import org.oic.simulator.client.SimulatorRemoteResource.GetResponseListener;
67 import org.oic.simulator.client.SimulatorRemoteResource.ObserveNotificationListener;
68 import org.oic.simulator.client.SimulatorRemoteResource.PostResponseListener;
69 import org.oic.simulator.client.SimulatorRemoteResource.PutResponseListener;
70 import org.oic.simulator.client.SimulatorRemoteResource.VerificationListener;
71 import org.oic.simulator.client.SimulatorRemoteResource.VerificationType;
72
73 /**
74  * This class acts as an interface between the simulator java SDK and the
75  * various UI modules. It maintains all the details of resources and provides
76  * other UI modules with the information required. It also handles responses for
77  * find, GET, PUT, POST, Observe and automatic verification operations from
78  * native layer and propagates those events to the registered UI listeners.
79  */
80 public class ResourceManager {
81
82     private Set<String>                               lastKnownSearchTypes;
83
84     private RemoteResource                            currentResourceInSelection;
85
86     private FindResourceListener                      findResourceListener;
87     private GetResponseListener                       getListener;
88     private PutResponseListener                       putListener;
89     private PostResponseListener                      postListener;
90     private ObserveNotificationListener               observeListener;
91     private VerificationListener                      verifyListener;
92     private DeviceListener                            deviceListener;
93     private PlatformListener                          platformListener;
94
95     private ResponseSynchronizerThread                synchronizerThread;
96
97     private Thread                                    threadHandle;
98
99     private List<IFindResourceUIListener>             findResourceUIListeners;
100     private List<IResourceSelectionChangedUIListener> resourceSelectionChangedUIListeners;
101     private List<IGetUIListener>                      getUIListeners;
102     private List<IPutUIListener>                      putUIListeners;
103     private List<IPostUIListener>                     postUIListeners;
104     private List<IObserveUIListener>                  observeUIListeners;
105     private List<IVerificationUIListener>             verificationUIListeners;
106     private List<IConfigurationUpload>                configUploadUIListeners;
107     private List<IDevicePlatformInfoUIListener>       devicePlatformInfoUIListeners;
108
109     // Map with Server ID as key and the complete object as the value
110     private Map<String, RemoteResource>               resourceMap;
111     private List<RemoteResource>                      favoriteResources;
112     // Maintaining a list of resource URIs for favorite resources feature.
113     private List<String>                              favoriteURIList;
114
115     // Maintaining a list of observed resource URIs.
116     private List<String>                              observedResourceURIList;
117
118     private DeviceInfo                                devInfo;
119     private PlatformInfo                              platInfo;
120
121     public ResourceManager() {
122         resourceMap = new HashMap<String, RemoteResource>();
123         favoriteResources = new ArrayList<RemoteResource>();
124         favoriteURIList = new ArrayList<String>();
125         observedResourceURIList = new ArrayList<String>();
126         findResourceUIListeners = new ArrayList<IFindResourceUIListener>();
127         resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
128         getUIListeners = new ArrayList<IGetUIListener>();
129         putUIListeners = new ArrayList<IPutUIListener>();
130         postUIListeners = new ArrayList<IPostUIListener>();
131         observeUIListeners = new ArrayList<IObserveUIListener>();
132         verificationUIListeners = new ArrayList<IVerificationUIListener>();
133         configUploadUIListeners = new ArrayList<IConfigurationUpload>();
134         devicePlatformInfoUIListeners = new ArrayList<IDevicePlatformInfoUIListener>();
135
136         findResourceListener = new FindResourceListener() {
137
138             @Override
139             public void onResourceFound(final SimulatorRemoteResource resourceN) {
140                 synchronizerThread.addToQueue(new Runnable() {
141                     @Override
142                     public void run() {
143                         if (null == resourceN) {
144                             return;
145                         }
146
147                         // If id is not available, then it cannot be added to
148                         // the local map as null value should not be allowed as
149                         // key.
150                         String uid = resourceN.getId();
151                         if (null == uid) {
152                             return;
153                         }
154
155                         // If resource already exist, then ignore it.
156                         boolean exist = isUidExist(uid);
157                         if (exist) {
158                             return;
159                         }
160
161                         // Fetch the resource data
162                         // RemoteResource resource =
163                         // fetchResourceDetails(resourceN);
164                         RemoteResource resource = new RemoteResource();
165                         resource.setRemoteResourceRef(resourceN);
166
167                         String uri = resourceN.getURI();
168                         if (null != uri && uri.trim().length() > 0) {
169                             // Add resource to favorite list if it was in
170                             // favorites list during find/refresh operation.
171                             if (favoriteURIList.contains(uri)) {
172                                 addResourcetoFavorites(resource);
173                             }
174                             // Add resource to observed resources list if it was
175                             // in observe list during find/refresh operation.
176                             if (observedResourceURIList.contains(uri)) {
177                                 sendObserveRequest(resource);
178                             }
179                         } else {
180                             Activator
181                                     .getDefault()
182                                     .getLogManager()
183                                     .log(Level.INFO.ordinal(), new Date(),
184                                             "Found a resource without URI. Ignoring it.");
185                             return;
186                         }
187
188                         // Add the resource in local data structure
189                         addResourceDetails(resource);
190
191                         // Notify the UI listener
192                         newResourceFoundNotification(resource);
193
194                         Activator
195                                 .getDefault()
196                                 .getLogManager()
197                                 .log(Level.INFO.ordinal(),
198                                         new Date(),
199                                         "Resource Found [" + resourceN.getURI()
200                                                 + "].");
201
202                         // Send an initial GET request to get the resource
203                         // attributes
204                         try {
205                             resourceN.get(null, getListener);
206                         } catch (SimulatorException e) {
207                             Activator
208                                     .getDefault()
209                                     .getLogManager()
210                                     .log(Level.ERROR.ordinal(),
211                                             new Date(),
212                                             Utility.getSimulatorErrorString(e,
213                                                     null));
214                         }
215
216                         // Get the device and platform information
217                         try {
218                             SimulatorManager.findDevices(deviceListener);
219                             SimulatorManager
220                                     .getPlatformInformation(platformListener);
221                         } catch (SimulatorException e) {
222                             Activator
223                                     .getDefault()
224                                     .getLogManager()
225                                     .log(Level.ERROR.ordinal(),
226                                             new Date(),
227                                             Utility.getSimulatorErrorString(e,
228                                                     null));
229                         }
230                     }
231                 });
232             }
233         };
234
235         // TODO: Listeners for device and platform information.
236         deviceListener = new DeviceListener() {
237
238             @Override
239             public void onDeviceFound(final DeviceInfo deviceInfo) {
240                 if (null == deviceInfo) {
241                     return;
242                 }
243                 synchronizerThread.addToQueue(new Runnable() {
244                     @Override
245                     public void run() {
246                         setDeviceInfo(deviceInfo);
247
248                         // Notify UI listeners
249                         deviceInfoReceivedNotification();
250                     }
251                 });
252             }
253         };
254
255         platformListener = new PlatformListener() {
256
257             @Override
258             public void onPlatformFound(final PlatformInfo platformInfo) {
259                 if (null == platformInfo) {
260                     return;
261                 }
262                 synchronizerThread.addToQueue(new Runnable() {
263                     @Override
264                     public void run() {
265                         setPlatformInfo(platformInfo);
266
267                         // Notify UI listeners
268                         platformInfoReceivedNotification();
269                     }
270                 });
271             }
272         };
273
274         getListener = new GetResponseListener() {
275             @Override
276             public void onGetResponse(final String uid,
277                     final SimulatorResult result,
278                     final SimulatorResourceModel resourceModelN) {
279                 System.out.println(result);
280                 if (result != SimulatorResult.SIMULATOR_OK) {
281                     Activator
282                             .getDefault()
283                             .getLogManager()
284                             .log(Level.ERROR.ordinal(),
285                                     new Date(),
286                                     "["
287                                             + result.toString()
288                                             + "] Received error response for GET request.");
289                     return;
290                 }
291                 synchronizerThread.addToQueue(new Runnable() {
292                     @Override
293                     public void run() {
294                         // Handling the response which includes retrieving the
295                         // attributes and updating the local model.
296                         RemoteResource resource = handleResponse(uid,
297                                 resourceModelN);
298                         if (null != resource) {
299                             // Notify the UI listeners
300                             getCompleteNotification(resource);
301                         }
302                     }
303                 });
304             }
305         };
306
307         putListener = new PutResponseListener() {
308
309             @Override
310             public void onPutResponse(final String uid,
311                     final SimulatorResult result,
312                     final SimulatorResourceModel resourceModelN) {
313                 if (result != SimulatorResult.SIMULATOR_OK) {
314                     Activator
315                             .getDefault()
316                             .getLogManager()
317                             .log(Level.ERROR.ordinal(),
318                                     new Date(),
319                                     "["
320                                             + result.toString()
321                                             + "] Received error response for PUT request.");
322                     return;
323                 }
324                 synchronizerThread.addToQueue(new Thread() {
325                     @Override
326                     public void run() {
327                         // Handling the response which includes retrieving the
328                         // attributes and updating the local model.
329                         RemoteResource resource = handleResponse(uid,
330                                 resourceModelN);
331                         if (null != resource) {
332                             // Notify the UI listeners
333                             putCompleteNotification(resource);
334                         }
335                     }
336                 });
337             }
338         };
339
340         postListener = new PostResponseListener() {
341             @Override
342             public void onPostResponse(final String uid,
343                     final SimulatorResult result,
344                     final SimulatorResourceModel resourceModelN) {
345                 if (result != SimulatorResult.SIMULATOR_OK) {
346                     Activator
347                             .getDefault()
348                             .getLogManager()
349                             .log(Level.ERROR.ordinal(),
350                                     new Date(),
351                                     "["
352                                             + result.toString()
353                                             + "] Received error response for POST request.");
354                     return;
355                 }
356                 synchronizerThread.addToQueue(new Runnable() {
357                     @Override
358                     public void run() {
359                         // Handling the response which includes retrieving the
360                         // attributes and updating the local model.
361                         RemoteResource resource = handleResponse(uid,
362                                 resourceModelN);
363                         if (null != resource) {
364                             // Notify the UI listeners
365                             postCompleteNotification(resource);
366                         }
367                     }
368                 });
369             }
370         };
371
372         observeListener = new ObserveNotificationListener() {
373
374             @Override
375             public void onObserveNotification(final String uid,
376                     final SimulatorResourceModel resourceModelN, final int seq) {
377                 synchronizerThread.addToQueue(new Runnable() {
378                     @Override
379                     public void run() {
380                         // Handling the response which includes retrieving the
381                         // attributes and updating the local model.
382                         RemoteResource resource = handleResponse(uid,
383                                 resourceModelN);
384                         if (null != resource) {
385                             // Notify the UI listeners
386                             observeCompleteNotification(resource);
387                         }
388                     }
389                 });
390             }
391         };
392
393         verifyListener = new VerificationListener() {
394
395             @Override
396             public void onVerificationStarted(final String uid, final int autoId) {
397                 synchronizerThread.addToQueue(new Runnable() {
398                     @Override
399                     public void run() {
400                         RemoteResource resource = getResource(uid);
401                         if (null == resource) {
402                             return;
403                         }
404                         // Update the automation status.
405                         resource.updateAutomationStatus(autoId, true);
406
407                         int autoType = resource.getAutomationtype(autoId);
408
409                         // Notify the listeners.
410                         verificationStartedNotification(resource, autoType);
411                     }
412                 });
413             }
414
415             @Override
416             public void onVerificationCompleted(final String uid,
417                     final int autoId) {
418                 synchronizerThread.addToQueue(new Runnable() {
419                     @Override
420                     public void run() {
421                         RemoteResource resource = getResource(uid);
422                         if (null == resource) {
423                             return;
424                         }
425                         // Update the automation status.
426                         resource.updateAutomationStatus(autoId, false);
427
428                         int autoType = resource.getAutomationtype(autoId);
429
430                         // Notify the listeners.
431                         verificationCompletedNotification(resource, autoType);
432                     }
433                 });
434             }
435
436             @Override
437             public void onVerificationAborted(final String uid, final int autoId) {
438                 synchronizerThread.addToQueue(new Runnable() {
439                     @Override
440                     public void run() {
441                         RemoteResource resource = getResource(uid);
442                         if (null == resource) {
443                             return;
444                         }
445                         // Update the automation status.
446                         resource.updateAutomationStatus(autoId, false);
447
448                         int autoType = resource.getAutomationtype(autoId);
449
450                         // Notify the listeners.
451                         verificationAbortedNotification(resource, autoType);
452                     }
453                 });
454             }
455         };
456
457         synchronizerThread = new ResponseSynchronizerThread();
458         threadHandle = new Thread(synchronizerThread);
459         threadHandle.setName("Simulator Client Controller Event Queue");
460         threadHandle.start();
461     }
462
463     private RemoteResource handleResponse(String uid,
464             SimulatorResourceModel resourceModelN) {
465         if (null == uid || null == resourceModelN) {
466             return null;
467         }
468
469         // Update the local model
470         RemoteResource resource;
471         resource = getResource(uid);
472         if (null == resource) {
473             return null;
474         }
475
476         resource.setResourceModelRef(resourceModelN);
477         Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModelN);
478         if (resource.isConfigUploaded()) {
479             updateResourceAttributesFromResponse(resource, attributeMap);
480         } else {
481             resource.setResourceAttributesMap(attributeMap);
482         }
483         // TODO: Printing the values for debugging
484         if (null != attributeMap) {
485             RemoteResourceAttribute.printAttributes(attributeMap);
486         }
487         return resource;
488     }
489
490     private void updateResourceAttributesFromResponse(RemoteResource res,
491             Map<String, RemoteResourceAttribute> newAttributeMap) {
492         if (null == res || null == newAttributeMap) {
493             return;
494         }
495         Map<String, RemoteResourceAttribute> oldAttributeMap = res
496                 .getResourceAttributesMap();
497         if (null == oldAttributeMap) {
498             return;
499         }
500         Iterator<String> itr = oldAttributeMap.keySet().iterator();
501         String attName;
502         RemoteResourceAttribute newAtt;
503         RemoteResourceAttribute oldAtt;
504         while (itr.hasNext()) {
505             attName = itr.next();
506             newAtt = newAttributeMap.get(attName);
507             if (null == newAtt) {
508                 // Attribute does not exist in the received model. Hence
509                 // removing it from local model.
510                 itr.remove();
511             } else {
512                 oldAtt = oldAttributeMap.get(attName);
513                 if (null != oldAtt) {
514                     oldAtt.setAttributeValue(newAtt.getAttributeValue());
515                 } else {
516                     itr.remove();
517                 }
518                 newAttributeMap.remove(attName);
519             }
520         }
521         // Adding new attributes in the received model.
522         itr = newAttributeMap.keySet().iterator();
523         while (itr.hasNext()) {
524             attName = itr.next();
525             oldAttributeMap.put(attName, newAttributeMap.get(attName));
526         }
527     }
528
529     public synchronized DeviceInfo getDeviceInfo() {
530         return devInfo;
531     }
532
533     public synchronized void setDeviceInfo(DeviceInfo devInfo) {
534         this.devInfo = devInfo;
535     }
536
537     public synchronized PlatformInfo getPlatformInfo() {
538         return platInfo;
539     }
540
541     public synchronized void setPlatformInfo(PlatformInfo platInfo) {
542         this.platInfo = platInfo;
543     }
544
545     private static class ResponseSynchronizerThread implements Runnable {
546
547         LinkedList<Runnable> responseQueue = new LinkedList<Runnable>();
548
549         @Override
550         public void run() {
551             while (!Thread.interrupted()) {
552                 synchronized (this) {
553                     try {
554                         while (responseQueue.isEmpty()) {
555                             this.wait();
556                             break;
557                         }
558                     } catch (InterruptedException e) {
559                         return;
560                     }
561                 }
562
563                 Runnable thread;
564                 synchronized (this) {
565                     thread = responseQueue.pop();
566                 }
567                 try {
568                     thread.run();
569                 } catch (Exception e) {
570                     if (e instanceof InterruptedException) {
571                         return;
572                     }
573                     e.printStackTrace();
574                 }
575             }
576         }
577
578         public void addToQueue(Runnable event) {
579             synchronized (this) {
580                 responseQueue.add(event);
581                 this.notify();
582             }
583         }
584     }
585
586     public void addResourceSelectionChangedUIListener(
587             IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
588         synchronized (resourceSelectionChangedUIListeners) {
589             resourceSelectionChangedUIListeners
590                     .add(resourceSelectionChangedUIListener);
591         }
592     }
593
594     public void addGetUIListener(IGetUIListener getUIListener) {
595         synchronized (getUIListeners) {
596             getUIListeners.add(getUIListener);
597         }
598     }
599
600     public void addPutUIListener(IPutUIListener putUIListener) {
601         synchronized (putUIListeners) {
602             putUIListeners.add(putUIListener);
603         }
604     }
605
606     public void addPostUIListener(IPostUIListener postUIListener) {
607         synchronized (postUIListeners) {
608             postUIListeners.add(postUIListener);
609         }
610     }
611
612     public void addObserveUIListener(IObserveUIListener observeUIListener) {
613         synchronized (observeUIListeners) {
614             observeUIListeners.add(observeUIListener);
615         }
616     }
617
618     public void addVerificationUIListener(
619             IVerificationUIListener verificationUIListener) {
620         synchronized (verificationUIListeners) {
621             verificationUIListeners.add(verificationUIListener);
622         }
623     }
624
625     public void addConfigUploadUIListener(IConfigurationUpload configListener) {
626         synchronized (configUploadUIListeners) {
627             configUploadUIListeners.add(configListener);
628         }
629     }
630
631     public void addDevicePlatformInfoUIListener(
632             IDevicePlatformInfoUIListener deviceUIListener) {
633         synchronized (devicePlatformInfoUIListeners) {
634             devicePlatformInfoUIListeners.add(deviceUIListener);
635         }
636     }
637
638     public void removeDevicePlatformInfoUIListener(
639             IDevicePlatformInfoUIListener platformUIListener) {
640         synchronized (devicePlatformInfoUIListeners) {
641             devicePlatformInfoUIListeners.remove(platformUIListener);
642         }
643     }
644
645     public void removeResourceSelectionChangedUIListener(
646             IResourceSelectionChangedUIListener listener) {
647         synchronized (resourceSelectionChangedUIListeners) {
648             if (null != listener
649                     && resourceSelectionChangedUIListeners.size() > 0) {
650                 resourceSelectionChangedUIListeners.remove(listener);
651             }
652         }
653     }
654
655     public void removeGetUIListener(IGetUIListener getUIListener) {
656         synchronized (getUIListeners) {
657             getUIListeners.remove(getUIListener);
658         }
659     }
660
661     public void removePutUIListener(IPutUIListener putUIListener) {
662         synchronized (putUIListeners) {
663             putUIListeners.remove(putUIListener);
664         }
665     }
666
667     public void removePostUIListener(IPostUIListener postUIListener) {
668         synchronized (postUIListeners) {
669             postUIListeners.remove(postUIListener);
670         }
671     }
672
673     public void removeObserveUIListener(IObserveUIListener observeUIListener) {
674         synchronized (observeUIListeners) {
675             observeUIListeners.remove(observeUIListener);
676         }
677     }
678
679     public void removeVerificationUIListener(
680             IVerificationUIListener verificationUIListener) {
681         synchronized (verificationUIListeners) {
682             verificationUIListeners.remove(verificationUIListener);
683         }
684     }
685
686     public void removeConfigUploadUIListener(IConfigurationUpload configListener) {
687         synchronized (configUploadUIListeners) {
688             configUploadUIListeners.remove(configListener);
689         }
690     }
691
692     public void addResourcetoFavorites(RemoteResource resource) {
693         if (null == resource) {
694             return;
695         }
696         resource.setFavorite(true);
697         synchronized (favoriteResources) {
698             favoriteResources.add(resource);
699         }
700     }
701
702     public void removeResourceFromFavorites(RemoteResource resource) {
703         if (null == resource) {
704             return;
705         }
706         resource.setFavorite(false);
707         synchronized (favoriteResources) {
708             favoriteResources.remove(resource);
709         }
710     }
711
712     public void addResourceURItoFavorites(RemoteResource resource) {
713         if (null == resource) {
714             return;
715         }
716         synchronized (favoriteURIList) {
717             favoriteURIList.add(resource.getRemoteResourceRef().getURI());
718         }
719     }
720
721     public void removeResourceURIFromFavorites(RemoteResource resource) {
722         if (null == resource) {
723             return;
724         }
725         synchronized (favoriteURIList) {
726             favoriteURIList.remove(resource.getRemoteResourceRef().getURI());
727         }
728     }
729
730     public void addObservedResourceURI(String resourceURI) {
731         synchronized (observedResourceURIList) {
732             observedResourceURIList.add(resourceURI);
733         }
734     }
735
736     public void removeObservedResourceURI(String resourceURI) {
737         synchronized (observedResourceURIList) {
738             observedResourceURIList.remove(resourceURI);
739         }
740     }
741
742     public boolean isResourceObserved(String resourceURI) {
743         boolean observed = false;
744         synchronized (observedResourceURIList) {
745             observed = observedResourceURIList.contains(resourceURI);
746         }
747         return observed;
748     }
749
750     public synchronized RemoteResource getCurrentResourceInSelection() {
751         return currentResourceInSelection;
752     }
753
754     public synchronized void setCurrentResourceInSelection(
755             RemoteResource resource) {
756         this.currentResourceInSelection = resource;
757     }
758
759     private void addResourceDetails(RemoteResource remoteResource) {
760         if (null != remoteResource) {
761             synchronized (resourceMap) {
762                 resourceMap.put(remoteResource.getRemoteResourceRef().getId(),
763                         remoteResource);
764             }
765         }
766     }
767
768     public void addFindresourceUIListener(IFindResourceUIListener listener) {
769         if (null == listener) {
770             return;
771         }
772         synchronized (findResourceUIListeners) {
773             findResourceUIListeners.add(listener);
774         }
775     }
776
777     public void removeFindresourceUIListener(IFindResourceUIListener listener) {
778         if (null == listener) {
779             return;
780         }
781         synchronized (findResourceUIListeners) {
782             findResourceUIListeners.remove(listener);
783         }
784     }
785
786     private boolean isUidExist(String uid) {
787         boolean exist;
788         synchronized (resourceMap) {
789             exist = resourceMap.containsKey(uid);
790         }
791         return exist;
792     }
793
794     private RemoteResource getResource(String uid) {
795         if (null == uid) {
796             return null;
797         }
798         RemoteResource resource;
799         synchronized (resourceMap) {
800             resource = resourceMap.get(uid);
801         }
802         return resource;
803     }
804
805     private Map<String, RemoteResourceAttribute> fetchResourceAttributesFromModel(
806             SimulatorResourceModel resourceModelN) {
807         Map<String, RemoteResourceAttribute> resourceAttributeMap = null;
808         if (null != resourceModelN) {
809             Map<String, SimulatorResourceAttribute> attributeMapN;
810             attributeMapN = resourceModelN.getAttributes();
811             if (null != attributeMapN) {
812                 resourceAttributeMap = new HashMap<String, RemoteResourceAttribute>();
813
814                 Set<String> attNameSet = attributeMapN.keySet();
815                 String attName;
816                 Object attValueObj;
817                 AttributeValue attValueN;
818                 AttributeProperty attPropN;
819                 TypeInfo typeInfo;
820                 Type valuesType;
821                 SimulatorResourceAttribute attributeN;
822                 RemoteResourceAttribute attribute;
823                 Iterator<String> attNameItr = attNameSet.iterator();
824                 while (attNameItr.hasNext()) {
825                     attName = attNameItr.next();
826                     attributeN = attributeMapN.get(attName);
827                     if (null != attributeN) {
828                         attribute = new RemoteResourceAttribute();
829                         attribute.setResourceAttributeRef(attributeN);
830                         attribute.setAttributeName(attName);
831
832                         attValueN = attributeN.value();
833                         if (null != attValueN) {
834                             attValueObj = attValueN.get();
835                             if (null != attValueObj) {
836                                 attribute.setAttributeValue(attValueObj);
837                             }
838
839                             // Set the attribute type
840                             typeInfo = attValueN.typeInfo();
841                             if (null != typeInfo) {
842                                 attribute.setAttValBaseType(typeInfo.mBaseType);
843                                 attribute.setAttValType(typeInfo.mType);
844                                 attribute.setDepth(typeInfo.mDepth);
845                             }
846
847                         }
848
849                         // Set the range and allowed values
850                         attPropN = attributeN.property();
851                         valuesType = attPropN.type();
852                         attribute.setValuesType(valuesType);
853                         if (valuesType == Type.RANGE) {
854                             attribute.setMinValue(attPropN.min());
855                             attribute.setMaxValue(attPropN.max());
856                         } else if (valuesType == Type.VALUESET) {
857                             Object[] values = attPropN.valueSet();
858                             if (null != values && values.length > 0) {
859                                 List<Object> valueList = new ArrayList<Object>();
860                                 for (Object obj : values) {
861                                     valueList.add(((AttributeValue) obj).get());
862                                 }
863                                 attribute.setAllowedValues(valueList);
864                             }
865                         }
866                         resourceAttributeMap.put(attName, attribute);
867                     }
868                 }
869             }
870         }
871         return resourceAttributeMap;
872     }
873
874     private void newResourceFoundNotification(RemoteResource resource) {
875         synchronized (findResourceUIListeners) {
876             if (findResourceUIListeners.size() > 0) {
877                 IFindResourceUIListener listener;
878                 Iterator<IFindResourceUIListener> listenerItr = findResourceUIListeners
879                         .iterator();
880                 while (listenerItr.hasNext()) {
881                     listener = listenerItr.next();
882                     if (null != listener) {
883                         listener.onNewResourceFound(resource);
884                     }
885                 }
886             }
887         }
888     }
889
890     private void resourceSelectionChangedUINotification(RemoteResource resource) {
891         synchronized (resourceSelectionChangedUIListeners) {
892             if (resourceSelectionChangedUIListeners.size() > 0) {
893                 IResourceSelectionChangedUIListener listener;
894                 Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
895                         .iterator();
896                 while (listenerItr.hasNext()) {
897                     listener = listenerItr.next();
898                     if (null != listener) {
899                         listener.onResourceSelectionChange(resource);
900                     }
901                 }
902             }
903         }
904     }
905
906     private void getCompleteNotification(RemoteResource resource) {
907         synchronized (getUIListeners) {
908             if (getUIListeners.size() > 0) {
909                 IGetUIListener listener;
910                 Iterator<IGetUIListener> listenerItr = getUIListeners
911                         .iterator();
912                 while (listenerItr.hasNext()) {
913                     listener = listenerItr.next();
914                     if (null != listener) {
915                         listener.onGetCompleted(resource);
916                     }
917                 }
918             }
919         }
920     }
921
922     private void putCompleteNotification(RemoteResource resource) {
923         synchronized (putUIListeners) {
924             if (putUIListeners.size() > 0) {
925                 IPutUIListener listener;
926                 Iterator<IPutUIListener> listenerItr = putUIListeners
927                         .iterator();
928                 while (listenerItr.hasNext()) {
929                     listener = listenerItr.next();
930                     if (null != listener) {
931                         listener.onPutCompleted(resource);
932                     }
933                 }
934             }
935         }
936     }
937
938     private void postCompleteNotification(RemoteResource resource) {
939         synchronized (postUIListeners) {
940             if (postUIListeners.size() > 0) {
941                 IPostUIListener listener;
942                 Iterator<IPostUIListener> listenerItr = postUIListeners
943                         .iterator();
944                 while (listenerItr.hasNext()) {
945                     listener = listenerItr.next();
946                     if (null != listener) {
947                         listener.onPostCompleted(resource);
948                     }
949                 }
950             }
951         }
952     }
953
954     private void observeCompleteNotification(RemoteResource resource) {
955         synchronized (observeUIListeners) {
956             if (observeUIListeners.size() > 0) {
957                 IObserveUIListener listener;
958                 Iterator<IObserveUIListener> listenerItr = observeUIListeners
959                         .iterator();
960                 while (listenerItr.hasNext()) {
961                     listener = listenerItr.next();
962                     if (null != listener) {
963                         listener.onObserveCompleted(resource);
964                     }
965                 }
966             }
967         }
968     }
969
970     private void verificationStartedNotification(RemoteResource resource,
971             int autoType) {
972         synchronized (verificationUIListeners) {
973             if (verificationUIListeners.size() > 0) {
974                 IVerificationUIListener listener;
975                 Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
976                         .iterator();
977                 while (listenerItr.hasNext()) {
978                     listener = listenerItr.next();
979                     if (null != listener) {
980                         listener.onVerificationStarted(resource, autoType);
981                     }
982                 }
983             }
984         }
985     }
986
987     private void verificationAbortedNotification(RemoteResource resource,
988             int autoType) {
989         synchronized (verificationUIListeners) {
990             if (verificationUIListeners.size() > 0) {
991                 IVerificationUIListener listener;
992                 Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
993                         .iterator();
994                 while (listenerItr.hasNext()) {
995                     listener = listenerItr.next();
996                     if (null != listener) {
997                         listener.onVerificationAborted(resource, autoType);
998                     }
999                 }
1000             }
1001         }
1002     }
1003
1004     private void verificationCompletedNotification(RemoteResource resource,
1005             int autoType) {
1006         synchronized (verificationUIListeners) {
1007             if (verificationUIListeners.size() > 0) {
1008                 IVerificationUIListener listener;
1009                 Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
1010                         .iterator();
1011                 while (listenerItr.hasNext()) {
1012                     listener = listenerItr.next();
1013                     if (null != listener) {
1014                         listener.onVerificationCompleted(resource, autoType);
1015                     }
1016                 }
1017             }
1018         }
1019     }
1020
1021     private void configUploadedNotification(RemoteResource resource) {
1022         synchronized (configUploadUIListeners) {
1023             if (configUploadUIListeners.size() > 0) {
1024                 IConfigurationUpload listener;
1025                 Iterator<IConfigurationUpload> listenerItr = configUploadUIListeners
1026                         .iterator();
1027                 while (listenerItr.hasNext()) {
1028                     listener = listenerItr.next();
1029                     if (null != listener) {
1030                         listener.onConfigurationUploaded(resource);
1031                     }
1032                 }
1033             }
1034         }
1035     }
1036
1037     private void deviceInfoReceivedNotification() {
1038         synchronized (devicePlatformInfoUIListeners) {
1039             if (devicePlatformInfoUIListeners.size() > 0) {
1040                 IDevicePlatformInfoUIListener listener;
1041                 Iterator<IDevicePlatformInfoUIListener> listenerItr = devicePlatformInfoUIListeners
1042                         .iterator();
1043                 while (listenerItr.hasNext()) {
1044                     listener = listenerItr.next();
1045                     if (null != listener) {
1046                         listener.onDeviceInfoFound();
1047                     }
1048                 }
1049             }
1050         }
1051     }
1052
1053     private void platformInfoReceivedNotification() {
1054         synchronized (devicePlatformInfoUIListeners) {
1055             if (devicePlatformInfoUIListeners.size() > 0) {
1056                 IDevicePlatformInfoUIListener listener;
1057                 Iterator<IDevicePlatformInfoUIListener> listenerItr = devicePlatformInfoUIListeners
1058                         .iterator();
1059                 while (listenerItr.hasNext()) {
1060                     listener = listenerItr.next();
1061                     if (null != listener) {
1062                         listener.onPlatformInfoFound();
1063                     }
1064                 }
1065             }
1066         }
1067     }
1068
1069     public synchronized Set<String> getLastKnownSearchTypes() {
1070         return lastKnownSearchTypes;
1071     }
1072
1073     public synchronized void setLastKnownSearchTypes(
1074             Set<String> lastKnownSearchTypes) {
1075         this.lastKnownSearchTypes = lastKnownSearchTypes;
1076     }
1077
1078     public boolean findResourceRequest(Set<String> searchTypes) {
1079         boolean result = false;
1080         if (null == searchTypes || searchTypes.size() < 1) {
1081             try {
1082                 SimulatorManager.findResource(findResourceListener);
1083                 result = true;
1084             } catch (SimulatorException e) {
1085                 Activator
1086                         .getDefault()
1087                         .getLogManager()
1088                         .log(Level.ERROR.ordinal(), new Date(),
1089                                 Utility.getSimulatorErrorString(e, null));
1090             }
1091         } else {
1092             Iterator<String> searchItr = searchTypes.iterator();
1093             String rType;
1094             while (searchItr.hasNext()) {
1095                 rType = searchItr.next();
1096                 try {
1097                     SimulatorManager.findResource(rType, findResourceListener);
1098                     result = true;
1099                 } catch (SimulatorException e) {
1100                     Activator
1101                             .getDefault()
1102                             .getLogManager()
1103                             .log(Level.ERROR.ordinal(), new Date(),
1104                                     Utility.getSimulatorErrorString(e, null));
1105                 }
1106             }
1107         }
1108         return result;
1109     }
1110
1111     public void deleteResources(final Set<String> searchTypes) {
1112         synchronized (resourceMap) {
1113             if (null == resourceMap && resourceMap.isEmpty()) {
1114                 return;
1115             }
1116         }
1117         new Thread() {
1118             public void run() {
1119                 if (null == searchTypes || searchTypes.size() < 1) {
1120                     synchronized (resourceMap) {
1121                         // Stop observing all the resources
1122                         Iterator<String> itr = resourceMap.keySet().iterator();
1123                         while (itr.hasNext()) {
1124                             sendCancelObserveRequest(
1125                                     resourceMap.get(itr.next()), false);
1126                         }
1127                         // Delete all cached details of resources
1128                         resourceMap.clear();
1129                         favoriteResources.clear();
1130                     }
1131                     // Change the current resource in selection
1132                     setCurrentResourceInSelection(null);
1133                     resourceSelectionChangedUINotification(null);
1134                 } else {
1135                     Iterator<String> typeItr = searchTypes.iterator();
1136                     String resType;
1137                     while (typeItr.hasNext()) {
1138                         resType = typeItr.next();
1139                         deleteResourcesByType(resType);
1140
1141                         // Change the current resource in selection
1142                         updateCurrentResourceInSelection(searchTypes);
1143                     }
1144                 }
1145             }
1146         }.start();
1147     }
1148
1149     private void updateCurrentResourceInSelection(Set<String> searchTypes) {
1150         if (null == searchTypes || searchTypes.size() < 1) {
1151             return;
1152         }
1153         RemoteResource resourceInSelection = getCurrentResourceInSelection();
1154         if (null == resourceInSelection) {
1155             return;
1156         }
1157         List<String> typesOfSelection = resourceInSelection
1158                 .getRemoteResourceRef().getResourceTypes();
1159         if (null == typesOfSelection || typesOfSelection.size() < 1) {
1160             return;
1161         }
1162         Iterator<String> itr = typesOfSelection.iterator();
1163         String type;
1164         while (itr.hasNext()) {
1165             type = itr.next();
1166             if (searchTypes.contains(type)) {
1167                 setCurrentResourceInSelection(null);
1168                 resourceSelectionChangedUINotification(null);
1169                 break;
1170             }
1171         }
1172     }
1173
1174     private void deleteResourcesByType(String resourceType) {
1175         if (null == resourceType) {
1176             return;
1177         }
1178         synchronized (resourceMap) {
1179             Set<String> keySet = resourceMap.keySet();
1180             if (null == keySet) {
1181                 return;
1182             }
1183             Iterator<String> keyItr = keySet.iterator();
1184             String uId;
1185             RemoteResource resource;
1186             boolean exist;
1187             List<String> types;
1188             while (keyItr.hasNext()) {
1189                 uId = keyItr.next();
1190                 resource = resourceMap.get(uId);
1191                 if (null == resource) {
1192                     continue;
1193                 }
1194                 types = resource.getRemoteResourceRef().getResourceTypes();
1195                 if (null != types) {
1196                     exist = types.contains(resourceType);
1197                     if (exist) {
1198                         // Cancel observing the resource.
1199                         sendCancelObserveRequest(resource, false);
1200                         // Remove the resource from favorites list.
1201                         removeResourceFromFavorites(resource);
1202                         // Remove the resource
1203                         keyItr.remove();
1204                     }
1205                 }
1206             }
1207         }
1208     }
1209
1210     public void resourceSelectionChanged(final RemoteResource resource) {
1211         new Thread() {
1212             @Override
1213             public void run() {
1214                 setCurrentResourceInSelection(resource);
1215                 // Notify all observers for resource selection change event
1216                 resourceSelectionChangedUINotification(resource);
1217             }
1218         }.start();
1219     }
1220
1221     public List<MetaProperty> getDefaultProperties(RemoteResource resource) {
1222         if (null != resource) {
1223             String propName;
1224             String propValue;
1225
1226             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
1227
1228             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
1229                 propName = Constants.META_PROPERTIES[index];
1230                 if (propName.equals(Constants.RESOURCE_URI)) {
1231                     propValue = resource.getRemoteResourceRef().getURI();
1232                 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
1233                     propValue = resource.getRemoteResourceRef()
1234                             .getConnectivityType().toString();
1235                 } else if (propName.equals(Constants.ADDRESS)) {
1236                     propValue = resource.getRemoteResourceRef().getHost();
1237                 } else if (propName.equals(Constants.OBSERVABLE)) {
1238                     propValue = Utility.getObservableInString(resource
1239                             .getRemoteResourceRef().isObservable());
1240                 } else if (propName.equals(Constants.RESOURCE_TYPES)) {
1241                     Vector<String> types = resource.getRemoteResourceRef()
1242                             .getResourceTypes();
1243                     if (null != types) {
1244                         propValue = types.toString();
1245                     } else {
1246                         propValue = Constants.NOT_AVAILABLE;
1247                     }
1248                 } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
1249                     Vector<String> interfaces = resource.getRemoteResourceRef()
1250                             .getResourceInterfaces();
1251                     if (null != interfaces) {
1252                         propValue = interfaces.toString();
1253                     } else {
1254                         propValue = Constants.NOT_AVAILABLE;
1255                     }
1256                 } else {
1257                     propValue = null;
1258                 }
1259                 if (null != propValue) {
1260                     metaPropertyList.add(new MetaProperty(propName, propValue));
1261                 }
1262             }
1263
1264             return metaPropertyList;
1265         }
1266         return null;
1267     }
1268
1269     public List<MetaProperty> getDeviceProperties() {
1270         if (null == devInfo) {
1271             return null;
1272         }
1273
1274         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
1275
1276         metaProperties.add(new MetaProperty(Constants.DEVICE_ID, devInfo
1277                 .getID()));
1278         metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, devInfo
1279                 .getName()));
1280         metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
1281                 devInfo.getSpecVersion()));
1282         metaProperties.add(new MetaProperty(Constants.DEVICE_DMV_VERSION,
1283                 devInfo.getDataModelVersion()));
1284
1285         /*
1286          * metaProperties.add(new MetaProperty(Constants.DEVICE_ID, ""));
1287          * metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, ""));
1288          * metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
1289          * "")); metaProperties.add(new
1290          * MetaProperty(Constants.DEVICE_DMV_VERSION, ""));
1291          */
1292         return metaProperties;
1293     }
1294
1295     public List<MetaProperty> getPlatformProperties() {
1296         if (null == platInfo) {
1297             return null;
1298         }
1299
1300         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
1301
1302         metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platInfo
1303                 .getPlatformID()));
1304         metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME,
1305                 platInfo.getManufacturerName()));
1306         metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
1307                 platInfo.getManufacturerUrl()));
1308         metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
1309                 platInfo.getModelNumber()));
1310         metaProperties.add(new MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC,
1311                 platInfo.getDateOfManufacture()));
1312         metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
1313                 platInfo.getPlatformVersion()));
1314         metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
1315                 platInfo.getOperationSystemVersion()));
1316         metaProperties.add(new MetaProperty(
1317                 Constants.PLATFORM_HARDWARE_VERSION, platInfo
1318                         .getHardwareVersion()));
1319         metaProperties.add(new MetaProperty(
1320                 Constants.PLATFORM_FIRMWARE_VERSION, platInfo
1321                         .getFirmwareVersion()));
1322         metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
1323                 platInfo.getSupportUrl()));
1324         metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
1325                 platInfo.getSystemTime()));
1326
1327         /*
1328          * metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, ""));
1329          * metaProperties .add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME,
1330          * "")); metaProperties .add(new
1331          * MetaProperty(Constants.PLATFORM_MANUFAC_URL, ""));
1332          * metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
1333          * "")); metaProperties.add(new
1334          * MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC, ""));
1335          * metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION, ""));
1336          * metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
1337          * "")); metaProperties.add(new MetaProperty(
1338          * Constants.PLATFORM_HARDWARE_VERSION, "")); metaProperties.add(new
1339          * MetaProperty( Constants.PLATFORM_FIRMWARE_VERSION, ""));
1340          * metaProperties .add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
1341          * "")); metaProperties .add(new
1342          * MetaProperty(Constants.PLATFORM_SYSTEM_TIME, ""));
1343          */
1344         return metaProperties;
1345     }
1346
1347     public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
1348         if (null == resource) {
1349             return null;
1350         }
1351         Map<String, Boolean> autoStatus = new HashMap<String, Boolean>();
1352         autoStatus.put(Constants.GET, resource.isGetAutomtnInProgress());
1353         autoStatus.put(Constants.PUT, resource.isPutAutomtnInProgress());
1354         autoStatus.put(Constants.POST, resource.isPostAutomtnInProgress());
1355         return autoStatus;
1356     }
1357
1358     public List<RemoteResource> getResourceList() {
1359         List<RemoteResource> resourceList = new ArrayList<RemoteResource>();
1360         synchronized (resourceMap) {
1361             Set<String> idSet = resourceMap.keySet();
1362             Iterator<String> idItr = idSet.iterator();
1363             RemoteResource resource;
1364             while (idItr.hasNext()) {
1365                 resource = resourceMap.get(idItr.next());
1366                 if (null != resource) {
1367                     resourceList.add(resource);
1368                 }
1369             }
1370         }
1371         // Sort the list
1372         Collections.sort(resourceList, new Comparator<RemoteResource>() {
1373             public int compare(RemoteResource res1, RemoteResource res2) {
1374                 String s1 = res1.getRemoteResourceRef().getURI();
1375                 String s2 = res2.getRemoteResourceRef().getURI();
1376
1377                 String s1Part = s1.replaceAll("\\d", "");
1378                 String s2Part = s2.replaceAll("\\d", "");
1379
1380                 if (s1Part.equalsIgnoreCase(s2Part)) {
1381                     return extractInt(s1) - extractInt(s2);
1382                 }
1383                 return s1.compareTo(s2);
1384             }
1385
1386             int extractInt(String s) {
1387                 String num = s.replaceAll("\\D", "");
1388                 // return 0 if no digits found
1389                 return num.isEmpty() ? 0 : Integer.parseInt(num);
1390             }
1391         });
1392
1393         return resourceList;
1394     }
1395
1396     public List<RemoteResource> getFavResourceList() {
1397         List<RemoteResource> resourceList;
1398         synchronized (favoriteResources) {
1399             resourceList = new ArrayList<RemoteResource>(favoriteResources);
1400         }
1401         return resourceList;
1402     }
1403
1404     public String getAttributeValue(RemoteResource res, String attName) {
1405         if (null == res || null == attName) {
1406             return null;
1407         }
1408         return res.getAttributeValue(attName);
1409     }
1410
1411     public void sendGetRequest(RemoteResource resource) {
1412         if (null == resource) {
1413             return;
1414         }
1415         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1416         if (null == resourceN) {
1417             return;
1418         }
1419         try {
1420             resourceN.get(null, getListener);
1421         } catch (SimulatorException e) {
1422             Activator
1423                     .getDefault()
1424                     .getLogManager()
1425                     .log(Level.ERROR.ordinal(), new Date(),
1426                             Utility.getSimulatorErrorString(e, null));
1427         }
1428     }
1429
1430     public void sendPutRequest(RemoteResource resource,
1431             List<PutPostAttributeModel> putPostModelList) {
1432         if (null == resource) {
1433             return;
1434         }
1435         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1436         if (null == resourceN) {
1437             return;
1438         }
1439         Map<String, RemoteResourceAttribute> attMap = resource
1440                 .getResourceAttributesMap();
1441         if (null == attMap || attMap.size() < 1) {
1442             return;
1443         }
1444         try {
1445             SimulatorResourceModel resourceModel = getUpdatedResourceModel(
1446                     attMap, putPostModelList);
1447             resourceN.put(null, resourceModel, putListener);
1448         } catch (Exception e) {
1449             String addlInfo;
1450             addlInfo = "Invalid Attribute Value. Cannot send PUT request.";
1451             Activator
1452                     .getDefault()
1453                     .getLogManager()
1454                     .log(Level.ERROR.ordinal(), new Date(),
1455                             Utility.getSimulatorErrorString(e, addlInfo));
1456         }
1457     }
1458
1459     public void sendPostRequest(RemoteResource resource,
1460             List<PutPostAttributeModel> putPostModelList) {
1461         if (null == resource) {
1462             return;
1463         }
1464         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1465         if (null == resourceN) {
1466             return;
1467         }
1468         Map<String, RemoteResourceAttribute> attMap = resource
1469                 .getResourceAttributesMap();
1470         if (null == attMap || attMap.size() < 1) {
1471             return;
1472         }
1473         // Filter out the attributes whose modification status is true.
1474         Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
1475         PutPostAttributeModel model;
1476         while (itr.hasNext()) {
1477             model = itr.next();
1478             if (!model.isModified()) {
1479                 itr.remove();
1480             }
1481         }
1482         try {
1483             SimulatorResourceModel resourceModel = getUpdatedResourceModel(
1484                     attMap, putPostModelList);
1485             resourceN.post(null, resourceModel, postListener);
1486         } catch (Exception e) {
1487             String addlInfo;
1488             addlInfo = "Invalid Attribute Value. Cannot send POST request.";
1489             Activator
1490                     .getDefault()
1491                     .getLogManager()
1492                     .log(Level.ERROR.ordinal(), new Date(),
1493                             Utility.getSimulatorErrorString(e, addlInfo));
1494         }
1495     }
1496
1497     private SimulatorResourceModel getUpdatedResourceModel(
1498             Map<String, RemoteResourceAttribute> attMap,
1499             List<PutPostAttributeModel> putPostModelList) throws Exception {
1500         SimulatorResourceModel resourceModel = new SimulatorResourceModel();
1501         for (PutPostAttributeModel putPostAttribute : putPostModelList)
1502         {
1503             String attributeName = putPostAttribute.getAttName();
1504             RemoteResourceAttribute resourceAttribute = attMap.get(attributeName);
1505             AttributeValue attributeValue = AttributeValueBuilder.build(
1506                     putPostAttribute.getAttValue(), resourceAttribute.getAttValBaseType());
1507             resourceModel.addAttribute(attributeName, attributeValue);
1508         }
1509
1510         return resourceModel;
1511     }
1512
1513     public boolean sendObserveRequest(RemoteResource resource) {
1514         if (null == resource) {
1515             return false;
1516         }
1517         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1518         if (null == resourceN) {
1519             return false;
1520         }
1521         try {
1522             resourceN.startObserve(null, observeListener);
1523             resource.setObserved(true);
1524             // Add observed resource URI to show the proper status after every
1525             // find/refresh operations.
1526             addObservedResourceURI(resource.getRemoteResourceRef().getURI());
1527         } catch (SimulatorException e) {
1528             Activator
1529                     .getDefault()
1530                     .getLogManager()
1531                     .log(Level.ERROR.ordinal(), new Date(),
1532                             Utility.getSimulatorErrorString(e, null));
1533             return false;
1534         }
1535         return true;
1536     }
1537
1538     public boolean sendCancelObserveRequest(RemoteResource resource,
1539             boolean removeEntry) {
1540         if (null == resource || !resource.isObserved()) {
1541             return false;
1542         }
1543         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1544         if (null == resourceN) {
1545             return false;
1546         }
1547         try {
1548             resourceN.stopObserve();
1549             resource.setObserved(false);
1550             // Remove observed resource URI to show the proper status after
1551             // every find/refresh operations.
1552             if (removeEntry)
1553                 removeObservedResourceURI(resource.getRemoteResourceRef()
1554                         .getURI());
1555         } catch (SimulatorException e) {
1556             Activator
1557                     .getDefault()
1558                     .getLogManager()
1559                     .log(Level.ERROR.ordinal(), new Date(),
1560                             Utility.getSimulatorErrorString(e, null));
1561             return false;
1562         }
1563         return true;
1564     }
1565
1566     public void startAutomationRequest(VerificationType reqType,
1567             RemoteResource resource) {
1568         if (null == resource) {
1569             return;
1570         }
1571         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1572         if (null == resourceN) {
1573             return;
1574         }
1575         if (null == reqType) {
1576             return;
1577         }
1578         int autoId;
1579         try {
1580             autoId = resourceN.startVerification(reqType, verifyListener);
1581             if (autoId != -1) {
1582                 if (reqType == VerificationType.GET) {
1583                     // resource.setGetAutomtnInProgress(true);
1584                     resource.setGetAutomtnId(autoId);
1585                 } else if (reqType == VerificationType.PUT) {
1586                     // resource.setPutAutomtnInProgress(true);
1587                     resource.setPutAutomtnId(autoId);
1588                 } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
1589                     // resource.setPostAutomtnInProgress(true);
1590                     resource.setPostAutomtnId(autoId);
1591                 }
1592             }
1593         } catch (SimulatorException e) {
1594             Activator
1595                     .getDefault()
1596                     .getLogManager()
1597                     .log(Level.ERROR.ordinal(), new Date(),
1598                             Utility.getSimulatorErrorString(e, null));
1599         }
1600     }
1601
1602     public void stopAutomationRequest(VerificationType reqType,
1603             RemoteResource resource) {
1604         if (null == resource) {
1605             return;
1606         }
1607         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1608         if (null == resourceN) {
1609             return;
1610         }
1611         int autoId;
1612         if (reqType == VerificationType.GET) {
1613             resource.setGetAutomtnInProgress(false);
1614             autoId = resource.getGetAutomtnId();
1615         } else if (reqType == VerificationType.PUT) {
1616             resource.setPutAutomtnInProgress(false);
1617             autoId = resource.getPutAutomtnId();
1618         } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
1619             resource.setPostAutomtnInProgress(false);
1620             autoId = resource.getPostAutomtnId();
1621         }
1622         try {
1623             resourceN.stopVerification(autoId);
1624         } catch (SimulatorException e) {
1625             Activator
1626                     .getDefault()
1627                     .getLogManager()
1628                     .log(Level.ERROR.ordinal(), new Date(),
1629                             Utility.getSimulatorErrorString(e, null));
1630         }
1631     }
1632
1633     public boolean setConfigFilePath(RemoteResource resource,
1634             String configFilePath) throws SimulatorException {
1635         if (null == resource) {
1636             return false;
1637         }
1638         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1639         if (null == resourceN) {
1640             return false;
1641         }
1642         try {
1643             SimulatorResourceModel resourceModel;
1644             resourceModel = resourceN.setConfigInfo(configFilePath);
1645             if (null == resourceModel) {
1646                 return false;
1647             }
1648             // Store the resource model in the local cache
1649             resource.setResourceModelRef(resourceModel);
1650
1651             // Fetching the allowed values and range for all the attributes
1652             Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModel);
1653             resource.setResourceAttributesMap(attributeMap);
1654             // TODO: Printing the values for debugging
1655             if (null != attributeMap) {
1656                 RemoteResourceAttribute.printAttributes(attributeMap);
1657             }
1658         } catch (SimulatorException e) {
1659             Activator
1660                     .getDefault()
1661                     .getLogManager()
1662                     .log(Level.ERROR.ordinal(), new Date(),
1663                             Utility.getSimulatorErrorString(e, null));
1664             throw e;
1665         }
1666         // Update the status
1667         resource.setConfigUploaded(true);
1668
1669         // Notify the UI listeners
1670         configUploadedNotification(resource);
1671
1672         return true;
1673     }
1674
1675     public void shutdown() {
1676     }
1677 }