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