[IoTivity Simulator] Handling resource interfaces.
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / utils / Utility.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.serviceprovider.utils;
18
19 import java.util.ArrayList;
20 import java.util.Comparator;
21 import java.util.Date;
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.Vector;
30
31 import oic.simulator.serviceprovider.Activator;
32 import oic.simulator.serviceprovider.model.Resource;
33 import oic.simulator.serviceprovider.model.SingleResource;
34
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.ILogger.Level;
39 import org.oic.simulator.SimulatorException;
40
41 /**
42  * This class has common utility methods.
43  */
44 public class Utility {
45
46     public static String getAutomationStatus(boolean status) {
47         if (status) {
48             return Constants.ENABLED;
49         } else {
50             return Constants.DISABLED;
51         }
52     }
53
54     public static String getAutomationString(boolean status) {
55         if (status) {
56             return Constants.ENABLE;
57         } else {
58             return Constants.DISABLE;
59         }
60     }
61
62     public static boolean getAutomationBoolean(String status) {
63         if (null != status) {
64             if (status.equals(Constants.ENABLE)) {
65                 return true;
66             }
67         }
68         return false;
69     }
70
71     public static int getUpdateIntervalFromString(String value) {
72         int result = Constants.DEFAULT_AUTOMATION_INTERVAL;
73         if (null != value) {
74             try {
75                 result = Integer.parseInt(value);
76             } catch (NumberFormatException e) {
77                 Activator
78                         .getDefault()
79                         .getLogManager()
80                         .log(Level.ERROR.ordinal(),
81                                 new Date(),
82                                 getSimulatorErrorString(
83                                         e,
84                                         "Update interval convertion failed."
85                                                 + "Taking the default value("
86                                                 + Constants.DEFAULT_AUTOMATION_INTERVAL
87                                                 + ")"));
88             }
89         }
90         return result;
91     }
92
93     public static List<String> convertSetToList(Set<String> typeSet) {
94         if (null == typeSet) {
95             return null;
96         }
97         List<String> list = new ArrayList<String>();
98         Iterator<String> typeItr = typeSet.iterator();
99         while (typeItr.hasNext()) {
100             list.add(typeItr.next());
101         }
102         return list;
103     }
104
105     public static List<SingleResource> getSingleResourceListFromSet(
106             Set<SingleResource> resources) {
107         if (null == resources) {
108             return null;
109         }
110         List<SingleResource> list = new ArrayList<SingleResource>();
111         Iterator<SingleResource> typeItr = resources.iterator();
112         while (typeItr.hasNext()) {
113             list.add(typeItr.next());
114         }
115         return list;
116     }
117
118     public static Set<String> convertVectorToSet(Vector<String> vector) {
119         if (null == vector || vector.isEmpty()) {
120             return null;
121         }
122         Set<String> resultSet = new HashSet<String>();
123         Enumeration<String> e = vector.elements();
124         while (e.hasMoreElements()) {
125             resultSet.add(e.nextElement().toString());
126         }
127         return resultSet;
128     }
129
130     public static String getSimulatorErrorString(Exception e, String info) {
131         if (null == e) {
132             return null;
133         }
134         String detail = "";
135         if (e instanceof SimulatorException) {
136             SimulatorException simEx = (SimulatorException) e;
137             detail = simEx.message() + "\n";
138             detail += "Exception Type: " + simEx.getClass().getSimpleName()
139                     + "\n";
140             detail += "Error code: " + simEx.code().toString();
141         } else {
142             if (null != info && !info.isEmpty())
143                 detail = info + "\n";
144             else
145                 detail = "Description not available\n";
146             detail += "Exception Type: " + e.getClass().getSimpleName() + "\n";
147             String msg = e.getMessage();
148             if (null != msg && !msg.isEmpty()) {
149                 detail += "Message: " + e.getMessage();
150             }
151         }
152         return detail;
153     }
154
155     public static Set<String> getAttributeTypes() {
156         Set<String> attTypes = new HashSet<String>();
157         ValueType[] types = ValueType.values();
158         if (null != types) {
159             attTypes.add(Constants.INT);
160             attTypes.add(Constants.DOUBLE);
161             attTypes.add(Constants.BOOL);
162             attTypes.add(Constants.STRING);
163         }
164         return attTypes;
165     }
166
167     public static ValueType getAttributeTypeEnum(String type) {
168         if (null != type && type.trim().length() > 0) {
169             if (type.equalsIgnoreCase(Constants.INT)) {
170                 return ValueType.INTEGER;
171             }
172             if (type.equalsIgnoreCase(Constants.DOUBLE)) {
173                 return ValueType.DOUBLE;
174             }
175             if (type.equalsIgnoreCase(Constants.BOOL)) {
176                 return ValueType.BOOLEAN;
177             }
178             if (type.equalsIgnoreCase(Constants.STRING)) {
179                 return ValueType.STRING;
180             }
181         }
182         return ValueType.UNKNOWN;
183     }
184
185     public static int[] convertSetToArrayInt(Set<Object> allowedValues) {
186         if (null == allowedValues || allowedValues.size() < 1) {
187             return null;
188         }
189         int[] arr = new int[allowedValues.size()];
190         Iterator<Object> itr = allowedValues.iterator();
191         try {
192             int i = 0;
193             while (itr.hasNext()) {
194                 arr[i++] = (int) itr.next();
195             }
196         } catch (Exception e) {
197             return null;
198         }
199         return arr;
200     }
201
202     public static double[] convertSetToArrayDouble(Set<Object> allowedValues) {
203         if (null == allowedValues || allowedValues.size() < 1) {
204             return null;
205         }
206         double[] arr = new double[allowedValues.size()];
207         Iterator<Object> itr = allowedValues.iterator();
208         try {
209             int i = 0;
210             while (itr.hasNext()) {
211                 arr[i++] = (double) itr.next();
212             }
213         } catch (Exception e) {
214             return null;
215         }
216         return arr;
217     }
218
219     public static boolean[] convertSetToArrayBoolean(Set<Object> allowedValues) {
220         if (null == allowedValues || allowedValues.size() < 1) {
221             return null;
222         }
223         boolean[] arr = new boolean[allowedValues.size()];
224         Iterator<Object> itr = allowedValues.iterator();
225         try {
226             int i = 0;
227             while (itr.hasNext()) {
228                 arr[i++] = (boolean) itr.next();
229             }
230         } catch (Exception e) {
231             return null;
232         }
233         return arr;
234     }
235
236     public static String[] convertSetToArrayString(Set<Object> allowedValues) {
237         if (null == allowedValues || allowedValues.size() < 1) {
238             return null;
239         }
240         String[] arr = new String[allowedValues.size()];
241         Iterator<Object> itr = allowedValues.iterator();
242         try {
243             int i = 0;
244             while (itr.hasNext()) {
245                 arr[i++] = (String) itr.next();
246             }
247         } catch (Exception e) {
248             return null;
249         }
250         return arr;
251     }
252
253     public static Vector<Integer> convertSetToVectorInt(
254             Set<Object> allowedValues) {
255         if (null == allowedValues || allowedValues.size() < 1) {
256             return null;
257         }
258         Vector<Integer> resultVec = new Vector<Integer>();
259         Iterator<Object> itr = allowedValues.iterator();
260         try {
261             while (itr.hasNext()) {
262                 resultVec.add((Integer) itr.next());
263             }
264         } catch (Exception e) {
265             return null;
266         }
267         return resultVec;
268     }
269
270     public static Vector<Double> convertSetToVectorDouble(
271             Set<Object> allowedValues) {
272         if (null == allowedValues || allowedValues.size() < 1) {
273             return null;
274         }
275         Vector<Double> resultVec = new Vector<Double>();
276         Iterator<Object> itr = allowedValues.iterator();
277         try {
278             while (itr.hasNext()) {
279                 resultVec.add((Double) itr.next());
280             }
281         } catch (Exception e) {
282             return null;
283         }
284         return resultVec;
285     }
286
287     public static Vector<String> convertSetToVectorString(
288             Set<String> allowedValues) {
289         if (null == allowedValues || allowedValues.size() < 1) {
290             return null;
291         }
292         Vector<String> resultVec = new Vector<String>();
293         Iterator<String> itr = allowedValues.iterator();
294         try {
295             while (itr.hasNext()) {
296                 resultVec.add((String) itr.next());
297             }
298         } catch (Exception e) {
299             return null;
300         }
301         return resultVec;
302     }
303
304     public static Set<Object> convertSetStringToSetObject(Set<String> values,
305             ValueType type) {
306         if (null == values || values.isEmpty()) {
307             return null;
308         }
309         Set<Object> resultSet = new HashSet<Object>();
310         if (AttributeValue.ValueType.INTEGER == type) {
311             int val;
312             Iterator<String> itr = values.iterator();
313             while (itr.hasNext()) {
314                 try {
315                     val = Integer.parseInt(itr.next());
316                     resultSet.add(val);
317                 } catch (NumberFormatException nfe) {
318                     // Added for safety. Nothing to do.
319                 }
320             }
321         } else if (AttributeValue.ValueType.DOUBLE == type) {
322             double val;
323             Iterator<String> itr = values.iterator();
324             while (itr.hasNext()) {
325                 try {
326                     val = Double.parseDouble(itr.next());
327                     resultSet.add(val);
328                 } catch (NumberFormatException nfe) {
329                     // Added for safety. Nothing to do.
330                 }
331             }
332         } else if (AttributeValue.ValueType.BOOLEAN == type) {
333             resultSet.add(true);
334             resultSet.add(false);
335         } else if (AttributeValue.ValueType.STRING == type) {
336             Iterator<String> itr = values.iterator();
337             while (itr.hasNext()) {
338                 resultSet.add(itr.next());
339             }
340         }
341         return resultSet;
342     }
343
344     public static List<Resource> convertSingleTypeResourceListToBaseType(
345             List<SingleResource> resources) {
346         if (null == resources || resources.isEmpty()) {
347             return null;
348         }
349         List<Resource> resultSet = new ArrayList<Resource>();
350         Iterator<SingleResource> itr = resources.iterator();
351         while (itr.hasNext()) {
352             resultSet.add(itr.next());
353         }
354         return resultSet;
355     }
356
357     public static Comparator<Resource>       resourceComparator       = new Comparator<Resource>() {
358                                                                           public int compare(
359                                                                                   Resource res1,
360                                                                                   Resource res2) {
361                                                                               String s1 = res1
362                                                                                       .getResourceName();
363                                                                               String s2 = res2
364                                                                                       .getResourceName();
365
366                                                                               String s1Part = s1
367                                                                                       .replaceAll(
368                                                                                               "\\d",
369                                                                                               "");
370                                                                               String s2Part = s2
371                                                                                       .replaceAll(
372                                                                                               "\\d",
373                                                                                               "");
374
375                                                                               if (s1Part
376                                                                                       .equalsIgnoreCase(s2Part)) {
377                                                                                   return extractInt(s1)
378                                                                                           - extractInt(s2);
379                                                                               }
380                                                                               return s1
381                                                                                       .compareTo(s2);
382                                                                           }
383
384                                                                           int extractInt(
385                                                                                   String s) {
386                                                                               String num = s
387                                                                                       .replaceAll(
388                                                                                               "\\D",
389                                                                                               "");
390                                                                               // return
391                                                                               // 0
392                                                                               // if
393                                                                               // no
394                                                                               // digits
395                                                                               // found
396                                                                               return num
397                                                                                       .isEmpty() ? 0
398                                                                                       : Integer
399                                                                                               .parseInt(num);
400                                                                           }
401                                                                       };
402
403     public static Comparator<SingleResource> singleResourceComparator = new Comparator<SingleResource>() {
404                                                                           public int compare(
405                                                                                   SingleResource res1,
406                                                                                   SingleResource res2) {
407                                                                               String s1 = res1
408                                                                                       .getResourceName();
409                                                                               String s2 = res2
410                                                                                       .getResourceName();
411
412                                                                               String s1Part = s1
413                                                                                       .replaceAll(
414                                                                                               "\\d",
415                                                                                               "");
416                                                                               String s2Part = s2
417                                                                                       .replaceAll(
418                                                                                               "\\d",
419                                                                                               "");
420
421                                                                               if (s1Part
422                                                                                       .equalsIgnoreCase(s2Part)) {
423                                                                                   return extractInt(s1)
424                                                                                           - extractInt(s2);
425                                                                               }
426                                                                               return s1
427                                                                                       .compareTo(s2);
428                                                                           }
429
430                                                                           int extractInt(
431                                                                                   String s) {
432                                                                               String num = s
433                                                                                       .replaceAll(
434                                                                                               "\\D",
435                                                                                               "");
436                                                                               // return
437                                                                               // 0
438                                                                               // if
439                                                                               // no
440                                                                               // digits
441                                                                               // found
442                                                                               return num
443                                                                                       .isEmpty() ? 0
444                                                                                       : Integer
445                                                                                               .parseInt(num);
446                                                                           }
447                                                                       };
448
449     // This method only works for attributes whose values are of type int,
450     // double, bool, string and 1-D array of primitive types
451     public static String getAttributeValueAsString(AttributeValue val) {
452         if (null == val) {
453             return null;
454         }
455         Object value = val.get();
456         if (null == value) {
457             return null;
458         }
459         TypeInfo type = val.typeInfo();
460         if (type.mType == ValueType.RESOURCEMODEL
461                 || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL)
462                 || (type.mType == ValueType.ARRAY && type.mDepth > 1)) {
463             return null;
464         }
465         if (type.mType == ValueType.ARRAY) {
466             if (type.mBaseType == ValueType.INTEGER) {
467                 Integer[] values = (Integer[]) value;
468                 if (null == values || values.length < 1) {
469                     return null;
470                 }
471                 List<Integer> list = new ArrayList<Integer>();
472                 for (Integer i : values) {
473                     list.add(i);
474                 }
475                 return list.toString();
476             } else if (type.mBaseType == ValueType.DOUBLE) {
477                 Double[] values = (Double[]) value;
478                 if (null == values || values.length < 1) {
479                     return null;
480                 }
481                 List<Double> list = new ArrayList<Double>();
482                 for (Double i : values) {
483                     list.add(i);
484                 }
485                 return list.toString();
486             } else if (type.mBaseType == ValueType.BOOLEAN) {
487                 Boolean[] values = (Boolean[]) value;
488                 if (null == values || values.length < 1) {
489                     return null;
490                 }
491                 List<Boolean> list = new ArrayList<Boolean>();
492                 for (Boolean i : values) {
493                     list.add(i);
494                 }
495                 return list.toString();
496             } else if (type.mBaseType == ValueType.STRING) {
497                 String[] values = (String[]) value;
498                 if (null == values || values.length < 1) {
499                     return null;
500                 }
501                 List<String> list = new ArrayList<String>();
502                 for (String i : values) {
503                     list.add(i);
504                 }
505                 return list.toString();
506             } else {
507                 return null;
508             }
509         } else {
510             return String.valueOf(value);
511         }
512     }
513
514     public static boolean isUriValid(String resURI) {
515         if (null == resURI || resURI.length() < 2 || resURI.length() > 63
516                 || !resURI.startsWith("/") || resURI.endsWith("/")
517                 || resURI.contains("/..") || resURI.contains("//")
518                 || resURI.contains("/./") || resURI.contains("?")
519                 || resURI.contains("#") || resURI.contains("%")) {
520             return false;
521         }
522         return true;
523     }
524
525     public static boolean isResourceTypeValid(String resType) {
526         if (null == resType || resType.isEmpty()) {
527             return false;
528         }
529
530         char[] ch = resType.toCharArray();
531         for (char c : ch) {
532             if (c != '.' && c != '-' && (c < 'a' || c > 'z')
533                     && (c < '0' || c > '9')) {
534                 return false;
535             }
536         }
537
538         return true;
539     }
540
541     public static Map<String, String> getResourceInterfaces(
542             Class<? extends Resource> resourceClass) {
543         Map<String, String> ifTypes = null;
544         if (resourceClass == SingleResource.class) {
545             ifTypes = new HashMap<String, String>();
546             ifTypes.put(Constants.BASELINE_INTERFACE, "Baseline");
547             ifTypes.put(Constants.READ_ONLY_INTERFACE, "Read-Only");
548             ifTypes.put(Constants.READ_WRITE_INTERFACE, "Read-Write");
549             ifTypes.put(Constants.ACTUATOR_INTERFACE, "Actuator");
550             ifTypes.put(Constants.SENSOR_INTERFACE, "Sensor");
551         }
552         return ifTypes;
553     }
554 }