2 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package oic.simulator.clientcontroller.manager;
19 import java.text.NumberFormat;
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;
30 import java.util.Vector;
32 import org.oic.simulator.ArrayProperty;
33 import org.oic.simulator.AttributeProperty;
34 import org.oic.simulator.AttributeProperty.Type;
35 import org.oic.simulator.AttributeValue;
36 import org.oic.simulator.AttributeValue.TypeInfo;
37 import org.oic.simulator.AttributeValue.ValueType;
38 import org.oic.simulator.BooleanProperty;
39 import org.oic.simulator.DeviceInfo;
40 import org.oic.simulator.DeviceListener;
41 import org.oic.simulator.DoubleProperty;
42 import org.oic.simulator.ILogger.Level;
43 import org.oic.simulator.IntegerProperty;
44 import org.oic.simulator.PlatformInfo;
45 import org.oic.simulator.PlatformListener;
46 import org.oic.simulator.SimulatorException;
47 import org.oic.simulator.SimulatorManager;
48 import org.oic.simulator.SimulatorResourceAttribute;
49 import org.oic.simulator.SimulatorResourceModel;
50 import org.oic.simulator.SimulatorResult;
51 import org.oic.simulator.StringProperty;
52 import org.oic.simulator.client.FindResourceListener;
53 import org.oic.simulator.client.SimulatorRemoteResource;
54 import org.oic.simulator.client.SimulatorRemoteResource.GetResponseListener;
55 import org.oic.simulator.client.SimulatorRemoteResource.ObserveNotificationListener;
56 import org.oic.simulator.client.SimulatorRemoteResource.PostResponseListener;
57 import org.oic.simulator.client.SimulatorRemoteResource.PutResponseListener;
58 import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
59 import org.oic.simulator.client.SimulatorRemoteResource.VerificationListener;
60 import org.oic.simulator.client.SimulatorRequestModel;
62 import oic.simulator.clientcontroller.Activator;
63 import oic.simulator.clientcontroller.remoteresource.DeviceAndPlatformInfo;
64 import oic.simulator.clientcontroller.remoteresource.MetaProperty;
65 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
66 import oic.simulator.clientcontroller.utils.AttributeValueStringConverter;
67 import oic.simulator.clientcontroller.utils.Constants;
68 import oic.simulator.clientcontroller.utils.Utility;
71 * This class acts as an interface between the simulator java SDK and the
72 * various UI modules. It maintains all the details of resources and provides
73 * other UI modules with the information required. It also handles responses for
74 * find, GET, PUT, POST, Observe and automatic verification operations from
75 * native layer and propagates those events to the registered UI listeners.
77 public class ResourceManager {
79 private Set<String> lastKnownSearchTypes;
81 private RemoteResource currentResourceInSelection;
83 private FindResourceListener findResourceListener;
84 private GetResponseListener getListener;
85 private PutResponseListener putListener;
86 private PostResponseListener postListener;
87 private ObserveNotificationListener observeListener;
88 private VerificationListener verifyListener;
89 private DeviceListener deviceListener;
90 private PlatformListener platformListener;
92 private ResponseSynchronizerThread synchronizerThread;
94 private Thread threadHandle;
96 // Map with Server ID as key and the complete object as the value
97 private Map<String, RemoteResource> resourceMap;
98 private List<RemoteResource> favoriteResources;
99 // Maintaining a list of resource URIs for favorite resources feature.
100 private List<String> favoriteURIList;
102 // Maintaining a list of observed resource URIs.
103 private List<String> observedResourceURIList;
105 private Map<String, DeviceAndPlatformInfo> hostDeviceAndPlatformMap;
107 public ResourceManager() {
108 resourceMap = new HashMap<String, RemoteResource>();
109 favoriteResources = new ArrayList<RemoteResource>();
110 favoriteURIList = new ArrayList<String>();
111 observedResourceURIList = new ArrayList<String>();
112 hostDeviceAndPlatformMap = new HashMap<String, DeviceAndPlatformInfo>();
114 findResourceListener = new FindResourceListener() {
117 public void onResourceFound(final SimulatorRemoteResource resourceN) {
118 synchronizerThread.addToQueue(new Runnable() {
121 if (null == resourceN) {
125 // Ignore the response if the resource is a device or
127 Vector<String> resTypes = resourceN.getResourceTypes();
129 && (resTypes.contains("oic.wk.d") || resTypes
130 .contains("oic.wk.p"))) {
134 // If id is not available, then it cannot be added to
135 // the local map as null value should not be allowed as
137 String uid = resourceN.getId();
142 // If resource already exist, then ignore it.
143 boolean exist = isUidExist(uid);
145 handleExistingResource(resourceN);
149 RemoteResource resource = new RemoteResource();
150 resource.setRemoteResourceRef(resourceN);
152 boolean observeRequestSent = false;
154 String uri = resourceN.getURI();
155 if (null != uri && uri.trim().length() > 0) {
156 // Add resource to favorite list if it was in
157 // favorites list during find/refresh operation.
158 synchronized (favoriteURIList) {
159 if (favoriteURIList.contains(uri)) {
160 addResourcetoFavorites(resource);
162 } // Add resource to observed resources list if it
164 // in observe list during find/refresh operation.
165 synchronized (observedResourceURIList) {
166 if (observedResourceURIList.contains(uri)) {
167 observeRequestSent = sendObserveRequest(resource);
174 .log(Level.INFO.ordinal(), new Date(),
175 "Found a resource without URI. Ignoring it.");
179 // Add the resource in local data structure
180 addResourceDetails(resource);
182 // Notify the UI listener
183 UiListenerHandler.getInstance()
184 .newResourceFoundNotification(resource);
189 .log(Level.INFO.ordinal(),
191 "Resource Found [" + resourceN.getURI()
194 // Send an initial GET request(If observe request has
195 // not been sent already) to get the resource
196 // attributes on an interface supported by the resource.
197 if (!observeRequestSent) {
199 String ifType = null;
200 Vector<String> resInterfaces = resourceN
201 .getResourceInterfaces();
202 if (null != resInterfaces) {
203 ifType = resInterfaces.get(0);
206 formQueryParameters(ifType, null),
208 } catch (SimulatorException e) {
212 .log(Level.ERROR.ordinal(),
214 Utility.getSimulatorErrorString(
219 // Get the device information
220 if (!isDeviceInfoExist(resourceN.getHost())) {
222 SimulatorManager.findDevices(resource
223 .getRemoteResourceRef().getHost(),
225 } catch (SimulatorException e) {
229 .log(Level.ERROR.ordinal(),
231 Utility.getSimulatorErrorString(
236 // Get the platform information
237 if (!isPlatformInfoExist(resourceN.getHost())) {
239 SimulatorManager.getPlatformInformation(
240 resource.getRemoteResourceRef()
241 .getHost(), platformListener);
242 } catch (SimulatorException e) {
246 .log(Level.ERROR.ordinal(),
248 Utility.getSimulatorErrorString(
257 // Listeners for device and platform information.
258 deviceListener = new DeviceListener() {
261 public void onDeviceFound(final String host,
262 final DeviceInfo deviceInfo) {
263 if (null == deviceInfo || null == host) {
266 synchronizerThread.addToQueue(new Runnable() {
269 synchronized (hostDeviceAndPlatformMap) {
270 DeviceAndPlatformInfo info = hostDeviceAndPlatformMap
273 info = new DeviceAndPlatformInfo();
275 hostDeviceAndPlatformMap.put(host, info);
277 info.setDeviceInfo(deviceInfo);
280 // Notify UI listeners
281 UiListenerHandler.getInstance()
282 .deviceInfoReceivedNotification();
288 platformListener = new PlatformListener() {
291 public void onPlatformFound(final String host,
292 final PlatformInfo platformInfo) {
293 if (null == platformInfo || null == host) {
296 synchronizerThread.addToQueue(new Runnable() {
299 synchronized (hostDeviceAndPlatformMap) {
300 DeviceAndPlatformInfo info = hostDeviceAndPlatformMap
303 info = new DeviceAndPlatformInfo();
305 hostDeviceAndPlatformMap.put(host, info);
307 info.setPlatformInfo(platformInfo);
310 // Notify UI listeners
311 UiListenerHandler.getInstance()
312 .platformInfoReceivedNotification();
318 getListener = new GetResponseListener() {
320 public void onGetResponse(final String uid,
321 final SimulatorResult result,
322 final SimulatorResourceModel resourceModelN) {
323 if (result != SimulatorResult.SIMULATOR_OK) {
327 .log(Level.ERROR.ordinal(),
331 + "] Received error response for GET request.");
334 synchronizerThread.addToQueue(new Runnable() {
337 // Handling the response which includes retrieving the
338 // attributes and updating the local model.
339 RemoteResource resource = handleResponse(uid,
341 if (null != resource) {
342 // Notify the UI listeners
343 UiListenerHandler.getInstance()
344 .getCompleteNotification(resource);
351 putListener = new PutResponseListener() {
354 public void onPutResponse(final String uid,
355 final SimulatorResult result,
356 final SimulatorResourceModel resourceModelN) {
357 if (result != SimulatorResult.SIMULATOR_OK) {
361 .log(Level.ERROR.ordinal(),
365 + "] Received error response for PUT request.");
368 synchronizerThread.addToQueue(new Thread() {
371 // Handling the response which includes retrieving the
372 // attributes and updating the local model.
373 RemoteResource resource = handleResponse(uid,
375 if (null != resource) {
376 // Notify the UI listeners
377 UiListenerHandler.getInstance()
378 .putCompleteNotification(resource);
385 postListener = new PostResponseListener() {
387 public void onPostResponse(final String uid,
388 final SimulatorResult result,
389 final SimulatorResourceModel resourceModelN) {
390 if (result != SimulatorResult.SIMULATOR_OK) {
394 .log(Level.ERROR.ordinal(),
398 + "] Received error response for POST request.");
401 synchronizerThread.addToQueue(new Runnable() {
404 // Handling the response which includes retrieving the
405 // attributes and updating the local model.
406 RemoteResource resource = handleResponse(uid,
408 if (null != resource) {
409 // Notify the UI listeners
410 UiListenerHandler.getInstance()
411 .postCompleteNotification(resource);
418 observeListener = new ObserveNotificationListener() {
421 public void onObserveNotification(final String uid,
422 final SimulatorResourceModel resourceModelN, final int seq) {
423 synchronizerThread.addToQueue(new Runnable() {
426 // Handling the response which includes retrieving the
427 // attributes and updating the local model.
428 RemoteResource resource = handleResponse(uid,
430 if (null != resource) {
431 // Notify the UI listeners
432 UiListenerHandler.getInstance()
433 .observeCompleteNotification(resource);
440 verifyListener = new VerificationListener() {
443 public void onVerificationStarted(final String uid, final int autoId) {
444 synchronizerThread.addToQueue(new Runnable() {
447 RemoteResource resource = getResource(uid);
448 if (null == resource) {
451 // Update the automation status.
452 resource.updateAutomationStatus(autoId, true);
454 RequestType reqType = resource
455 .getAutomationtype(autoId);
457 // Notify the listeners.
458 UiListenerHandler.getInstance()
459 .verificationStartedNotification(resource,
466 public void onVerificationCompleted(final String uid,
468 synchronizerThread.addToQueue(new Runnable() {
471 RemoteResource resource = getResource(uid);
472 if (null == resource) {
475 // Update the automation status.
476 resource.updateAutomationStatus(autoId, false);
478 RequestType reqType = resource
479 .getAutomationtype(autoId);
481 // Notify the listeners.
482 UiListenerHandler.getInstance()
483 .verificationCompletedNotification(resource,
490 public void onVerificationAborted(final String uid, final int autoId) {
491 synchronizerThread.addToQueue(new Runnable() {
494 RemoteResource resource = getResource(uid);
495 if (null == resource) {
498 // Update the automation status.
499 resource.updateAutomationStatus(autoId, false);
501 RequestType reqType = resource
502 .getAutomationtype(autoId);
504 // Notify the listeners.
505 UiListenerHandler.getInstance()
506 .verificationAbortedNotification(resource,
513 synchronizerThread = new ResponseSynchronizerThread();
514 threadHandle = new Thread(synchronizerThread);
515 threadHandle.setName("Simulator Client Controller Event Queue");
516 threadHandle.start();
519 private void handleExistingResource(
520 final SimulatorRemoteResource newNativeResourceRef) {
521 if (null == newNativeResourceRef) {
525 RemoteResource existingResource = getResource(newNativeResourceRef
527 if (null == existingResource) {
531 SimulatorRemoteResource existingNativeResourceRef = existingResource
532 .getRemoteResourceRef();
533 if (null == existingNativeResourceRef) {
537 // Compare the resource properties(resource types, interface types and
539 // of the received resource with the existing resource.
540 // If there is a change, then replace the existing resource properties
542 // a GET request to receive the latest resource representation.
543 boolean change = compareResourceProperties(existingNativeResourceRef,
544 newNativeResourceRef);
549 existingResource.setRemoteResourceRef(newNativeResourceRef);
552 String ifType = null;
553 Vector<String> resInterfaces = newNativeResourceRef
554 .getResourceInterfaces();
555 if (null != resInterfaces) {
556 ifType = resInterfaces.get(0);
558 newNativeResourceRef.get(formQueryParameters(ifType, null),
560 } catch (SimulatorException e) {
564 .log(Level.ERROR.ordinal(), new Date(),
565 Utility.getSimulatorErrorString(e, null));
568 // Notify the UI listener which may be looking for this callback for
569 // further processing.
570 UiListenerHandler.getInstance().newResourceFoundNotification(
573 // Notify the UI listeners by re-selecting the same resource.
574 // This is just to refresh the resource properties being shown.
575 RemoteResource resourceInSelection = getCurrentResourceInSelection();
576 if (null != resourceInSelection) {
577 if (resourceInSelection.getRemoteResourceRef().getURI()
578 .equals(newNativeResourceRef.getURI())) {
579 UiListenerHandler.getInstance()
580 .resourceSelectionChangedUINotification(
586 private boolean compareResourceProperties(
587 SimulatorRemoteResource existingNativeResourceRef,
588 SimulatorRemoteResource newNativeResourceRef) {
589 boolean change = false;
593 if (!existingNativeResourceRef.getURI().equals(
594 existingNativeResourceRef.getURI())) {
600 && !existingNativeResourceRef.getId().equals(
601 existingNativeResourceRef.getId())) {
607 && !existingNativeResourceRef.getHost().equals(
608 existingNativeResourceRef.getHost())) {
612 // Compare Observable flag.
614 && existingNativeResourceRef.isObservable() != existingNativeResourceRef
619 // Compare Resource Types.
620 Vector<String> existingResTypes = existingNativeResourceRef
622 Vector<String> newResTypes = newNativeResourceRef
626 if (existingResTypes.size() != newResTypes.size()) {
629 // Compare both lists.
630 Iterator<String> itr = existingResTypes.iterator();
631 while (itr.hasNext()) {
632 if (!newResTypes.contains(itr.next())) {
640 // Compare Interface Types.
641 Vector<String> existingInterfaceTypes = existingNativeResourceRef
642 .getResourceInterfaces();
643 Vector<String> newInterfaceTypes = newNativeResourceRef
644 .getResourceInterfaces();
647 if (existingInterfaceTypes.size() != newInterfaceTypes.size()) {
650 // Compare both lists.
651 Iterator<String> itr = existingInterfaceTypes.iterator();
652 while (itr.hasNext()) {
653 if (!newInterfaceTypes.contains(itr.next())) {
660 } catch (Exception e) {
667 private RemoteResource handleResponse(String uid,
668 SimulatorResourceModel resourceModelN) {
669 if (null == uid || null == resourceModelN) {
673 // Update the local model
674 RemoteResource resource;
675 resource = getResource(uid);
676 if (null == resource) {
680 resource.setResourceModelRef(resourceModelN);
681 resource.setResourceRepresentation(resourceModelN);
686 public synchronized boolean isDeviceInfoExist(String host) {
687 DeviceAndPlatformInfo info = hostDeviceAndPlatformMap.get(host);
691 if (null == info.getDeviceInfo()) {
697 public synchronized boolean isPlatformInfoExist(String host) {
698 DeviceAndPlatformInfo info = hostDeviceAndPlatformMap.get(host);
702 if (null == info.getPlatformInfo()) {
708 private static class ResponseSynchronizerThread implements Runnable {
710 LinkedList<Runnable> responseQueue = new LinkedList<Runnable>();
714 while (!Thread.interrupted()) {
715 synchronized (this) {
717 while (responseQueue.isEmpty()) {
721 } catch (InterruptedException e) {
727 synchronized (this) {
728 thread = responseQueue.pop();
732 } catch (Exception e) {
733 if (e instanceof InterruptedException) {
741 public void addToQueue(Runnable event) {
742 synchronized (this) {
743 responseQueue.add(event);
749 public void addResourcetoFavorites(RemoteResource resource) {
750 if (null == resource) {
753 resource.setFavorite(true);
754 synchronized (favoriteResources) {
755 favoriteResources.add(resource);
759 public void removeResourceFromFavorites(RemoteResource resource) {
760 if (null == resource) {
763 resource.setFavorite(false);
764 synchronized (favoriteResources) {
765 favoriteResources.remove(resource);
769 public void addResourceURItoFavorites(RemoteResource resource) {
770 if (null == resource) {
773 synchronized (favoriteURIList) {
774 favoriteURIList.add(resource.getRemoteResourceRef().getURI());
778 public void removeResourceURIFromFavorites(RemoteResource resource) {
779 if (null == resource) {
782 synchronized (favoriteURIList) {
783 favoriteURIList.remove(resource.getRemoteResourceRef().getURI());
787 public void addObservedResourceURI(String resourceURI) {
788 synchronized (observedResourceURIList) {
789 if (!observedResourceURIList.contains(resourceURI))
790 observedResourceURIList.add(resourceURI);
794 public void removeObservedResourceURI(String resourceURI) {
795 synchronized (observedResourceURIList) {
796 observedResourceURIList.remove(resourceURI);
800 public boolean isResourceObserved(String resourceURI) {
802 synchronized (observedResourceURIList) {
803 observed = observedResourceURIList.contains(resourceURI);
808 public synchronized RemoteResource getCurrentResourceInSelection() {
809 return currentResourceInSelection;
812 public synchronized void setCurrentResourceInSelection(
813 RemoteResource resource) {
814 this.currentResourceInSelection = resource;
817 private void addResourceDetails(RemoteResource remoteResource) {
818 if (null != remoteResource) {
819 synchronized (resourceMap) {
820 resourceMap.put(remoteResource.getRemoteResourceRef().getId(),
826 private boolean isUidExist(String uid) {
828 synchronized (resourceMap) {
829 exist = resourceMap.containsKey(uid);
834 private RemoteResource getResource(String uid) {
838 RemoteResource resource;
839 synchronized (resourceMap) {
840 resource = resourceMap.get(uid);
845 public synchronized Set<String> getLastKnownSearchTypes() {
846 return lastKnownSearchTypes;
849 public synchronized void setLastKnownSearchTypes(
850 Set<String> lastKnownSearchTypes) {
851 this.lastKnownSearchTypes = lastKnownSearchTypes;
854 public boolean findResourceRequest(Set<String> searchTypes) {
855 boolean result = false;
856 if (null == searchTypes || searchTypes.size() < 1) {
858 SimulatorManager.findResource(findResourceListener);
860 } catch (SimulatorException e) {
864 .log(Level.ERROR.ordinal(), new Date(),
865 Utility.getSimulatorErrorString(e, null));
868 Iterator<String> searchItr = searchTypes.iterator();
870 while (searchItr.hasNext()) {
871 rType = searchItr.next();
873 SimulatorManager.findResource(rType, findResourceListener);
875 } catch (SimulatorException e) {
879 .log(Level.ERROR.ordinal(), new Date(),
880 Utility.getSimulatorErrorString(e, null));
887 public void deleteResources(final Set<String> searchTypes) {
888 synchronized (resourceMap) {
889 if (resourceMap.isEmpty()) {
895 if (null == searchTypes || searchTypes.size() < 1) {
896 synchronized (resourceMap) {
897 // Stop observing all the resources
898 Iterator<String> itr = resourceMap.keySet().iterator();
899 while (itr.hasNext()) {
900 sendCancelObserveRequest(
901 resourceMap.get(itr.next()), false);
903 // Delete all cached details of resources
906 synchronized (favoriteResources) {
907 favoriteResources.clear();
910 // Clearing the device and platform information
911 synchronized (hostDeviceAndPlatformMap) {
912 hostDeviceAndPlatformMap.clear();
915 // Change the current resource in selection
916 setCurrentResourceInSelection(null);
917 UiListenerHandler.getInstance()
918 .resourceSelectionChangedUINotification(null);
920 Iterator<String> typeItr = searchTypes.iterator();
922 while (typeItr.hasNext()) {
923 resType = typeItr.next();
924 deleteResourcesByType(resType);
926 // Change the current resource in selection
927 updateCurrentResourceInSelection(searchTypes);
934 private void updateCurrentResourceInSelection(Set<String> searchTypes) {
935 if (null == searchTypes || searchTypes.size() < 1) {
938 RemoteResource resourceInSelection = getCurrentResourceInSelection();
939 if (null == resourceInSelection) {
942 List<String> typesOfSelection = resourceInSelection
943 .getRemoteResourceRef().getResourceTypes();
944 if (null == typesOfSelection || typesOfSelection.size() < 1) {
947 Iterator<String> itr = typesOfSelection.iterator();
949 while (itr.hasNext()) {
951 if (searchTypes.contains(type)) {
952 setCurrentResourceInSelection(null);
953 UiListenerHandler.getInstance()
954 .resourceSelectionChangedUINotification(null);
960 private void deleteResourcesByType(String resourceType) {
961 if (null == resourceType) {
964 synchronized (resourceMap) {
965 Set<String> keySet = resourceMap.keySet();
966 if (null == keySet) {
969 Iterator<String> keyItr = keySet.iterator();
971 RemoteResource resource;
974 while (keyItr.hasNext()) {
976 resource = resourceMap.get(uId);
977 if (null == resource) {
980 types = resource.getRemoteResourceRef().getResourceTypes();
982 exist = types.contains(resourceType);
984 // Cancel observing the resource.
985 sendCancelObserveRequest(resource, false);
986 // Remove the resource from favorites list.
987 removeResourceFromFavorites(resource);
988 // Remove the resource
990 // Remove the device and platform information
991 synchronized (hostDeviceAndPlatformMap) {
992 hostDeviceAndPlatformMap.remove(resource
993 .getRemoteResourceRef().getHost());
1001 public void resourceSelectionChanged(final RemoteResource resource) {
1005 setCurrentResourceInSelection(resource);
1006 // Notify all observers for resource selection change event
1007 UiListenerHandler.getInstance()
1008 .resourceSelectionChangedUINotification(resource);
1013 public List<MetaProperty> getDefaultProperties(RemoteResource resource) {
1014 if (null != resource) {
1016 StringBuilder propValue;
1018 List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
1020 for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
1021 propName = Constants.META_PROPERTIES[index];
1022 propValue = new StringBuilder();
1023 if (propName.equals(Constants.RESOURCE_URI)) {
1024 propValue.append(resource.getRemoteResourceRef().getURI());
1025 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
1026 propValue.append(resource.getRemoteResourceRef()
1027 .getConnectivityType().toString());
1028 } else if (propName.equals(Constants.ADDRESS)) {
1029 propValue.append(resource.getRemoteResourceRef().getHost());
1030 } else if (propName.equals(Constants.OBSERVABLE)) {
1031 propValue.append(Utility.getObservableInString(resource
1032 .getRemoteResourceRef().isObservable()));
1033 } else if (propName.equals(Constants.RESOURCE_TYPES)) {
1034 Vector<String> resTypes = resource.getRemoteResourceRef()
1035 .getResourceTypes();
1036 if (null != resTypes && !resTypes.isEmpty()) {
1037 Iterator<String> itr = resTypes.iterator();
1038 while (itr.hasNext()) {
1039 propValue.append(itr.next());
1040 if (itr.hasNext()) {
1041 propValue.append(", ");
1045 propValue.append(Constants.NOT_AVAILABLE);
1047 } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
1048 Vector<String> interfaces = resource.getRemoteResourceRef()
1049 .getResourceInterfaces();
1050 if (null != interfaces && !interfaces.isEmpty()) {
1051 Iterator<String> itr = interfaces.iterator();
1052 while (itr.hasNext()) {
1053 propValue.append(itr.next());
1054 if (itr.hasNext()) {
1055 propValue.append(", ");
1059 propValue.append(Constants.NOT_AVAILABLE);
1064 if (null != propValue) {
1065 metaPropertyList.add(new MetaProperty(propName, propValue
1070 return metaPropertyList;
1075 public List<MetaProperty> getDeviceProperties() {
1076 RemoteResource resourceInSelection = getCurrentResourceInSelection();
1077 if (null == resourceInSelection) {
1081 SimulatorRemoteResource remoteResource = resourceInSelection
1082 .getRemoteResourceRef();
1083 if (null == remoteResource) {
1087 String host = remoteResource.getHost();
1092 if (!isDeviceInfoExist(host)) {
1093 // Device Information
1095 SimulatorManager.findDevices(host, deviceListener);
1096 } catch (SimulatorException e) {
1100 .log(Level.ERROR.ordinal(), new Date(),
1101 Utility.getSimulatorErrorString(e, null));
1106 List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
1107 synchronized (hostDeviceAndPlatformMap) {
1108 DeviceInfo devInfo = hostDeviceAndPlatformMap.get(host)
1110 metaProperties.add(new MetaProperty(Constants.DEVICE_ID, devInfo
1112 metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, devInfo
1114 metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
1115 devInfo.getSpecVersion()));
1116 metaProperties.add(new MetaProperty(Constants.DEVICE_DMV_VERSION,
1117 devInfo.getDataModelVersion()));
1120 return metaProperties;
1123 public List<MetaProperty> getPlatformProperties() {
1124 RemoteResource resourceInSelection = getCurrentResourceInSelection();
1125 if (null == resourceInSelection) {
1129 SimulatorRemoteResource remoteResource = resourceInSelection
1130 .getRemoteResourceRef();
1131 if (null == remoteResource) {
1135 String host = remoteResource.getHost();
1140 if (!isPlatformInfoExist(host)) {
1141 // Platform Information
1143 SimulatorManager.getPlatformInformation(host, platformListener);
1144 } catch (SimulatorException e) {
1148 .log(Level.ERROR.ordinal(), new Date(),
1149 Utility.getSimulatorErrorString(e, null));
1154 List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
1155 synchronized (hostDeviceAndPlatformMap) {
1156 PlatformInfo platInfo = hostDeviceAndPlatformMap.get(host)
1158 metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platInfo
1160 metaProperties.add(new MetaProperty(
1161 Constants.PLATFORM_MANUFAC_NAME, platInfo
1162 .getManufacturerName()));
1163 metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL,
1164 platInfo.getManufacturerUrl()));
1165 metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
1166 platInfo.getModelNumber()));
1167 metaProperties.add(new MetaProperty(
1168 Constants.PLATFORM_DATE_OF_MANUFAC, platInfo
1169 .getDateOfManufacture()));
1170 metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION,
1171 platInfo.getPlatformVersion()));
1172 metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
1173 platInfo.getOperationSystemVersion()));
1174 metaProperties.add(new MetaProperty(
1175 Constants.PLATFORM_HARDWARE_VERSION, platInfo
1176 .getHardwareVersion()));
1177 metaProperties.add(new MetaProperty(
1178 Constants.PLATFORM_FIRMWARE_VERSION, platInfo
1179 .getFirmwareVersion()));
1180 metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
1181 platInfo.getSupportUrl()));
1182 metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME,
1183 platInfo.getSystemTime()));
1185 return metaProperties;
1188 public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
1189 if (null == resource) {
1192 Map<String, Boolean> autoStatus = new HashMap<String, Boolean>();
1193 autoStatus.put(Constants.GET, resource.isGetAutomtnInProgress());
1194 autoStatus.put(Constants.PUT, resource.isPutAutomtnInProgress());
1195 autoStatus.put(Constants.POST, resource.isPostAutomtnInProgress());
1199 public List<RemoteResource> getResourceList() {
1200 List<RemoteResource> resourceList = new ArrayList<RemoteResource>();
1201 synchronized (resourceMap) {
1202 Set<String> idSet = resourceMap.keySet();
1203 Iterator<String> idItr = idSet.iterator();
1204 RemoteResource resource;
1205 while (idItr.hasNext()) {
1206 resource = resourceMap.get(idItr.next());
1207 if (null != resource) {
1208 resourceList.add(resource);
1213 Collections.sort(resourceList, new Comparator<RemoteResource>() {
1214 public int compare(RemoteResource res1, RemoteResource res2) {
1215 String s1 = res1.getRemoteResourceRef().getURI();
1216 String s2 = res2.getRemoteResourceRef().getURI();
1218 String s1Part = s1.replaceAll("\\d", "");
1219 String s2Part = s2.replaceAll("\\d", "");
1221 if (s1Part.equalsIgnoreCase(s2Part)) {
1222 return extractInt(s1) - extractInt(s2);
1224 return s1.compareTo(s2);
1227 int extractInt(String s) {
1228 String num = s.replaceAll("\\D", "");
1229 // return 0 if no digits found
1230 return num.isEmpty() ? 0 : Integer.parseInt(num);
1234 return resourceList;
1237 public List<RemoteResource> getFavResourceList() {
1238 List<RemoteResource> resourceList;
1239 synchronized (favoriteResources) {
1240 resourceList = new ArrayList<RemoteResource>(favoriteResources);
1242 return resourceList;
1245 public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
1250 AttributeValue val = att.value();
1251 if (null == val || null == val.get()) {
1255 TypeInfo type = val.typeInfo();
1257 if (type.mBaseType == ValueType.RESOURCEMODEL) {
1261 List<String> values = new ArrayList<String>();
1263 AttributeProperty prop = att.property();
1265 values.add(new AttributeValueStringConverter(val).toString());
1269 if (type.mType == ValueType.ARRAY) {
1270 if (type.mDepth == 1) {
1271 ArrayProperty arrayProperty = prop.asArray();
1272 if (null != arrayProperty) {
1273 AttributeProperty childProp = arrayProperty
1274 .getElementProperty();
1275 switch (childProp.getType()) {
1277 IntegerProperty intProperty = childProp.asInteger();
1278 if (null != intProperty) {
1279 values.addAll(getAllValues(att, intProperty,
1284 DoubleProperty dblProperty = childProp.asDouble();
1285 if (null != dblProperty) {
1286 values.addAll(getAllValues(att, dblProperty,
1291 BooleanProperty boolProperty = childProp
1293 if (null != boolProperty) {
1294 values.addAll(getAllValues(att, boolProperty,
1299 StringProperty stringProperty = childProp
1301 if (null != stringProperty) {
1302 values.addAll(getAllValues(att, stringProperty,
1312 switch (prop.getType()) {
1314 IntegerProperty intProperty = prop.asInteger();
1315 if (null != intProperty) {
1316 values.addAll(getAllValues(att, intProperty,
1321 DoubleProperty dblProperty = prop.asDouble();
1322 if (null != dblProperty) {
1323 values.addAll(getAllValues(att, dblProperty,
1328 BooleanProperty boolProperty = prop.asBoolean();
1329 if (null != boolProperty) {
1330 values.addAll(getAllValues(att, boolProperty,
1335 StringProperty stringProperty = prop.asString();
1336 if (null != stringProperty) {
1337 values.addAll(getAllValues(att, stringProperty,
1349 public List<String> getAllValues(SimulatorResourceAttribute attribute,
1350 IntegerProperty intProperty, AttributeProperty.Type type) {
1351 List<String> values = new ArrayList<String>();
1353 if (intProperty.hasRange()) {
1354 int min = (int) intProperty.min();
1355 int max = (int) intProperty.max();
1356 for (int iVal = min; iVal <= max; iVal++) {
1357 values.add(String.valueOf(iVal));
1359 } else if (intProperty.hasValues()) {
1360 for (Integer val : intProperty.getValues()) {
1361 values.add(String.valueOf(val));
1364 AttributeValue value = attribute.value();
1365 if (null != value && null != value.get()) {
1366 // Adding the current value of the attribute.
1367 values.add(String.valueOf(value.get()));
1373 public List<String> getAllValues(SimulatorResourceAttribute attribute,
1374 DoubleProperty dblProperty, AttributeProperty.Type type) {
1375 NumberFormat formatter = NumberFormat.getInstance();
1376 List<String> values = new ArrayList<String>();
1378 if (dblProperty.hasRange()) {
1379 double min = (double) dblProperty.min();
1380 double max = (double) dblProperty.max();
1381 for (double val = min; val <= max; val += 0.1) {
1382 formatter.setMaximumFractionDigits(1);
1383 formatter.setMinimumFractionDigits(1);
1384 values.add(formatter.format(val));
1386 } else if (dblProperty.hasValues()) {
1387 for (Double val : dblProperty.getValues()) {
1388 values.add(String.valueOf(val));
1391 AttributeValue value = attribute.value();
1392 if (null != value && null != value.get()) {
1393 // Adding the current value of the attribute.
1394 values.add(String.valueOf(value.get()));
1400 public List<String> getAllValues(SimulatorResourceAttribute attribute,
1401 BooleanProperty boolProperty, AttributeProperty.Type type) {
1402 List<String> values = new ArrayList<String>();
1404 values.add("false");
1408 public List<String> getAllValues(SimulatorResourceAttribute attribute,
1409 StringProperty stringProperty, AttributeProperty.Type type) {
1410 List<String> values = new ArrayList<String>();
1412 if (stringProperty.hasValues()) {
1413 for (String val : stringProperty.getValues()) {
1414 values.add(String.valueOf(val));
1417 AttributeValue value = attribute.value();
1418 if (null != value && null != value.get()) {
1419 // Adding the current value of the attribute.
1420 values.add(String.valueOf(value.get()));
1426 public void sendGetRequest(String ifType, String query,
1427 RemoteResource resource) {
1428 if (null == resource) {
1431 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1432 if (null == resourceN) {
1436 Map<String, String> queryParams = formQueryParameters(ifType, query);
1438 resourceN.get(queryParams, getListener);
1439 } catch (SimulatorException e) {
1443 .log(Level.ERROR.ordinal(), new Date(),
1444 Utility.getSimulatorErrorString(e, null));
1448 public void sendPutRequest(String ifType, RemoteResource resource,
1449 SimulatorResourceModel model) {
1450 if (null == resource || null == model) {
1453 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1454 if (null == resourceN) {
1457 Map<String, String> queryParams = formQueryParameters(ifType, null);
1459 resourceN.put(queryParams, model, putListener);
1460 } catch (Exception e) {
1462 addlInfo = "Invalid Attribute Value. Cannot send PUT request.";
1466 .log(Level.ERROR.ordinal(), new Date(),
1467 Utility.getSimulatorErrorString(e, addlInfo));
1471 public void sendPostRequest(String ifType, RemoteResource resource,
1472 SimulatorResourceModel model) {
1473 if (null == resource || null == model) {
1476 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1477 if (null == resourceN) {
1480 Map<String, String> queryParams = formQueryParameters(ifType, null);
1482 resourceN.post(queryParams, model, postListener);
1483 } catch (Exception e) {
1485 addlInfo = "Invalid Attribute Value. Cannot send POST request.";
1489 .log(Level.ERROR.ordinal(), new Date(),
1490 Utility.getSimulatorErrorString(e, addlInfo));
1494 public boolean sendObserveRequest(RemoteResource resource) {
1495 if (null == resource) {
1498 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1499 if (null == resourceN) {
1503 resourceN.observe(observeListener);
1504 resource.setObserved(true);
1505 // Add observed resource URI to show the proper status after every
1506 // find/refresh operations.
1507 addObservedResourceURI(resource.getRemoteResourceRef().getURI());
1508 } catch (SimulatorException e) {
1512 .log(Level.ERROR.ordinal(), new Date(),
1513 Utility.getSimulatorErrorString(e, null));
1519 private Map<String, String> formQueryParameters(String ifType, String query) {
1520 Map<String, String> queryParams = new HashMap<String, String>();
1522 // Including the interface type, if given,
1523 if (null != ifType) {
1524 ifType = ifType.trim();
1525 if (ifType.length() > 0)
1526 queryParams.put("if", ifType);
1529 // Including other queries, if given.
1530 if (null != query) {
1531 query = query.trim();
1532 if (query.length() > 0) {
1533 // Parse the query parameters and fill the map.
1534 String queries[] = query.split(";");
1535 if (queries.length > 0) {
1536 for (String pair : queries) {
1537 String tok[] = pair.split("=");
1538 if (null != tok && tok.length == 2) {
1539 queryParams.put(tok[0].trim(), tok[1].trim());
1548 public boolean sendCancelObserveRequest(RemoteResource resource,
1549 boolean removeEntry) {
1550 if (null == resource || !resource.isObserved()) {
1553 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1554 if (null == resourceN) {
1558 resourceN.stopObserve();
1559 resource.setObserved(false);
1560 // Remove observed resource URI to show the proper status after
1561 // every find/refresh operations.
1563 removeObservedResourceURI(resource.getRemoteResourceRef()
1565 } catch (SimulatorException e) {
1569 .log(Level.ERROR.ordinal(), new Date(),
1570 Utility.getSimulatorErrorString(e, null));
1576 public void startAutomationRequest(RequestType reqType,
1577 RemoteResource resource) {
1578 if (null == resource) {
1581 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1582 if (null == resourceN) {
1585 if (null == reqType) {
1590 autoId = resourceN.startVerification(reqType, verifyListener);
1592 if (reqType == RequestType.GET) {
1593 resource.setGetAutomtnId(autoId);
1594 } else if (reqType == RequestType.PUT) {
1595 resource.setPutAutomtnId(autoId);
1597 resource.setPostAutomtnId(autoId);
1603 .log(Level.INFO.ordinal(),
1605 "[" + reqType.toString()
1606 + "] Verification Started for \""
1607 + resourceN.getURI() + "\".");
1608 } catch (SimulatorException e) {
1612 .log(Level.ERROR.ordinal(), new Date(),
1613 Utility.getSimulatorErrorString(e, null));
1617 public void stopAutomationRequest(RequestType reqType,
1618 RemoteResource resource) {
1619 if (null == resource) {
1622 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1623 if (null == resourceN) {
1627 if (reqType == RequestType.GET) {
1628 resource.setGetAutomtnInProgress(false);
1629 autoId = resource.getGetAutomtnId();
1630 } else if (reqType == RequestType.PUT) {
1631 resource.setPutAutomtnInProgress(false);
1632 autoId = resource.getPutAutomtnId();
1634 resource.setPostAutomtnInProgress(false);
1635 autoId = resource.getPostAutomtnId();
1638 resourceN.stopVerification(autoId);
1639 } catch (SimulatorException e) {
1643 .log(Level.ERROR.ordinal(), new Date(),
1644 Utility.getSimulatorErrorString(e, null));
1648 public boolean setConfigFilePath(RemoteResource resource,
1649 String configFilePath) throws SimulatorException {
1651 if (null == resource) {
1654 SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
1655 if (null == resourceN) {
1659 Map<RequestType, SimulatorRequestModel> requestModels;
1660 requestModels = resourceN.setConfigInfo(configFilePath);
1661 if (null == requestModels) {
1665 // Store the resource model in the local cache
1666 resource.setRequestModels(requestModels);
1667 } catch (SimulatorException e) {
1671 .log(Level.ERROR.ordinal(), new Date(),
1672 Utility.getSimulatorErrorString(e, null));
1674 } catch (Exception e) {
1678 .log(Level.ERROR.ordinal(),
1680 Utility.getSimulatorErrorString(e,
1681 "Error while configuring the attribute properties"));
1683 // Update the status
1684 resource.setConfigUploaded(true);
1686 // Notify the UI listeners
1687 UiListenerHandler.getInstance().configUploadedNotification(resource);
1692 public void shutdown() {