Java SDK and Eclipse plugin for simulator.
[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.net.URL;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.Date;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30
31 import oic.simulator.clientcontroller.Activator;
32 import oic.simulator.clientcontroller.listener.IConfigurationUpload;
33 import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
34 import oic.simulator.clientcontroller.listener.IGetUIListener;
35 import oic.simulator.clientcontroller.listener.IObserveUIListener;
36 import oic.simulator.clientcontroller.listener.IPostUIListener;
37 import oic.simulator.clientcontroller.listener.IPutUIListener;
38 import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
39 import oic.simulator.clientcontroller.listener.IVerificationUIListener;
40 import oic.simulator.clientcontroller.remoteresource.MetaProperty;
41 import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
42 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
43 import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
44 import oic.simulator.clientcontroller.utils.Constants;
45 import oic.simulator.clientcontroller.utils.Utility;
46
47 import org.eclipse.jface.resource.ImageDescriptor;
48 import org.eclipse.swt.graphics.Image;
49 import org.oic.simulator.ILogger.Level;
50 import org.oic.simulator.ResourceAttribute;
51 import org.oic.simulator.ResourceAttribute.Range;
52 import org.oic.simulator.ResourceAttribute.Type;
53 import org.oic.simulator.SimulatorException;
54 import org.oic.simulator.SimulatorManager;
55 import org.oic.simulator.SimulatorResourceModel;
56 import org.oic.simulator.clientcontroller.IFindResourceListener;
57 import org.oic.simulator.clientcontroller.IGetListener;
58 import org.oic.simulator.clientcontroller.IObserveListener;
59 import org.oic.simulator.clientcontroller.IPostListener;
60 import org.oic.simulator.clientcontroller.IPutListener;
61 import org.oic.simulator.clientcontroller.IVerificationListener;
62 import org.oic.simulator.clientcontroller.SimulatorObserveType;
63 import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
64 import org.oic.simulator.clientcontroller.SimulatorVerificationType;
65
66 /**
67  * This class acts as an interface between the simulator java SDK and the
68  * various UI modules. It maintains all the details of resources and provides
69  * other UI modules with the information required. It also handles responses for find,
70  * GET, PUT, POST, Observe and automatic verification operations from native layer and propagates
71  * those events to the registered UI listeners.
72  */
73 public class ResourceManager {
74
75     private Set<String>                               lastKnownSearchTypes;
76
77     private RemoteResource                            currentResourceInSelection;
78
79     private IFindResourceListener                     findResourceListener;
80     private IGetListener                              getListener;
81     private IPutListener                              putListener;
82     private IPostListener                             postListener;
83     private IObserveListener                          observeListener;
84     private IVerificationListener                     verifyListener;
85
86     private ResponseSynchronizerThread                synchronizerThread;
87
88     private Thread                                    threadHandle;
89
90     private List<IFindResourceUIListener>             findResourceUIListeners;
91     private List<IResourceSelectionChangedUIListener> resourceSelectionChangedUIListeners;
92     private List<IGetUIListener>                      getUIListeners;
93     private List<IPutUIListener>                      putUIListeners;
94     private List<IPostUIListener>                     postUIListeners;
95     private List<IObserveUIListener>                  observeUIListeners;
96     private List<IVerificationUIListener>             verificationUIListeners;
97     private List<IConfigurationUpload>                configUploadUIListeners;
98
99     // Map with Server ID as key and the complete object as the value
100     private Map<String, RemoteResource>               resourceMap;
101     private List<RemoteResource>                      favoriteResources;
102     // TODO: Temporarily maintaining a list of favorite resource URIs.
103     private List<String>                              favoriteURIList;
104
105     public ResourceManager() {
106         resourceMap = new HashMap<String, RemoteResource>();
107         favoriteResources = new ArrayList<RemoteResource>();
108         favoriteURIList = new ArrayList<String>();
109         findResourceUIListeners = new ArrayList<IFindResourceUIListener>();
110         resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
111         getUIListeners = new ArrayList<IGetUIListener>();
112         putUIListeners = new ArrayList<IPutUIListener>();
113         postUIListeners = new ArrayList<IPostUIListener>();
114         observeUIListeners = new ArrayList<IObserveUIListener>();
115         verificationUIListeners = new ArrayList<IVerificationUIListener>();
116         configUploadUIListeners = new ArrayList<IConfigurationUpload>();
117
118         findResourceListener = new IFindResourceListener() {
119
120             @Override
121             public void onResourceCallback(
122                     final SimulatorRemoteResource resourceN) {
123                 synchronizerThread.addToQueue(new Runnable() {
124                     @Override
125                     public void run() {
126                         System.out.println("onResourceCallback() entry");
127                         if (null == resourceN) {
128                             return;
129                         }
130                         // If resource already exist, then ignore it.
131                         String uid = resourceN.getId();
132                         if (null == uid) {
133                             return;
134                         }
135                         boolean exist = isUidExist(uid);
136                         if (exist) {
137                             System.out.println("Duplicate resource found: ["
138                                     + uid + "]");
139                             return;
140                         }
141
142                         // Fetch the resource data
143                         RemoteResource resource = fetchResourceDetails(resourceN);
144                         if (null == resource) {
145                             return;
146                         }
147
148                         resource.setResource(resourceN);
149
150                         // Add the resource in local data structure
151                         addResourceDetails(resource);
152
153                         // Add resource to favorite list
154                         String uri = resource.getResourceURI();
155                         if (null != uri) {
156                             if (favoriteURIList.contains(uri)) {
157                                 addResourcetoFavorites(resource);
158                             }
159                         }
160                         // Notify the UI listener
161                         newResourceFoundNotification(resource);
162
163                         // Send an initial GET request to get the resource
164                         // attributes
165                         try {
166                             resourceN.get(null, getListener);
167                         } catch (SimulatorException e) {
168                             Activator
169                                     .getDefault()
170                                     .getLogManager()
171                                     .log(Level.ERROR.ordinal(),
172                                             new Date(),
173                                             "[" + e.getClass().getSimpleName()
174                                                     + "]" + e.code().toString()
175                                                     + "-" + e.message());
176                         }
177                     }
178                 });
179             }
180         };
181
182         getListener = new IGetListener() {
183             @Override
184             public void onGetCompleted(final String uid,
185                     final SimulatorResourceModel resourceModelN) {
186                 synchronizerThread.addToQueue(new Runnable() {
187                     @Override
188                     public void run() {
189                         // Handling the response which includes retrieving the
190                         // attributes and updating the local model.
191                         RemoteResource resource = handleResponse(uid,
192                                 resourceModelN);
193                         if (null != resource) {
194                             // Notify the UI listeners
195                             getCompleteNotification(resource);
196                         }
197                     }
198                 });
199             }
200
201             @Override
202             public void onGetFailed(Throwable th) {
203                 synchronizerThread.addToQueue(new Runnable() {
204                     @Override
205                     public void run() {
206                     }
207                 });
208             }
209         };
210
211         putListener = new IPutListener() {
212
213             @Override
214             public void onPutCompleted(final String uid,
215                     final SimulatorResourceModel resourceModelN) {
216                 synchronizerThread.addToQueue(new Thread() {
217                     @Override
218                     public void run() {
219                         // Handling the response which includes retrieving the
220                         // attributes and updating the local model.
221                         RemoteResource resource = handleResponse(uid,
222                                 resourceModelN);
223                         if (null != resource) {
224                             // Notify the UI listeners
225                             putCompleteNotification(resource);
226                         }
227                     }
228                 });
229             }
230
231             @Override
232             public void onPutFailed(Throwable th) {
233                 synchronizerThread.addToQueue(new Runnable() {
234                     @Override
235                     public void run() {
236                     }
237                 });
238             }
239         };
240
241         postListener = new IPostListener() {
242             @Override
243             public void onPostCompleted(final String uid,
244                     final SimulatorResourceModel resourceModelN) {
245                 synchronizerThread.addToQueue(new Runnable() {
246                     @Override
247                     public void run() {
248                         // Handling the response which includes retrieving the
249                         // attributes and updating the local model.
250                         RemoteResource resource = handleResponse(uid,
251                                 resourceModelN);
252                         if (null != resource) {
253                             // Notify the UI listeners
254                             postCompleteNotification(resource);
255                         }
256                     }
257                 });
258             }
259
260             @Override
261             public void onPostFailed(Throwable th) {
262                 synchronizerThread.addToQueue(new Runnable() {
263                     @Override
264                     public void run() {
265                     }
266                 });
267             }
268         };
269
270         observeListener = new IObserveListener() {
271
272             @Override
273             public void onObserveCompleted(final String uid,
274                     final SimulatorResourceModel resourceModelN, final int seq) {
275                 System.out.println("ResourceManager: onObserveCallback()");
276                 synchronizerThread.addToQueue(new Runnable() {
277                     @Override
278                     public void run() {
279                         // Handling the response which includes retrieving the
280                         // attributes and updating the local model.
281                         RemoteResource resource = handleResponse(uid,
282                                 resourceModelN);
283                         if (null != resource) {
284                             // Notify the UI listeners
285                             observeCompleteNotification(resource);
286                         }
287                     }
288                 });
289             }
290
291             @Override
292             public void onObserveFailed(Throwable th) {
293                 // TODO Auto-generated method stub
294             }
295         };
296
297         verifyListener = new IVerificationListener() {
298
299             @Override
300             public void onVerificationStarted(final String uid, final int autoId) {
301                 System.out.println("onVefificationStarted: " + autoId);
302                 synchronizerThread.addToQueue(new Runnable() {
303                     @Override
304                     public void run() {
305                         RemoteResource resource = getResource(uid);
306                         if (null == resource) {
307                             return;
308                         }
309                         // Update the automation status.
310                         resource.updateAutomationStatus(autoId, true);
311
312                         int autoType = resource.getAutomationtype(autoId);
313
314                         // Notify the listeners.
315                         verificationStartedNotification(resource, autoType);
316                     }
317                 });
318             }
319
320             @Override
321             public void onVerificationCompleted(final String uid,
322                     final int autoId) {
323                 System.out.println("onVefificationCompleted: " + autoId);
324                 synchronizerThread.addToQueue(new Runnable() {
325                     @Override
326                     public void run() {
327                         RemoteResource resource = getResource(uid);
328                         if (null == resource) {
329                             return;
330                         }
331                         // Update the automation status.
332                         resource.updateAutomationStatus(autoId, false);
333
334                         int autoType = resource.getAutomationtype(autoId);
335
336                         // Notify the listeners.
337                         verificationCompletedNotification(resource, autoType);
338                     }
339                 });
340             }
341
342             @Override
343             public void onVerificationAborted(final String uid, final int autoId) {
344                 System.out.println("onVefificationAborted: " + autoId);
345                 synchronizerThread.addToQueue(new Runnable() {
346                     @Override
347                     public void run() {
348                         RemoteResource resource = getResource(uid);
349                         if (null == resource) {
350                             return;
351                         }
352                         // Update the automation status.
353                         resource.updateAutomationStatus(autoId, false);
354
355                         int autoType = resource.getAutomationtype(autoId);
356
357                         // Notify the listeners.
358                         verificationAbortedNotification(resource, autoType);
359                     }
360                 });
361             }
362         };
363
364         synchronizerThread = new ResponseSynchronizerThread();
365         threadHandle = new Thread(synchronizerThread);
366         threadHandle.setName("Simulator Client Controller Event Queue");
367         threadHandle.start();
368     }
369
370     private RemoteResource handleResponse(String uid,
371             SimulatorResourceModel resourceModelN) {
372         if (null == uid || null == resourceModelN) {
373             return null;
374         }
375
376         // Update the local model
377         RemoteResource resource;
378         resource = getResource(uid);
379         if (null == resource) {
380             return null;
381         }
382
383         resource.setResourceModel(resourceModelN);
384         Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModelN);
385
386         // TODO: For debugging
387         RemoteResourceAttribute.printAttributes(attributeMap);
388         System.out.println("Attributes found: " + (null != attributeMap));
389         System.out.println("No of attributes: " + attributeMap.size());
390
391         resource.setResourceAttributesMap(attributeMap);
392         return resource;
393     }
394
395     private static class ResponseSynchronizerThread implements Runnable {
396
397         LinkedList<Runnable> responseQueue = new LinkedList<Runnable>();
398
399         @Override
400         public void run() {
401             while (!Thread.interrupted()) {
402                 synchronized (this) {
403                     try {
404                         while (responseQueue.isEmpty()) {
405                             this.wait();
406                             break;
407                         }
408                     } catch (InterruptedException e) {
409                         return;
410                     }
411                 }
412
413                 Runnable thread;
414                 synchronized (this) {
415                     thread = responseQueue.pop();
416                 }
417                 try {
418                     thread.run();
419                 } catch (Exception e) {
420                     if (e instanceof InterruptedException) {
421                         return;
422                     }
423                     e.printStackTrace();
424                 }
425             }
426         }
427
428         public void addToQueue(Runnable event) {
429             synchronized (this) {
430                 responseQueue.add(event);
431                 this.notify();
432             }
433         }
434     }
435
436     public void addResourceSelectionChangedUIListener(
437             IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
438         synchronized (resourceSelectionChangedUIListeners) {
439             resourceSelectionChangedUIListeners
440                     .add(resourceSelectionChangedUIListener);
441         }
442     }
443
444     public void addGetUIListener(IGetUIListener getUIListener) {
445         synchronized (getUIListeners) {
446             getUIListeners.add(getUIListener);
447         }
448     }
449
450     public void addPutUIListener(IPutUIListener putUIListener) {
451         synchronized (putUIListeners) {
452             putUIListeners.add(putUIListener);
453         }
454     }
455
456     public void addPostUIListener(IPostUIListener postUIListener) {
457         synchronized (postUIListeners) {
458             postUIListeners.add(postUIListener);
459         }
460     }
461
462     public void addObserveUIListener(IObserveUIListener observeUIListener) {
463         synchronized (observeUIListeners) {
464             observeUIListeners.add(observeUIListener);
465         }
466     }
467
468     public void addVerificationUIListener(
469             IVerificationUIListener verificationUIListener) {
470         synchronized (verificationUIListeners) {
471             verificationUIListeners.add(verificationUIListener);
472         }
473     }
474
475     public void addConfigUploadUIListener(IConfigurationUpload configListener) {
476         synchronized (configUploadUIListeners) {
477             configUploadUIListeners.add(configListener);
478         }
479     }
480
481     public void removeResourceSelectionChangedUIListener(
482             IResourceSelectionChangedUIListener listener) {
483         synchronized (resourceSelectionChangedUIListeners) {
484             if (null != listener
485                     && resourceSelectionChangedUIListeners.size() > 0) {
486                 resourceSelectionChangedUIListeners.remove(listener);
487             }
488         }
489     }
490
491     public void removeGetUIListener(IGetUIListener getUIListener) {
492         synchronized (getUIListeners) {
493             getUIListeners.remove(getUIListener);
494         }
495     }
496
497     public void removePutUIListener(IPutUIListener putUIListener) {
498         synchronized (putUIListeners) {
499             putUIListeners.remove(putUIListener);
500         }
501     }
502
503     public void removePostUIListener(IPostUIListener postUIListener) {
504         synchronized (postUIListeners) {
505             postUIListeners.remove(postUIListener);
506         }
507     }
508
509     public void removeObserveUIListener(IObserveUIListener observeUIListener) {
510         synchronized (observeUIListeners) {
511             observeUIListeners.remove(observeUIListener);
512         }
513     }
514
515     public void removeVerificationUIListener(
516             IVerificationUIListener verificationUIListener) {
517         synchronized (verificationUIListeners) {
518             verificationUIListeners.remove(verificationUIListener);
519         }
520     }
521
522     public void removeConfigUploadUIListener(IConfigurationUpload configListener) {
523         synchronized (configUploadUIListeners) {
524             configUploadUIListeners.remove(configListener);
525         }
526     }
527
528     public void addResourcetoFavorites(RemoteResource resource) {
529         if (null == resource) {
530             return;
531         }
532         resource.setFavorite(true);
533         synchronized (favoriteResources) {
534             favoriteResources.add(resource);
535             favoriteURIList.add(resource.getResourceURI());
536         }
537     }
538
539     public void removeResourceFromFavorites(RemoteResource resource) {
540         if (null == resource) {
541             return;
542         }
543         resource.setFavorite(false);
544         synchronized (favoriteResources) {
545             favoriteResources.remove(resource);
546         }
547     }
548
549     public void removeResourceURIFromFavorites(RemoteResource resource) {
550         if (null == resource) {
551             return;
552         }
553         synchronized (favoriteURIList) {
554             favoriteURIList.remove(resource.getResourceURI());
555         }
556     }
557
558     public synchronized RemoteResource getCurrentResourceInSelection() {
559         return currentResourceInSelection;
560     }
561
562     public synchronized void setCurrentResourceInSelection(
563             RemoteResource resource) {
564         this.currentResourceInSelection = resource;
565     }
566
567     private void addResourceDetails(RemoteResource remoteResource) {
568         if (null != remoteResource) {
569             synchronized (resourceMap) {
570                 resourceMap.put(remoteResource.getuId(), remoteResource);
571             }
572         }
573     }
574
575     public void addFindresourceUIListener(IFindResourceUIListener listener) {
576         if (null == listener) {
577             return;
578         }
579         synchronized (findResourceUIListeners) {
580             findResourceUIListeners.add(listener);
581         }
582     }
583
584     public void removeFindresourceUIListener(IFindResourceUIListener listener) {
585         if (null == listener) {
586             return;
587         }
588         synchronized (findResourceUIListeners) {
589             findResourceUIListeners.remove(listener);
590         }
591     }
592
593     private RemoteResource fetchResourceDetails(
594             SimulatorRemoteResource remoteResourceN) {
595         if (null == remoteResourceN) {
596             return null;
597         }
598         RemoteResource remoteResource = new RemoteResource();
599         remoteResource.setuId(remoteResourceN.getId());
600         remoteResource.setResourceURI(remoteResourceN.getUri());
601         remoteResource.setHost(remoteResourceN.getHost());
602         remoteResource.setResourceTypes(remoteResourceN.getResourceTypes());
603         remoteResource.setResourceInterfaces(remoteResourceN
604                 .getResourceInterfaces());
605         remoteResource.setConnectivityType(remoteResourceN
606                 .getConnectivityType());
607         remoteResource.setObservable(remoteResourceN.getIsObservable());
608         return remoteResource;
609     }
610
611     private boolean isUidExist(String uid) {
612         boolean exist;
613         synchronized (resourceMap) {
614             exist = resourceMap.containsKey(uid);
615         }
616         return exist;
617     }
618
619     private RemoteResource getResource(String uid) {
620         if (null == uid) {
621             return null;
622         }
623         RemoteResource resource;
624         synchronized (resourceMap) {
625             resource = resourceMap.get(uid);
626         }
627         return resource;
628     }
629
630     private Map<String, RemoteResourceAttribute> fetchResourceAttributesFromModel(
631             SimulatorResourceModel resourceModelN) {
632         Map<String, RemoteResourceAttribute> resourceAttributeMap = null;
633         if (null != resourceModelN) {
634             Map<String, ResourceAttribute> attributeMapN;
635             attributeMapN = resourceModelN.getAttributes();
636             if (null != attributeMapN) {
637                 resourceAttributeMap = new HashMap<String, RemoteResourceAttribute>();
638
639                 Set<String> attNameSet = attributeMapN.keySet();
640                 String attName;
641                 Object attValueObj;
642                 ResourceAttribute attributeN;
643                 RemoteResourceAttribute attribute;
644                 Iterator<String> attNameItr = attNameSet.iterator();
645                 while (attNameItr.hasNext()) {
646                     attName = attNameItr.next();
647                     attributeN = attributeMapN.get(attName);
648                     if (null != attributeN) {
649                         attribute = new RemoteResourceAttribute();
650                         attribute.setResourceAttribute(attributeN);
651                         attribute.setAttributeName(attName);
652
653                         attValueObj = attributeN.getValue();
654                         if (null != attValueObj) {
655                             attribute.setAttributeValue(attValueObj);
656                         }
657
658                         // Set the attribute type
659                         attribute.setAttValBaseType(attributeN.getBaseType());
660                         attribute.setAttValType(attributeN.getType());
661
662                         // Set the range and allowed values
663                         Range range = attributeN.getRange();
664                         if (null != range) {
665                             attribute.setMinValue(range.getMin());
666                             attribute.setMaxValue(range.getMax());
667                         } else {
668                             Object[] values = attributeN.getAllowedValues();
669                             if (null != values && values.length > 0) {
670                                 List<Object> valueList = new ArrayList<Object>();
671                                 for (Object obj : values) {
672                                     valueList.add(obj);
673                                 }
674                                 attribute.setAllowedValues(valueList);
675                             }
676                             /*
677                              * Type baseType = attribute.getAttValBaseType();
678                              * 
679                              * if(baseType == Type.INT) { //int[] values =
680                              * attributeN.getAllowedValues();
681                              * attribute.setAllowedValues
682                              * (attributeN.getAllowedValues()); } else
683                              * if(baseType == Type.DOUBLE) { double[] values =
684                              * attributeN.getAllowedValues();
685                              * attribute.setAllowedValues
686                              * (Utility.converArrayToList(values)); } else
687                              * if(baseType == Type.BOOL) { //boolean[] values =
688                              * attributeN.getAllowedValues(); List<Object> obj =
689                              * new ArrayList<Object>(); obj.add(true);
690                              * obj.add(false); attribute.setAllowedValues(obj);
691                              * } else if(baseType == Type.STRING) { String[]
692                              * values = attributeN.getAllowedValues();
693                              * attribute.
694                              * setAllowedValues(Utility.converArrayToList
695                              * (values)); }
696                              */
697                         }
698                         resourceAttributeMap.put(attName, attribute);
699                     }
700                 }
701             }
702         }
703         return resourceAttributeMap;
704     }
705
706     private void newResourceFoundNotification(RemoteResource resource) {
707         synchronized (findResourceUIListeners) {
708             if (findResourceUIListeners.size() > 0) {
709                 IFindResourceUIListener listener;
710                 Iterator<IFindResourceUIListener> listenerItr = findResourceUIListeners
711                         .iterator();
712                 while (listenerItr.hasNext()) {
713                     listener = listenerItr.next();
714                     if (null != listener) {
715                         listener.onNewResourceFound(resource);
716                     }
717                 }
718             }
719         }
720     }
721
722     private void resourceSelectionChangedUINotification(RemoteResource resource) {
723         synchronized (resourceSelectionChangedUIListeners) {
724             if (resourceSelectionChangedUIListeners.size() > 0) {
725                 IResourceSelectionChangedUIListener listener;
726                 Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
727                         .iterator();
728                 while (listenerItr.hasNext()) {
729                     listener = listenerItr.next();
730                     if (null != listener) {
731                         listener.onResourceSelectionChange(resource);
732                     }
733                 }
734             }
735         }
736     }
737
738     private void getCompleteNotification(RemoteResource resource) {
739         synchronized (getUIListeners) {
740             if (getUIListeners.size() > 0) {
741                 IGetUIListener listener;
742                 Iterator<IGetUIListener> listenerItr = getUIListeners
743                         .iterator();
744                 while (listenerItr.hasNext()) {
745                     listener = listenerItr.next();
746                     if (null != listener) {
747                         listener.onGetCompleted(resource);
748                     }
749                 }
750             }
751         }
752     }
753
754     private void putCompleteNotification(RemoteResource resource) {
755         synchronized (putUIListeners) {
756             if (putUIListeners.size() > 0) {
757                 IPutUIListener listener;
758                 Iterator<IPutUIListener> listenerItr = putUIListeners
759                         .iterator();
760                 while (listenerItr.hasNext()) {
761                     listener = listenerItr.next();
762                     if (null != listener) {
763                         listener.onPutCompleted(resource);
764                     }
765                 }
766             }
767         }
768     }
769
770     private void postCompleteNotification(RemoteResource resource) {
771         synchronized (postUIListeners) {
772             if (postUIListeners.size() > 0) {
773                 IPostUIListener listener;
774                 Iterator<IPostUIListener> listenerItr = postUIListeners
775                         .iterator();
776                 while (listenerItr.hasNext()) {
777                     listener = listenerItr.next();
778                     if (null != listener) {
779                         listener.onPostCompleted(resource);
780                     }
781                 }
782             }
783         }
784     }
785
786     private void observeCompleteNotification(RemoteResource resource) {
787         synchronized (observeUIListeners) {
788             if (observeUIListeners.size() > 0) {
789                 IObserveUIListener listener;
790                 Iterator<IObserveUIListener> listenerItr = observeUIListeners
791                         .iterator();
792                 while (listenerItr.hasNext()) {
793                     listener = listenerItr.next();
794                     if (null != listener) {
795                         listener.onObserveCompleted(resource);
796                     }
797                 }
798             }
799         }
800     }
801
802     private void verificationStartedNotification(RemoteResource resource,
803             int autoType) {
804         synchronized (verificationUIListeners) {
805             if (verificationUIListeners.size() > 0) {
806                 IVerificationUIListener listener;
807                 Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
808                         .iterator();
809                 while (listenerItr.hasNext()) {
810                     listener = listenerItr.next();
811                     if (null != listener) {
812                         listener.onVerificationStarted(resource, autoType);
813                     }
814                 }
815             }
816         }
817     }
818
819     private void verificationAbortedNotification(RemoteResource resource,
820             int autoType) {
821         synchronized (verificationUIListeners) {
822             if (verificationUIListeners.size() > 0) {
823                 IVerificationUIListener listener;
824                 Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
825                         .iterator();
826                 while (listenerItr.hasNext()) {
827                     listener = listenerItr.next();
828                     if (null != listener) {
829                         listener.onVerificationAborted(resource, autoType);
830                     }
831                 }
832             }
833         }
834     }
835
836     private void verificationCompletedNotification(RemoteResource resource,
837             int autoType) {
838         synchronized (verificationUIListeners) {
839             if (verificationUIListeners.size() > 0) {
840                 IVerificationUIListener listener;
841                 Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
842                         .iterator();
843                 while (listenerItr.hasNext()) {
844                     listener = listenerItr.next();
845                     if (null != listener) {
846                         listener.onVerificationCompleted(resource, autoType);
847                     }
848                 }
849             }
850         }
851     }
852
853     private void configUploadedNotification(RemoteResource resource) {
854         synchronized (configUploadUIListeners) {
855             if (configUploadUIListeners.size() > 0) {
856                 IConfigurationUpload listener;
857                 Iterator<IConfigurationUpload> listenerItr = configUploadUIListeners
858                         .iterator();
859                 while (listenerItr.hasNext()) {
860                     listener = listenerItr.next();
861                     if (null != listener) {
862                         listener.onConfigurationUploaded(resource);
863                     }
864                 }
865             }
866         }
867     }
868
869     // TODO: Temporarily used to display the resource in the UI
870     public List<String> getURIList() {
871         List<String> list = new ArrayList<String>();
872         synchronized (resourceMap) {
873             /*
874              * Set<String> idSet = resourceMap.keySet(); Iterator<String> idItr
875              * = idSet.iterator(); String sId; RemoteResource resource;
876              * while(idItr.hasNext()) { sId = idItr.next(); resource =
877              * resourceMap.get(sId); if(null == resource) { continue; }
878              * list.add(resource.getResourceURI()); }
879              */
880             Set<String> uriSet = resourceMap.keySet();
881             Iterator<String> uriItr = uriSet.iterator();
882             String uri;
883             while (uriItr.hasNext()) {
884                 uri = uriItr.next();
885                 if (null != uri) {
886                     list.add(uri);
887                 }
888             }
889
890             // Sort the types
891             Collections.sort(list);
892         }
893         return list;
894     }
895
896     public synchronized Set<String> getLastKnownSearchTypes() {
897         return lastKnownSearchTypes;
898     }
899
900     public synchronized void setLastKnownSearchTypes(
901             Set<String> lastKnownSearchTypes) {
902         this.lastKnownSearchTypes = lastKnownSearchTypes;
903     }
904
905     public boolean findResourceRequest(Set<String> searchTypes) {
906         if (null == searchTypes || searchTypes.size() < 1) {
907             return false;
908         }
909         boolean result = false;
910         Iterator<String> searchItr = searchTypes.iterator();
911         String rType;
912         while (searchItr.hasNext()) {
913             rType = searchItr.next();
914             try {
915                 SimulatorManager.findResources(rType, findResourceListener);
916                 result = true;
917             } catch (SimulatorException e) {
918                 Activator
919                         .getDefault()
920                         .getLogManager()
921                         .log(Level.ERROR.ordinal(),
922                                 new Date(),
923                                 "[" + e.getClass().getSimpleName() + "]"
924                                         + e.code().toString() + "-"
925                                         + e.message());
926             }
927         }
928         return result;
929     }
930
931     public void deleteResources(final Set<String> searchTypes) {
932         if (null == searchTypes || searchTypes.size() < 1) {
933             return;
934         }
935         new Thread() {
936             public void run() {
937                 Iterator<String> typeItr = searchTypes.iterator();
938                 String resType;
939                 while (typeItr.hasNext()) {
940                     resType = typeItr.next();
941                     deleteResourcesByType(resType);
942
943                     // Change the current resource in selection
944                     updateCurrentResourceInSelection(searchTypes);
945                 }
946             }
947         }.start();
948     }
949
950     private void updateCurrentResourceInSelection(Set<String> searchTypes) {
951         if (null == searchTypes || searchTypes.size() < 1) {
952             return;
953         }
954         RemoteResource resourceInSelection = getCurrentResourceInSelection();
955         if (null == resourceInSelection) {
956             return;
957         }
958         List<String> typesOfSelection = resourceInSelection.getResourceTypes();
959         if (null == typesOfSelection || typesOfSelection.size() < 1) {
960             return;
961         }
962         Iterator<String> itr = typesOfSelection.iterator();
963         String type;
964         while (itr.hasNext()) {
965             type = itr.next();
966             if (searchTypes.contains(type)) {
967                 setCurrentResourceInSelection(null);
968                 resourceSelectionChangedUINotification(null);
969                 break;
970             }
971         }
972     }
973
974     private void deleteResourcesByType(String resourceType) {
975         if (null == resourceType) {
976             return;
977         }
978         synchronized (resourceMap) {
979             Set<String> keySet = resourceMap.keySet();
980             if (null == keySet) {
981                 return;
982             }
983             Iterator<String> keyItr = keySet.iterator();
984             String uId;
985             RemoteResource resource;
986             boolean exist;
987             List<String> types;
988             while (keyItr.hasNext()) {
989                 uId = keyItr.next();
990                 resource = resourceMap.get(uId);
991                 if (null == resource) {
992                     continue;
993                 }
994                 types = resource.getResourceTypes();
995                 if (null != types) {
996                     exist = types.contains(resourceType);
997                     if (exist) {
998                         // Remove the resource
999                         keyItr.remove();
1000                         removeResourceFromFavorites(resource);
1001                     }
1002                 }
1003             }
1004         }
1005     }
1006
1007     public void resourceSelectionChanged(final RemoteResource resource) {
1008         new Thread() {
1009             @Override
1010             public void run() {
1011                 setCurrentResourceInSelection(resource);
1012                 // Notify all observers for resource selection change event
1013                 resourceSelectionChangedUINotification(resource);
1014             }
1015         }.start();
1016     }
1017
1018     public List<MetaProperty> getMetaProperties(RemoteResource resource) {
1019         if (null != resource) {
1020             String propName;
1021             String propValue;
1022
1023             List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
1024
1025             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
1026                 propName = Constants.META_PROPERTIES[index];
1027                 if (propName.equals(Constants.RESOURCE_URI)) {
1028                     propValue = resource.getResourceURI();
1029                 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
1030                     propValue = resource.getConnectivityType().toString();
1031                 } else if (propName.equals(Constants.OBSERVABLE)) {
1032                     propValue = Utility.getObservableInString(resource
1033                             .isObservable());
1034                     // see in UI
1035                 } else if (propName.equals(Constants.RESOURCE_TYPES)) {
1036                     List<String> types = resource.getResourceTypes();
1037                     if (null != types) {
1038                         propValue = types.toString();
1039                     } else {
1040                         propValue = Constants.NOT_AVAILABLE;
1041                     }
1042                 } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
1043                     List<String> interfaces = resource.getResourceInterfaces();
1044                     if (null != interfaces) {
1045                         propValue = interfaces.toString();
1046                     } else {
1047                         propValue = Constants.NOT_AVAILABLE;
1048                     }
1049                 } else {
1050                     propValue = null;
1051                 }
1052                 if (null != propValue) {
1053                     metaPropertyList.add(new MetaProperty(propName, propValue));
1054                 }
1055             }
1056
1057             return metaPropertyList;
1058         }
1059         return null;
1060     }
1061
1062     public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
1063         if (null == resource) {
1064             return null;
1065         }
1066         Map<String, Boolean> autoStatus = new HashMap<String, Boolean>();
1067         autoStatus.put(Constants.GET, resource.isGetAutomtnInProgress());
1068         autoStatus.put(Constants.PUT, resource.isPutAutomtnInProgress());
1069         autoStatus.put(Constants.POST, resource.isPostAutomtnInProgress());
1070         return autoStatus;
1071     }
1072
1073     public Map<String, String> getDummyAttributes() {
1074         Map<String, String> attributes = new HashMap<String, String>();
1075         attributes.put("intensity", "1");
1076         attributes.put("power", "off");
1077         return attributes;
1078     }
1079
1080     public List<RemoteResource> getResourceList() {
1081         List<RemoteResource> resourceList = new ArrayList<RemoteResource>();
1082         synchronized (resourceMap) {
1083             Set<String> idSet = resourceMap.keySet();
1084             Iterator<String> idItr = idSet.iterator();
1085             RemoteResource resource;
1086             while (idItr.hasNext()) {
1087                 resource = resourceMap.get(idItr.next());
1088                 if (null != resource) {
1089                     resourceList.add(resource);
1090                 }
1091             }
1092         }
1093         // Sort the list
1094         Collections.sort(resourceList, new Comparator<RemoteResource>() {
1095             public int compare(RemoteResource res1, RemoteResource res2) {
1096                 String s1 = res1.getResourceURI();
1097                 String s2 = res2.getResourceURI();
1098
1099                 String s1Part = s1.replaceAll("\\d", "");
1100                 String s2Part = s2.replaceAll("\\d", "");
1101
1102                 if (s1Part.equalsIgnoreCase(s2Part)) {
1103                     return extractInt(s1) - extractInt(s2);
1104                 }
1105                 return s1.compareTo(s2);
1106             }
1107
1108             int extractInt(String s) {
1109                 String num = s.replaceAll("\\D", "");
1110                 // return 0 if no digits found
1111                 return num.isEmpty() ? 0 : Integer.parseInt(num);
1112             }
1113         });
1114
1115         return resourceList;
1116     }
1117
1118     public List<RemoteResource> getFavResourceList() {
1119         List<RemoteResource> resourceList;
1120         synchronized (favoriteResources) {
1121             resourceList = new ArrayList<RemoteResource>(favoriteResources);
1122         }
1123         return resourceList;
1124     }
1125
1126     public String getAttributeValue(RemoteResource res, String attName) {
1127         if (null == res || null == attName) {
1128             return null;
1129         }
1130         return res.getAttributeValue(attName);
1131     }
1132
1133     public void sendGetRequest(RemoteResource resource) {
1134         if (null == resource) {
1135             return;
1136         }
1137         SimulatorRemoteResource resourceN = resource.getResource();
1138         if (null == resourceN) {
1139             return;
1140         }
1141         try {
1142             resourceN.get(null, getListener);
1143         } catch (SimulatorException e) {
1144             Activator
1145                     .getDefault()
1146                     .getLogManager()
1147                     .log(Level.ERROR.ordinal(),
1148                             new Date(),
1149                             "[" + e.getClass().getSimpleName() + "]"
1150                                     + e.code().toString() + "-" + e.message());
1151         }
1152     }
1153
1154     public void sendPutRequest(RemoteResource resource,
1155             List<PutPostAttributeModel> putPostModelList) {
1156         System.out.println(putPostModelList);
1157         System.out.println("ResourceManager: sendPutRequest");
1158         if (null == resource) {
1159             return;
1160         }
1161         System.out.println("ResourceManager: resource not null");
1162         SimulatorRemoteResource resourceN = resource.getResource();
1163         if (null == resourceN) {
1164             return;
1165         }
1166         System.out.println("ResourceManager: Native resource not null");
1167         Map<String, RemoteResourceAttribute> attMap = resource
1168                 .getResourceAttributesMap();
1169         if (null == attMap || attMap.size() < 1) {
1170             return;
1171         }
1172         System.out.println("ResourceManager: attrubutes obtained");
1173         SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap,
1174                 putPostModelList);
1175         System.out.println("ResourceModel exist?:" + (resourceModel != null));
1176         try {
1177             resourceN.put(resourceModel, null, putListener);
1178         } catch (SimulatorException e) {
1179             Activator
1180                     .getDefault()
1181                     .getLogManager()
1182                     .log(Level.ERROR.ordinal(),
1183                             new Date(),
1184                             "[" + e.getClass().getSimpleName() + "]"
1185                                     + e.code().toString() + "-" + e.message());
1186         }
1187         System.out.println("ResourceManager: called native put");
1188     }
1189
1190     public void sendPostRequest(RemoteResource resource,
1191             List<PutPostAttributeModel> putPostModelList) {
1192         System.out.println(putPostModelList);
1193         if (null == resource) {
1194             return;
1195         }
1196         SimulatorRemoteResource resourceN = resource.getResource();
1197         if (null == resourceN) {
1198             return;
1199         }
1200         Map<String, RemoteResourceAttribute> attMap = resource
1201                 .getResourceAttributesMap();
1202         if (null == attMap || attMap.size() < 1) {
1203             return;
1204         }
1205         // Filter out the attributes whose modification status is true.
1206         Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
1207         PutPostAttributeModel model;
1208         while (itr.hasNext()) {
1209             model = itr.next();
1210             if (!model.isModified()) {
1211                 itr.remove();
1212             }
1213         }
1214         SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap,
1215                 putPostModelList);
1216         try {
1217             resourceN.post(resourceModel, null, postListener);
1218         } catch (SimulatorException e) {
1219             Activator
1220                     .getDefault()
1221                     .getLogManager()
1222                     .log(Level.ERROR.ordinal(),
1223                             new Date(),
1224                             "[" + e.getClass().getSimpleName() + "]"
1225                                     + e.code().toString() + "-" + e.message());
1226         }
1227     }
1228
1229     private SimulatorResourceModel getUpdatedResourceModel(
1230             Map<String, RemoteResourceAttribute> attMap,
1231             List<PutPostAttributeModel> putPostModelList) {
1232         String attName;
1233         SimulatorResourceModel resourceModel = new SimulatorResourceModel();
1234         PutPostAttributeModel model;
1235         RemoteResourceAttribute attribute;
1236         Type attType;
1237         Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
1238         while (itr.hasNext()) {
1239             model = itr.next();
1240             attName = model.getAttName();
1241             attribute = attMap.get(attName);
1242             attType = attribute.getAttValBaseType();
1243             if (attType == Type.INT) {
1244                 int attValue;
1245                 try {
1246                     attValue = Integer.parseInt(model.getAttValue());
1247                 } catch (NumberFormatException e) {
1248                     attValue = -1;
1249                 }
1250                 resourceModel.addAttribute(attName, attValue);
1251             } else if (attType == Type.DOUBLE) {
1252                 double attValue;
1253                 try {
1254                     attValue = Double.parseDouble(model.getAttValue());
1255                 } catch (NumberFormatException e) {
1256                     attValue = -1.0;
1257                 }
1258                 resourceModel.addAttribute(attName, attValue);
1259             } else if (attType == Type.BOOL) {
1260                 boolean attValue;
1261                 attValue = Boolean.parseBoolean(model.getAttValue());
1262                 resourceModel.addAttribute(attName, attValue);
1263             } else if (attType == Type.STRING) {
1264                 String attValue;
1265                 attValue = model.getAttValue();
1266                 resourceModel.addAttribute(attName, attValue);
1267             }
1268         }
1269         return resourceModel;
1270     }
1271
1272     public void sendObserveRequest(RemoteResource resource) {
1273         System.out.println("sendObserverRequest() entry");
1274         if (null == resource) {
1275             return;
1276         }
1277         System.out.println("Resource is null:" + (resource == null));
1278         resource.setObserved(true);
1279         SimulatorRemoteResource resourceN = resource.getResource();
1280         if (null == resourceN) {
1281             return;
1282         }
1283         try {
1284             resourceN.observe(SimulatorObserveType.OBSERVE, null,
1285                     observeListener);
1286         } catch (SimulatorException e) {
1287             Activator
1288                     .getDefault()
1289                     .getLogManager()
1290                     .log(Level.ERROR.ordinal(),
1291                             new Date(),
1292                             "[" + e.getClass().getSimpleName() + "]"
1293                                     + e.code().toString() + "-" + e.message());
1294         }
1295         System.out.println("Observer called.");
1296     }
1297
1298     public void sendCancelObserveRequest(RemoteResource resource) {
1299         if (null == resource) {
1300             return;
1301         }
1302         resource.setObserved(false);
1303         SimulatorRemoteResource resourceN = resource.getResource();
1304         if (null == resourceN) {
1305             return;
1306         }
1307         try {
1308             resourceN.cancelObserve();
1309         } catch (SimulatorException e) {
1310             Activator
1311                     .getDefault()
1312                     .getLogManager()
1313                     .log(Level.ERROR.ordinal(),
1314                             new Date(),
1315                             "[" + e.getClass().getSimpleName() + "]"
1316                                     + e.code().toString() + "-" + e.message());
1317         }
1318     }
1319
1320     public void startAutomationRequest(int reqType, RemoteResource resource) {
1321         if (null == resource) {
1322             return;
1323         }
1324         SimulatorRemoteResource resourceN = resource.getResource();
1325         if (null == resourceN) {
1326             return;
1327         }
1328         SimulatorVerificationType type = SimulatorVerificationType
1329                 .getVerificationType(reqType);
1330         if (null == type) {
1331             return;
1332         }
1333         System.out.println("Before calling startVerification: " + reqType);
1334         int autoId;
1335         try {
1336             autoId = resourceN.startVerification(type, verifyListener);
1337             System.out.println("After calling startVerification: " + autoId);
1338             if (autoId != -1) {
1339                 if (reqType == Constants.GET_AUTOMATION_INDEX) {
1340                     // resource.setGetAutomtnInProgress(true);
1341                     resource.setGetAutomtnId(autoId);
1342                 } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
1343                     // resource.setPutAutomtnInProgress(true);
1344                     resource.setPutAutomtnId(autoId);
1345                 } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
1346                         // resource.setPostAutomtnInProgress(true);
1347                     resource.setPostAutomtnId(autoId);
1348                 }
1349             }
1350         } catch (SimulatorException e) {
1351             Activator
1352                     .getDefault()
1353                     .getLogManager()
1354                     .log(Level.ERROR.ordinal(),
1355                             new Date(),
1356                             "[" + e.getClass().getSimpleName() + "]"
1357                                     + e.code().toString() + "-" + e.message());
1358         }
1359     }
1360
1361     public void stopAutomationRequest(int reqType, RemoteResource resource) {
1362         if (null == resource) {
1363             return;
1364         }
1365         SimulatorRemoteResource resourceN = resource.getResource();
1366         if (null == resourceN) {
1367             return;
1368         }
1369         int autoId;
1370         if (reqType == Constants.GET_AUTOMATION_INDEX) {
1371             resource.setGetAutomtnInProgress(false);
1372             autoId = resource.getGetAutomtnId();
1373         } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
1374             resource.setPutAutomtnInProgress(false);
1375             autoId = resource.getPutAutomtnId();
1376         } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
1377             resource.setPostAutomtnInProgress(false);
1378             autoId = resource.getPostAutomtnId();
1379         }
1380         try {
1381             resourceN.stopVerification(autoId);
1382         } catch (SimulatorException e) {
1383             Activator
1384                     .getDefault()
1385                     .getLogManager()
1386                     .log(Level.ERROR.ordinal(),
1387                             new Date(),
1388                             "[" + e.getClass().getSimpleName() + "]"
1389                                     + e.code().toString() + "-" + e.message());
1390         }
1391     }
1392
1393     public void setConfigFilePath(RemoteResource resource, String configFilePath) {
1394         if (null == resource) {
1395             return;
1396         }
1397         SimulatorRemoteResource resourceN = resource.getResource();
1398         if (null == resourceN) {
1399             return;
1400         }
1401         try {
1402             resourceN.configureRAMLPath(configFilePath);
1403         } catch (SimulatorException e) {
1404             Activator
1405                     .getDefault()
1406                     .getLogManager()
1407                     .log(Level.ERROR.ordinal(),
1408                             new Date(),
1409                             "[" + e.getClass().getSimpleName() + "]"
1410                                     + e.code().toString() + "-" + e.message());
1411             return;
1412         }
1413         // Update the status
1414         resource.setConfigUploaded(true);
1415
1416         // Notify the UI listeners
1417         configUploadedNotification(resource);
1418     }
1419
1420     public Image getImage(String resourceURI) {
1421         if (null == resourceURI) {
1422             return null;
1423         }
1424         URL url = Activator.getDefault().getBundle()
1425                 .getEntry(getImageURL(resourceURI));
1426         if (null == url) {
1427             return null;
1428         }
1429         return ImageDescriptor.createFromURL(url).createImage();
1430     }
1431
1432     private String getImageURL(String resourceURI) {
1433         // TODO: Hard-coding the image file name temporarily.
1434         // It will be included in a separate class which manages all image
1435         // resources
1436         return "/icons/light_16x16.png";
1437     }
1438
1439     public void shutdown() {
1440         // TODO: To be implemented for clean-up activities.
1441     }
1442 }