07f57d92f82e5357e6bf4b78393565ab5b98da02
[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.remoteresource.DeviceAndPlatformInfo;
33 import oic.simulator.clientcontroller.remoteresource.MetaProperty;
34 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
35 import oic.simulator.clientcontroller.utils.Constants;
36 import oic.simulator.clientcontroller.utils.Utility;
37
38 import org.oic.simulator.AttributeProperty;
39 import org.oic.simulator.AttributeProperty.Type;
40 import org.oic.simulator.AttributeValue;
41 import org.oic.simulator.AttributeValue.TypeInfo;
42 import org.oic.simulator.AttributeValue.ValueType;
43 import org.oic.simulator.DeviceInfo;
44 import org.oic.simulator.DeviceListener;
45 import org.oic.simulator.ILogger.Level;
46 import org.oic.simulator.PlatformInfo;
47 import org.oic.simulator.PlatformListener;
48 import org.oic.simulator.SimulatorException;
49 import org.oic.simulator.SimulatorManager;
50 import org.oic.simulator.SimulatorResourceAttribute;
51 import org.oic.simulator.SimulatorResourceModel;
52 import org.oic.simulator.SimulatorResult;
53 import org.oic.simulator.client.FindResourceListener;
54 import org.oic.simulator.client.SimulatorRemoteResource;
55 import org.oic.simulator.client.SimulatorRemoteResource.GetResponseListener;
56 import org.oic.simulator.client.SimulatorRemoteResource.ObserveNotificationListener;
57 import org.oic.simulator.client.SimulatorRemoteResource.PostResponseListener;
58 import org.oic.simulator.client.SimulatorRemoteResource.PutResponseListener;
59 import org.oic.simulator.client.SimulatorRemoteResource.VerificationListener;
60 import org.oic.simulator.client.SimulatorRemoteResource.VerificationType;
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 responses for
66  * find, GET, PUT, POST, Observe and automatic verification operations from
67  * native layer and propagates those events to the registered UI listeners.
68  */
69 public class ResourceManager {
70
71     private Set<String>                        lastKnownSearchTypes;
72
73     private RemoteResource                     currentResourceInSelection;
74
75     private FindResourceListener               findResourceListener;
76     private GetResponseListener                getListener;
77     private PutResponseListener                putListener;
78     private PostResponseListener               postListener;
79     private ObserveNotificationListener        observeListener;
80     private VerificationListener               verifyListener;
81     private DeviceListener                     deviceListener;
82     private PlatformListener                   platformListener;
83
84     private ResponseSynchronizerThread         synchronizerThread;
85
86     private Thread                             threadHandle;
87
88     // Map with Server ID as key and the complete object as the value
89     private Map<String, RemoteResource>        resourceMap;
90     private List<RemoteResource>               favoriteResources;
91     // Maintaining a list of resource URIs for favorite resources feature.
92     private List<String>                       favoriteURIList;
93
94     // Maintaining a list of observed resource URIs.
95     private List<String>                       observedResourceURIList;
96
97     private Map<String, DeviceAndPlatformInfo> hostDeviceAndPlatformMap;
98
99     public ResourceManager() {
100         resourceMap = new HashMap<String, RemoteResource>();
101         favoriteResources = new ArrayList<RemoteResource>();
102         favoriteURIList = new ArrayList<String>();
103         observedResourceURIList = new ArrayList<String>();
104         hostDeviceAndPlatformMap = new HashMap<String, DeviceAndPlatformInfo>();
105
106         findResourceListener = new FindResourceListener() {
107
108             @Override
109             public void onResourceFound(final SimulatorRemoteResource resourceN) {
110                 synchronizerThread.addToQueue(new Runnable() {
111                     @Override
112                     public void run() {
113                         if (null == resourceN) {
114                             return;
115                         }
116
117                         // Ignore the response if the resource is a device or platform.
118                         Vector<String> resTypes = resourceN.getResourceTypes();
119                         if(null != resTypes && resTypes.contains("oic.wk.d") || resTypes.contains("oic.wk.p")) {
120                             return;
121                         }
122
123                         // If id is not available, then it cannot be added to
124                         // the local map as null value should not be allowed as
125                         // key.
126                         String uid = resourceN.getId();
127                         if (null == uid) {
128                             return;
129                         }
130
131                         // If resource already exist, then ignore it.
132                         boolean exist = isUidExist(uid);
133                         if (exist) {
134                             return;
135                         }
136
137                         RemoteResource resource = new RemoteResource();
138                         resource.setRemoteResourceRef(resourceN);
139
140                         String uri = resourceN.getURI();
141                         if (null != uri && uri.trim().length() > 0) {
142                             // Add resource to favorite list if it was in
143                             // favorites list during find/refresh operation.
144                             if (favoriteURIList.contains(uri)) {
145                                 addResourcetoFavorites(resource);
146                             }
147                             // Add resource to observed resources list if it was
148                             // in observe list during find/refresh operation.
149                             if (observedResourceURIList.contains(uri)) {
150                                 sendObserveRequest(resource);
151                             }
152                         } else {
153                             Activator
154                                     .getDefault()
155                                     .getLogManager()
156                                     .log(Level.INFO.ordinal(), new Date(),
157                                             "Found a resource without URI. Ignoring it.");
158                             return;
159                         }
160
161                         // Add the resource in local data structure
162                         addResourceDetails(resource);
163
164                         // Notify the UI listener
165                         UiListenerHandler.getInstance()
166                                 .newResourceFoundNotification(resource);
167
168                         Activator
169                                 .getDefault()
170                                 .getLogManager()
171                                 .log(Level.INFO.ordinal(),
172                                         new Date(),
173                                         "Resource Found [" + resourceN.getURI()
174                                                 + "].");
175
176                         // Send an initial GET request to get the resource
177                         // attributes.
178                         try {
179                             resourceN.get(null, getListener);
180                         } catch (SimulatorException e) {
181                             Activator
182                                     .getDefault()
183                                     .getLogManager()
184                                     .log(Level.ERROR.ordinal(),
185                                             new Date(),
186                                             Utility.getSimulatorErrorString(e,
187                                                     null));
188                         }
189
190                         // Get the device information
191                         if (!isDeviceInfoExist(resourceN.getHost())) {
192                             try {
193                                 SimulatorManager.findDevices(resource
194                                         .getRemoteResourceRef().getHost(),
195                                         deviceListener);
196                             } catch (SimulatorException e) {
197                                 Activator
198                                         .getDefault()
199                                         .getLogManager()
200                                         .log(Level.ERROR.ordinal(),
201                                                 new Date(),
202                                                 Utility.getSimulatorErrorString(
203                                                         e, null));
204                             }
205                         }
206
207                         // Get the platform information
208                         if (!isPlatformInfoExist(resourceN.getHost())) {
209                             try {
210                                 SimulatorManager.getPlatformInformation(
211                                         resource.getRemoteResourceRef()
212                                                 .getHost(), platformListener);
213                             } catch (SimulatorException e) {
214                                 Activator
215                                         .getDefault()
216                                         .getLogManager()
217                                         .log(Level.ERROR.ordinal(),
218                                                 new Date(),
219                                                 Utility.getSimulatorErrorString(
220                                                         e, null));
221                             }
222                         }
223                     }
224                 });
225             }
226         };
227
228         // Listeners for device and platform information.
229         deviceListener = new DeviceListener() {
230
231             @Override
232             public void onDeviceFound(final String host,
233                     final DeviceInfo deviceInfo) {
234                 if (null == deviceInfo || null == host) {
235                     return;
236                 }
237                 synchronizerThread.addToQueue(new Runnable() {
238                     @Override
239                     public void run() {
240                         synchronized (hostDeviceAndPlatformMap) {
241                             DeviceAndPlatformInfo info = hostDeviceAndPlatformMap
242                                     .get(host);
243                             if (null == info) {
244                                 info = new DeviceAndPlatformInfo();
245                                 info.setHost(host);
246                                 hostDeviceAndPlatformMap.put(host, info);
247                             }
248                             info.setDeviceInfo(deviceInfo);
249                         }
250
251                         // Notify UI listeners
252                         UiListenerHandler.getInstance()
253                                 .deviceInfoReceivedNotification();
254                     }
255                 });
256             }
257         };
258
259         platformListener = new PlatformListener() {
260
261             @Override
262             public void onPlatformFound(final String host,
263                     final PlatformInfo platformInfo) {
264                 if (null == platformInfo || null == host) {
265                     return;
266                 }
267                 synchronizerThread.addToQueue(new Runnable() {
268                     @Override
269                     public void run() {
270                         synchronized (hostDeviceAndPlatformMap) {
271                             DeviceAndPlatformInfo info = hostDeviceAndPlatformMap
272                                     .get(host);
273                             if (null == info) {
274                                 info = new DeviceAndPlatformInfo();
275                                 info.setHost(host);
276                                 hostDeviceAndPlatformMap.put(host, info);
277                             }
278                             info.setPlatformInfo(platformInfo);
279                         }
280
281                         // Notify UI listeners
282                         UiListenerHandler.getInstance()
283                                 .platformInfoReceivedNotification();
284                     }
285                 });
286             }
287         };
288
289         getListener = new GetResponseListener() {
290             @Override
291             public void onGetResponse(final String uid,
292                     final SimulatorResult result,
293                     final SimulatorResourceModel resourceModelN) {
294                 if (result != SimulatorResult.SIMULATOR_OK) {
295                     Activator
296                             .getDefault()
297                             .getLogManager()
298                             .log(Level.ERROR.ordinal(),
299                                     new Date(),
300                                     "["
301                                             + result.toString()
302                                             + "] Received error response for GET request.");
303                     return;
304                 }
305                 synchronizerThread.addToQueue(new Runnable() {
306                     @Override
307                     public void run() {
308                         // Handling the response which includes retrieving the
309                         // attributes and updating the local model.
310                         RemoteResource resource = handleResponse(uid,
311                                 resourceModelN);
312                         if (null != resource) {
313                             // Notify the UI listeners
314                             UiListenerHandler.getInstance()
315                                     .getCompleteNotification(resource);
316                         }
317                     }
318                 });
319             }
320         };
321
322         putListener = new PutResponseListener() {
323
324             @Override
325             public void onPutResponse(final String uid,
326                     final SimulatorResult result,
327                     final SimulatorResourceModel resourceModelN) {
328                 if (result != SimulatorResult.SIMULATOR_OK) {
329                     Activator
330                             .getDefault()
331                             .getLogManager()
332                             .log(Level.ERROR.ordinal(),
333                                     new Date(),
334                                     "["
335                                             + result.toString()
336                                             + "] Received error response for PUT request.");
337                     return;
338                 }
339                 synchronizerThread.addToQueue(new Thread() {
340                     @Override
341                     public void run() {
342                         // Handling the response which includes retrieving the
343                         // attributes and updating the local model.
344                         RemoteResource resource = handleResponse(uid,
345                                 resourceModelN);
346                         if (null != resource) {
347                             // Notify the UI listeners
348                             UiListenerHandler.getInstance()
349                                     .putCompleteNotification(resource);
350                         }
351                     }
352                 });
353             }
354         };
355
356         postListener = new PostResponseListener() {
357             @Override
358             public void onPostResponse(final String uid,
359                     final SimulatorResult result,
360                     final SimulatorResourceModel resourceModelN) {
361                 if (result != SimulatorResult.SIMULATOR_OK) {
362                     Activator
363                             .getDefault()
364                             .getLogManager()
365                             .log(Level.ERROR.ordinal(),
366                                     new Date(),
367                                     "["
368                                             + result.toString()
369                                             + "] Received error response for POST request.");
370                     return;
371                 }
372                 synchronizerThread.addToQueue(new Runnable() {
373                     @Override
374                     public void run() {
375                         // Handling the response which includes retrieving the
376                         // attributes and updating the local model.
377                         RemoteResource resource = handleResponse(uid,
378                                 resourceModelN);
379                         if (null != resource) {
380                             // Notify the UI listeners
381                             UiListenerHandler.getInstance()
382                                     .postCompleteNotification(resource);
383                         }
384                     }
385                 });
386             }
387         };
388
389         observeListener = new ObserveNotificationListener() {
390
391             @Override
392             public void onObserveNotification(final String uid,
393                     final SimulatorResourceModel resourceModelN, final int seq) {
394                 synchronizerThread.addToQueue(new Runnable() {
395                     @Override
396                     public void run() {
397                         // Handling the response which includes retrieving the
398                         // attributes and updating the local model.
399                         RemoteResource resource = handleResponse(uid,
400                                 resourceModelN);
401                         if (null != resource) {
402                             // Notify the UI listeners
403                             UiListenerHandler.getInstance()
404                                     .observeCompleteNotification(resource);
405                         }
406                     }
407                 });
408             }
409         };
410
411         verifyListener = new VerificationListener() {
412
413             @Override
414             public void onVerificationStarted(final String uid, final int autoId) {
415                 synchronizerThread.addToQueue(new Runnable() {
416                     @Override
417                     public void run() {
418                         RemoteResource resource = getResource(uid);
419                         if (null == resource) {
420                             return;
421                         }
422                         // Update the automation status.
423                         resource.updateAutomationStatus(autoId, true);
424
425                         int autoType = resource.getAutomationtype(autoId);
426
427                         // Notify the listeners.
428                         UiListenerHandler.getInstance()
429                                 .verificationStartedNotification(resource,
430                                         autoType);
431                     }
432                 });
433             }
434
435             @Override
436             public void onVerificationCompleted(final String uid,
437                     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                         UiListenerHandler.getInstance()
452                                 .verificationCompletedNotification(resource,
453                                         autoType);
454                     }
455                 });
456             }
457
458             @Override
459             public void onVerificationAborted(final String uid, final int autoId) {
460                 synchronizerThread.addToQueue(new Runnable() {
461                     @Override
462                     public void run() {
463                         RemoteResource resource = getResource(uid);
464                         if (null == resource) {
465                             return;
466                         }
467                         // Update the automation status.
468                         resource.updateAutomationStatus(autoId, false);
469
470                         int autoType = resource.getAutomationtype(autoId);
471
472                         // Notify the listeners.
473                         UiListenerHandler.getInstance()
474                                 .verificationAbortedNotification(resource,
475                                         autoType);
476                     }
477                 });
478             }
479         };
480
481         synchronizerThread = new ResponseSynchronizerThread();
482         threadHandle = new Thread(synchronizerThread);
483         threadHandle.setName("Simulator Client Controller Event Queue");
484         threadHandle.start();
485     }
486
487     private RemoteResource handleResponse(String uid,
488             SimulatorResourceModel resourceModelN) {
489         if (null == uid || null == resourceModelN) {
490             return null;
491         }
492
493         // Update the local model
494         RemoteResource resource;
495         resource = getResource(uid);
496         if (null == resource) {
497             return null;
498         }
499
500         SimulatorResourceModel resourceModel = resource.getResourceModelRef();
501         if (null == resourceModel) {
502             resource.setResourceModelRef(resourceModelN);
503         } else {
504             resourceModel.update(resourceModelN);
505         }
506
507         resource.setResourceRepresentation(resourceModelN, false);
508
509         return resource;
510     }
511
512     public synchronized boolean isDeviceInfoExist(String host) {
513         DeviceAndPlatformInfo info = hostDeviceAndPlatformMap.get(host);
514         if (null == info) {
515             return false;
516         }
517         if (null == info.getDeviceInfo()) {
518             return false;
519         }
520         return true;
521     }
522
523     public synchronized boolean isPlatformInfoExist(String host) {
524         DeviceAndPlatformInfo info = hostDeviceAndPlatformMap.get(host);
525         if (null == info) {
526             return false;
527         }
528         if (null == info.getPlatformInfo()) {
529             return false;
530         }
531         return true;
532     }
533
534     private static class ResponseSynchronizerThread implements Runnable {
535
536         LinkedList<Runnable> responseQueue = new LinkedList<Runnable>();
537
538         @Override
539         public void run() {
540             while (!Thread.interrupted()) {
541                 synchronized (this) {
542                     try {
543                         while (responseQueue.isEmpty()) {
544                             this.wait();
545                             break;
546                         }
547                     } catch (InterruptedException e) {
548                         return;
549                     }
550                 }
551
552                 Runnable thread;
553                 synchronized (this) {
554                     thread = responseQueue.pop();
555                 }
556                 try {
557                     thread.run();
558                 } catch (Exception e) {
559                     if (e instanceof InterruptedException) {
560                         return;
561                     }
562                     e.printStackTrace();
563                 }
564             }
565         }
566
567         public void addToQueue(Runnable event) {
568             synchronized (this) {
569                 responseQueue.add(event);
570                 this.notify();
571             }
572         }
573     }
574
575     public void addResourcetoFavorites(RemoteResource resource) {
576         if (null == resource) {
577             return;
578         }
579         resource.setFavorite(true);
580         synchronized (favoriteResources) {
581             favoriteResources.add(resource);
582         }
583     }
584
585     public void removeResourceFromFavorites(RemoteResource resource) {
586         if (null == resource) {
587             return;
588         }
589         resource.setFavorite(false);
590         synchronized (favoriteResources) {
591             favoriteResources.remove(resource);
592         }
593     }
594
595     public void addResourceURItoFavorites(RemoteResource resource) {
596         if (null == resource) {
597             return;
598         }
599         synchronized (favoriteURIList) {
600             favoriteURIList.add(resource.getRemoteResourceRef().getURI());
601         }
602     }
603
604     public void removeResourceURIFromFavorites(RemoteResource resource) {
605         if (null == resource) {
606             return;
607         }
608         synchronized (favoriteURIList) {
609             favoriteURIList.remove(resource.getRemoteResourceRef().getURI());
610         }
611     }
612
613     public void addObservedResourceURI(String resourceURI) {
614         synchronized (observedResourceURIList) {
615             if (!observedResourceURIList.contains(resourceURI))
616                 observedResourceURIList.add(resourceURI);
617         }
618     }
619
620     public void removeObservedResourceURI(String resourceURI) {
621         synchronized (observedResourceURIList) {
622             observedResourceURIList.remove(resourceURI);
623         }
624     }
625
626     public boolean isResourceObserved(String resourceURI) {
627         boolean observed = false;
628         synchronized (observedResourceURIList) {
629             observed = observedResourceURIList.contains(resourceURI);
630         }
631         return observed;
632     }
633
634     public synchronized RemoteResource getCurrentResourceInSelection() {
635         return currentResourceInSelection;
636     }
637
638     public synchronized void setCurrentResourceInSelection(
639             RemoteResource resource) {
640         this.currentResourceInSelection = resource;
641     }
642
643     private void addResourceDetails(RemoteResource remoteResource) {
644         if (null != remoteResource) {
645             synchronized (resourceMap) {
646                 resourceMap.put(remoteResource.getRemoteResourceRef().getId(),
647                         remoteResource);
648             }
649         }
650     }
651
652     private boolean isUidExist(String uid) {
653         boolean exist;
654         synchronized (resourceMap) {
655             exist = resourceMap.containsKey(uid);
656         }
657         return exist;
658     }
659
660     private RemoteResource getResource(String uid) {
661         if (null == uid) {
662             return null;
663         }
664         RemoteResource resource;
665         synchronized (resourceMap) {
666             resource = resourceMap.get(uid);
667         }
668         return resource;
669     }
670
671     public synchronized Set<String> getLastKnownSearchTypes() {
672         return lastKnownSearchTypes;
673     }
674
675     public synchronized void setLastKnownSearchTypes(
676             Set<String> lastKnownSearchTypes) {
677         this.lastKnownSearchTypes = lastKnownSearchTypes;
678     }
679
680     public boolean findResourceRequest(Set<String> searchTypes) {
681         boolean result = false;
682         if (null == searchTypes || searchTypes.size() < 1) {
683             try {
684                 SimulatorManager.findResource(findResourceListener);
685                 result = true;
686             } catch (SimulatorException e) {
687                 Activator
688                         .getDefault()
689                         .getLogManager()
690                         .log(Level.ERROR.ordinal(), new Date(),
691                                 Utility.getSimulatorErrorString(e, null));
692             }
693         } else {
694             Iterator<String> searchItr = searchTypes.iterator();
695             String rType;
696             while (searchItr.hasNext()) {
697                 rType = searchItr.next();
698                 try {
699                     SimulatorManager.findResource(rType, findResourceListener);
700                     result = true;
701                 } catch (SimulatorException e) {
702                     Activator
703                             .getDefault()
704                             .getLogManager()
705                             .log(Level.ERROR.ordinal(), new Date(),
706                                     Utility.getSimulatorErrorString(e, null));
707                 }
708             }
709         }
710         return result;
711     }
712
713     public void deleteResources(final Set<String> searchTypes) {
714         synchronized (resourceMap) {
715             if (null == resourceMap && resourceMap.isEmpty()) {
716                 return;
717             }
718         }
719         new Thread() {
720             public void run() {
721                 if (null == searchTypes || searchTypes.size() < 1) {
722                     synchronized (resourceMap) {
723                         // Stop observing all the resources
724                         Iterator<String> itr = resourceMap.keySet().iterator();
725                         while (itr.hasNext()) {
726                             sendCancelObserveRequest(
727                                     resourceMap.get(itr.next()), false);
728                         }
729                         // Delete all cached details of resources
730                         resourceMap.clear();
731                         favoriteResources.clear();
732
733                         // Clearing the device and platform information
734                         hostDeviceAndPlatformMap.clear();
735                     }
736                     // Change the current resource in selection
737                     setCurrentResourceInSelection(null);
738                     UiListenerHandler.getInstance()
739                             .resourceSelectionChangedUINotification(null);
740                 } else {
741                     Iterator<String> typeItr = searchTypes.iterator();
742                     String resType;
743                     while (typeItr.hasNext()) {
744                         resType = typeItr.next();
745                         deleteResourcesByType(resType);
746
747                         // Change the current resource in selection
748                         updateCurrentResourceInSelection(searchTypes);
749                     }
750                 }
751             }
752         }.start();
753     }
754
755     private void updateCurrentResourceInSelection(Set<String> searchTypes) {
756         if (null == searchTypes || searchTypes.size() < 1) {
757             return;
758         }
759         RemoteResource resourceInSelection = getCurrentResourceInSelection();
760         if (null == resourceInSelection) {
761             return;
762         }
763         List<String> typesOfSelection = resourceInSelection
764                 .getRemoteResourceRef().getResourceTypes();
765         if (null == typesOfSelection || typesOfSelection.size() < 1) {
766             return;
767         }
768         Iterator<String> itr = typesOfSelection.iterator();
769         String type;
770         while (itr.hasNext()) {
771             type = itr.next();
772             if (searchTypes.contains(type)) {
773                 setCurrentResourceInSelection(null);
774                 UiListenerHandler.getInstance()
775                         .resourceSelectionChangedUINotification(null);
776                 break;
777             }
778         }
779     }
780
781     private void deleteResourcesByType(String resourceType) {
782         if (null == resourceType) {
783             return;
784         }
785         synchronized (resourceMap) {
786             Set<String> keySet = resourceMap.keySet();
787             if (null == keySet) {
788                 return;
789             }
790             Iterator<String> keyItr = keySet.iterator();
791             String uId;
792             RemoteResource resource;
793             boolean exist;
794             List<String> types;
795             while (keyItr.hasNext()) {
796                 uId = keyItr.next();
797                 resource = resourceMap.get(uId);
798                 if (null == resource) {
799                     continue;
800                 }
801                 types = resource.getRemoteResourceRef().getResourceTypes();
802                 if (null != types) {
803                     exist = types.contains(resourceType);
804                     if (exist) {
805                         // Cancel observing the resource.
806                         sendCancelObserveRequest(resource, false);
807                         // Remove the resource from favorites list.
808                         removeResourceFromFavorites(resource);
809                         // Remove the resource
810                         keyItr.remove();
811                         // Remove the device and platform information
812                         synchronized (hostDeviceAndPlatformMap) {
813                             hostDeviceAndPlatformMap.remove(resource
814                                     .getRemoteResourceRef().getHost());
815                         }
816                     }
817                 }
818             }
819         }
820     }
821
822     public void resourceSelectionChanged(final RemoteResource resource) {
823         new Thread() {
824             @Override
825             public void run() {
826                 setCurrentResourceInSelection(resource);
827                 // Notify all observers for resource selection change event
828                 UiListenerHandler.getInstance()
829                         .resourceSelectionChangedUINotification(resource);
830             }
831         }.start();
832     }
833
834     public List<MetaProperty> getDefaultProperties(RemoteResource resource) {
835         if (null != resource) {
836             String propName;
837             String propValue;
838
839             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
840
841             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
842                 propName = Constants.META_PROPERTIES[index];
843                 if (propName.equals(Constants.RESOURCE_URI)) {
844                     propValue = resource.getRemoteResourceRef().getURI();
845                 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
846                     propValue = resource.getRemoteResourceRef()
847                             .getConnectivityType().toString();
848                 } else if (propName.equals(Constants.ADDRESS)) {
849                     propValue = resource.getRemoteResourceRef().getHost();
850                 } else if (propName.equals(Constants.OBSERVABLE)) {
851                     propValue = Utility.getObservableInString(resource
852                             .getRemoteResourceRef().isObservable());
853                 } else if (propName.equals(Constants.RESOURCE_TYPES)) {
854                     Vector<String> resTypes = resource.getRemoteResourceRef()
855                             .getResourceTypes();
856                     if (null != resTypes && !resTypes.isEmpty()) {
857                         propValue = "";
858                         Iterator<String> itr = resTypes.iterator();
859                         while (itr.hasNext()) {
860                             propValue += itr.next();
861                             if (itr.hasNext()) {
862                                 propValue += ", ";
863                             }
864                         }
865                     } else {
866                         propValue = Constants.NOT_AVAILABLE;
867                     }
868                 } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
869                     Vector<String> interfaces = resource.getRemoteResourceRef()
870                             .getResourceInterfaces();
871                     if (null != interfaces && !interfaces.isEmpty()) {
872                         propValue = "";
873                         Iterator<String> itr = interfaces.iterator();
874                         while (itr.hasNext()) {
875                             propValue += itr.next();
876                             if (itr.hasNext()) {
877                                 propValue += ", ";
878                             }
879                         }
880                     } else {
881                         propValue = Constants.NOT_AVAILABLE;
882                     }
883                 } else {
884                     propValue = null;
885                 }
886                 if (null != propValue) {
887                     metaPropertyList.add(new MetaProperty(propName, propValue));
888                 }
889             }
890
891             return metaPropertyList;
892         }
893         return null;
894     }
895
896     public List<MetaProperty> getDeviceProperties() {
897         if (null == currentResourceInSelection) {
898             return null;
899         }
900
901         SimulatorRemoteResource remoteResource = currentResourceInSelection
902                 .getRemoteResourceRef();
903         if (null == remoteResource) {
904             return null;
905         }
906
907         String host = remoteResource.getHost();
908         if (null == host) {
909             return null;
910         }
911
912         if (!isDeviceInfoExist(host)) {
913             // Device Information
914             try {
915                 SimulatorManager.findDevices(host, deviceListener);
916             } catch (SimulatorException e) {
917                 Activator
918                         .getDefault()
919                         .getLogManager()
920                         .log(Level.ERROR.ordinal(), new Date(),
921                                 Utility.getSimulatorErrorString(e, null));
922             }
923             return null;
924         }
925
926         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
927         synchronized (hostDeviceAndPlatformMap) {
928             DeviceInfo devInfo = hostDeviceAndPlatformMap.get(host)
929                     .getDeviceInfo();
930             metaProperties.add(new MetaProperty(Constants.DEVICE_ID, devInfo
931                     .getID()));
932             metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, devInfo
933                     .getName()));
934             metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
935                     devInfo.getSpecVersion()));
936             metaProperties.add(new MetaProperty(Constants.DEVICE_DMV_VERSION,
937                     devInfo.getDataModelVersion()));
938         }
939
940         return metaProperties;
941     }
942
943     public List<MetaProperty> getPlatformProperties() {
944         if (null == currentResourceInSelection) {
945             return null;
946         }
947
948         SimulatorRemoteResource remoteResource = currentResourceInSelection
949                 .getRemoteResourceRef();
950         if (null == remoteResource) {
951             return null;
952         }
953
954         String host = remoteResource.getHost();
955         if (null == host) {
956             return null;
957         }
958
959         if (!isPlatformInfoExist(host)) {
960             // Platform Information
961             try {
962                 SimulatorManager.getPlatformInformation(host, platformListener);
963             } catch (SimulatorException e) {
964                 Activator
965                         .getDefault()
966                         .getLogManager()
967                         .log(Level.ERROR.ordinal(), new Date(),
968                                 Utility.getSimulatorErrorString(e, null));
969             }
970             return null;
971         }
972
973         List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
974         synchronized (hostDeviceAndPlatformMap) {
975             PlatformInfo platInfo = hostDeviceAndPlatformMap.get(host)
976                     .getPlatformInfo();
977             metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platInfo
978                     .getPlatformID()));
979             metaProperties.add(new MetaProperty(
980                     Constants.PLATFORM_MANUFAC_NAME, platInfo
981                             .getManufacturerName()));
982             metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
983                     platInfo.getManufacturerUrl()));
984             metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
985                     platInfo.getModelNumber()));
986             metaProperties.add(new MetaProperty(
987                     Constants.PLATFORM_DATE_OF_MANUFAC, platInfo
988                             .getDateOfManufacture()));
989             metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
990                     platInfo.getPlatformVersion()));
991             metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
992                     platInfo.getOperationSystemVersion()));
993             metaProperties.add(new MetaProperty(
994                     Constants.PLATFORM_HARDWARE_VERSION, platInfo
995                             .getHardwareVersion()));
996             metaProperties.add(new MetaProperty(
997                     Constants.PLATFORM_FIRMWARE_VERSION, platInfo
998                             .getFirmwareVersion()));
999             metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
1000                     platInfo.getSupportUrl()));
1001             metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
1002                     platInfo.getSystemTime()));
1003         }
1004         return metaProperties;
1005     }
1006
1007     public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
1008         if (null == resource) {
1009             return null;
1010         }
1011         Map<String, Boolean> autoStatus = new HashMap<String, Boolean>();
1012         autoStatus.put(Constants.GET, resource.isGetAutomtnInProgress());
1013         autoStatus.put(Constants.PUT, resource.isPutAutomtnInProgress());
1014         autoStatus.put(Constants.POST, resource.isPostAutomtnInProgress());
1015         return autoStatus;
1016     }
1017
1018     public List<RemoteResource> getResourceList() {
1019         List<RemoteResource> resourceList = new ArrayList<RemoteResource>();
1020         synchronized (resourceMap) {
1021             Set<String> idSet = resourceMap.keySet();
1022             Iterator<String> idItr = idSet.iterator();
1023             RemoteResource resource;
1024             while (idItr.hasNext()) {
1025                 resource = resourceMap.get(idItr.next());
1026                 if (null != resource) {
1027                     resourceList.add(resource);
1028                 }
1029             }
1030         }
1031         // Sort the list
1032         Collections.sort(resourceList, new Comparator<RemoteResource>() {
1033             public int compare(RemoteResource res1, RemoteResource res2) {
1034                 String s1 = res1.getRemoteResourceRef().getURI();
1035                 String s2 = res2.getRemoteResourceRef().getURI();
1036
1037                 String s1Part = s1.replaceAll("\\d", "");
1038                 String s2Part = s2.replaceAll("\\d", "");
1039
1040                 if (s1Part.equalsIgnoreCase(s2Part)) {
1041                     return extractInt(s1) - extractInt(s2);
1042                 }
1043                 return s1.compareTo(s2);
1044             }
1045
1046             int extractInt(String s) {
1047                 String num = s.replaceAll("\\D", "");
1048                 // return 0 if no digits found
1049                 return num.isEmpty() ? 0 : Integer.parseInt(num);
1050             }
1051         });
1052
1053         return resourceList;
1054     }
1055
1056     public List<RemoteResource> getFavResourceList() {
1057         List<RemoteResource> resourceList;
1058         synchronized (favoriteResources) {
1059             resourceList = new ArrayList<RemoteResource>(favoriteResources);
1060         }
1061         return resourceList;
1062     }
1063
1064     public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
1065         if (null == att) {
1066             return null;
1067         }
1068
1069         AttributeValue val = att.value();
1070         if (null == val) {
1071             return null;
1072         }
1073
1074         List<String> values = new ArrayList<String>();
1075
1076         TypeInfo type = val.typeInfo();
1077
1078         AttributeProperty prop = att.property();
1079         if (null == prop || prop.type().ordinal() == Type.UNKNOWN.ordinal()) {
1080             values.add(Utility.getAttributeValueAsString(val));
1081             return values;
1082         }
1083
1084         Type valuesType = prop.type();
1085
1086         if (type.mType != ValueType.RESOURCEMODEL) {
1087             if (type.mType == ValueType.ARRAY) {
1088                 if (type.mDepth == 1) {
1089                     AttributeProperty childProp = prop.getChildProperty();
1090                     if (null != childProp) {
1091                         valuesType = childProp.type();
1092                         if (valuesType.ordinal() == Type.RANGE.ordinal()) {
1093                             List<String> list = getRangeForPrimitiveNonArrayAttributes(
1094                                     childProp, type.mBaseType);
1095                             if (null != list) {
1096                                 values.addAll(list);
1097                             }
1098                         } else if (valuesType.ordinal() == Type.VALUESET
1099                                 .ordinal()) {
1100                             List<String> list = getAllowedValuesForPrimitiveNonArrayAttributes(
1101                                     childProp.valueSet(), type.mBaseType);
1102                             if (null != list) {
1103                                 values.addAll(list);
1104                             }
1105                         }
1106                     }
1107                 }
1108             } else {
1109                 if (valuesType.ordinal() == Type.RANGE.ordinal()) {
1110                     List<String> list = getRangeForPrimitiveNonArrayAttributes(
1111                             prop, type.mType);
1112                     if (null != list) {
1113                         values.addAll(list);
1114                     }
1115                 } else if (valuesType.ordinal() == Type.VALUESET.ordinal()) {
1116                     List<String> list = getAllowedValuesForPrimitiveNonArrayAttributes(
1117                             prop.valueSet(), type.mType);
1118                     if (null != list) {
1119                         values.addAll(list);
1120                     }
1121                 }
1122             }
1123         }
1124
1125         if (values.isEmpty()) {
1126             values.add(Utility.getAttributeValueAsString(val));
1127         }
1128
1129         return values;
1130     }
1131
1132     public List<String> getRangeForPrimitiveNonArrayAttributes(
1133             AttributeProperty prop, ValueType type) {
1134         if (null == prop) {
1135             return null;
1136         }
1137
1138         if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) {
1139             return null;
1140         }
1141
1142         List<String> values = new ArrayList<String>();
1143         switch (type) {
1144             case INTEGER:
1145                 int min = (int) prop.min();
1146                 int max = (int) prop.max();
1147                 for (int iVal = min; iVal <= max; iVal++) {
1148                     values.add(String.valueOf(iVal));
1149                 }
1150                 break;
1151             case DOUBLE:
1152                 double minD = (double) prop.min();
1153                 double maxD = (double) prop.max();
1154                 for (double iVal = minD; iVal <= maxD; iVal = iVal + 1.0) {
1155                     values.add(String.valueOf(iVal));
1156                 }
1157                 break;
1158             default:
1159         }
1160         return values;
1161     }
1162
1163     public List<String> getAllowedValuesForPrimitiveNonArrayAttributes(
1164             AttributeValue[] attValues, ValueType type) {
1165         if (null == attValues || attValues.length < 1) {
1166             return null;
1167         }
1168
1169         if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) {
1170             return null;
1171         }
1172
1173         Object obj;
1174         List<String> values = new ArrayList<String>();
1175         for (AttributeValue val : attValues) {
1176             if (null == val) {
1177                 continue;
1178             }
1179             obj = val.get();
1180             if (null == obj) {
1181                 continue;
1182             }
1183             values.add(String.valueOf(obj));
1184         }
1185         return values;
1186     }
1187
1188     public void sendGetRequest(RemoteResource resource) {
1189         if (null == resource) {
1190             return;
1191         }
1192         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1193         if (null == resourceN) {
1194             return;
1195         }
1196
1197         try {
1198             resourceN.get(null, getListener);
1199         } catch (SimulatorException e) {
1200             Activator
1201                     .getDefault()
1202                     .getLogManager()
1203                     .log(Level.ERROR.ordinal(), new Date(),
1204                             Utility.getSimulatorErrorString(e, null));
1205         }
1206     }
1207
1208     public void sendPutRequest(RemoteResource resource,
1209             SimulatorResourceModel model) {
1210         if (null == resource || null == model) {
1211             return;
1212         }
1213         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1214         if (null == resourceN) {
1215             return;
1216         }
1217         try {
1218             resourceN.put(null, model, putListener);
1219         } catch (Exception e) {
1220             String addlInfo;
1221             addlInfo = "Invalid Attribute Value. Cannot send PUT request.";
1222             Activator
1223                     .getDefault()
1224                     .getLogManager()
1225                     .log(Level.ERROR.ordinal(), new Date(),
1226                             Utility.getSimulatorErrorString(e, addlInfo));
1227         }
1228     }
1229
1230     public void sendPostRequest(RemoteResource resource,
1231             SimulatorResourceModel model) {
1232         if (null == resource || null == model) {
1233             return;
1234         }
1235         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1236         if (null == resourceN) {
1237             return;
1238         }
1239         try {
1240             resourceN.post(null, model, postListener);
1241         } catch (Exception e) {
1242             String addlInfo;
1243             addlInfo = "Invalid Attribute Value. Cannot send POST request.";
1244             Activator
1245                     .getDefault()
1246                     .getLogManager()
1247                     .log(Level.ERROR.ordinal(), new Date(),
1248                             Utility.getSimulatorErrorString(e, addlInfo));
1249         }
1250     }
1251
1252     public boolean sendObserveRequest(RemoteResource resource) {
1253         if (null == resource) {
1254             return false;
1255         }
1256         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1257         if (null == resourceN) {
1258             return false;
1259         }
1260         try {
1261             resourceN.startObserve(null, observeListener);
1262             resource.setObserved(true);
1263             // Add observed resource URI to show the proper status after every
1264             // find/refresh operations.
1265             addObservedResourceURI(resource.getRemoteResourceRef().getURI());
1266         } catch (SimulatorException e) {
1267             Activator
1268                     .getDefault()
1269                     .getLogManager()
1270                     .log(Level.ERROR.ordinal(), new Date(),
1271                             Utility.getSimulatorErrorString(e, null));
1272             return false;
1273         }
1274         return true;
1275     }
1276
1277     public boolean sendCancelObserveRequest(RemoteResource resource,
1278             boolean removeEntry) {
1279         if (null == resource || !resource.isObserved()) {
1280             return false;
1281         }
1282         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1283         if (null == resourceN) {
1284             return false;
1285         }
1286         try {
1287             resourceN.stopObserve();
1288             resource.setObserved(false);
1289             // Remove observed resource URI to show the proper status after
1290             // every find/refresh operations.
1291             if (removeEntry)
1292                 removeObservedResourceURI(resource.getRemoteResourceRef()
1293                         .getURI());
1294         } catch (SimulatorException e) {
1295             Activator
1296                     .getDefault()
1297                     .getLogManager()
1298                     .log(Level.ERROR.ordinal(), new Date(),
1299                             Utility.getSimulatorErrorString(e, null));
1300             return false;
1301         }
1302         return true;
1303     }
1304
1305     public void startAutomationRequest(VerificationType reqType,
1306             RemoteResource resource) {
1307         if (null == resource) {
1308             return;
1309         }
1310         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1311         if (null == resourceN) {
1312             return;
1313         }
1314         if (null == reqType) {
1315             return;
1316         }
1317         int autoId;
1318         try {
1319             autoId = resourceN.startVerification(reqType, verifyListener);
1320             if (autoId != -1) {
1321                 if (reqType == VerificationType.GET) {
1322                     // resource.setGetAutomtnInProgress(true);
1323                     resource.setGetAutomtnId(autoId);
1324                 } else if (reqType == VerificationType.PUT) {
1325                     // resource.setPutAutomtnInProgress(true);
1326                     resource.setPutAutomtnId(autoId);
1327                 } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
1328                     // resource.setPostAutomtnInProgress(true);
1329                     resource.setPostAutomtnId(autoId);
1330                 }
1331             }
1332         } catch (SimulatorException e) {
1333             Activator
1334                     .getDefault()
1335                     .getLogManager()
1336                     .log(Level.ERROR.ordinal(), new Date(),
1337                             Utility.getSimulatorErrorString(e, null));
1338         }
1339     }
1340
1341     public void stopAutomationRequest(VerificationType reqType,
1342             RemoteResource resource) {
1343         if (null == resource) {
1344             return;
1345         }
1346         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1347         if (null == resourceN) {
1348             return;
1349         }
1350         int autoId;
1351         if (reqType == VerificationType.GET) {
1352             resource.setGetAutomtnInProgress(false);
1353             autoId = resource.getGetAutomtnId();
1354         } else if (reqType == VerificationType.PUT) {
1355             resource.setPutAutomtnInProgress(false);
1356             autoId = resource.getPutAutomtnId();
1357         } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
1358             resource.setPostAutomtnInProgress(false);
1359             autoId = resource.getPostAutomtnId();
1360         }
1361         try {
1362             resourceN.stopVerification(autoId);
1363         } catch (SimulatorException e) {
1364             Activator
1365                     .getDefault()
1366                     .getLogManager()
1367                     .log(Level.ERROR.ordinal(), new Date(),
1368                             Utility.getSimulatorErrorString(e, null));
1369         }
1370     }
1371
1372     public boolean setConfigFilePath(RemoteResource resource,
1373             String configFilePath) throws SimulatorException {
1374         if (null == resource) {
1375             return false;
1376         }
1377         SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1378         if (null == resourceN) {
1379             return false;
1380         }
1381         try {
1382             SimulatorResourceModel configuredResourceModel;
1383             configuredResourceModel = resourceN.setConfigInfo(configFilePath);
1384             if (null == configuredResourceModel) {
1385                 return false;
1386             }
1387
1388             // Store the resource model in the local cache
1389             SimulatorResourceModel resourceModel = resource
1390                     .getResourceModelRef();
1391             if (null != resourceModel) {
1392                 configuredResourceModel.update(resourceModel);
1393             }
1394             resource.setResourceModelRef(configuredResourceModel);
1395         } catch (SimulatorException e) {
1396             Activator
1397                     .getDefault()
1398                     .getLogManager()
1399                     .log(Level.ERROR.ordinal(), new Date(),
1400                             Utility.getSimulatorErrorString(e, null));
1401             throw e;
1402         }
1403         // Update the status
1404         resource.setConfigUploaded(true);
1405
1406         // Notify the UI listeners
1407         UiListenerHandler.getInstance().configUploadedNotification(resource);
1408
1409         return true;
1410     }
1411
1412     public void shutdown() {
1413     }
1414 }