b7e7761d3107bf8b1d41f65229ce7e51116a2a2b
[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 String[] convertListToStringArray(List<String> valueList) {
358         String[] strArr;
359         if (null != valueList && valueList.size() > 0) {
360             strArr = valueList.toArray(new String[1]);
361         } else {
362             strArr = new String[1];
363         }
364         return strArr;
365     }
366
367     public static Comparator<Resource>       resourceComparator       = new Comparator<Resource>() {
368                                                                           public int compare(
369                                                                                   Resource res1,
370                                                                                   Resource res2) {
371                                                                               String s1 = res1
372                                                                                       .getResourceName();
373                                                                               String s2 = res2
374                                                                                       .getResourceName();
375
376                                                                               String s1Part = s1
377                                                                                       .replaceAll(
378                                                                                               "\\d",
379                                                                                               "");
380                                                                               String s2Part = s2
381                                                                                       .replaceAll(
382                                                                                               "\\d",
383                                                                                               "");
384
385                                                                               if (s1Part
386                                                                                       .equalsIgnoreCase(s2Part)) {
387                                                                                   return extractInt(s1)
388                                                                                           - extractInt(s2);
389                                                                               }
390                                                                               return s1
391                                                                                       .compareTo(s2);
392                                                                           }
393
394                                                                           int extractInt(
395                                                                                   String s) {
396                                                                               String num = s
397                                                                                       .replaceAll(
398                                                                                               "\\D",
399                                                                                               "");
400                                                                               // return
401                                                                               // 0
402                                                                               // if
403                                                                               // no
404                                                                               // digits
405                                                                               // found
406                                                                               return num
407                                                                                       .isEmpty() ? 0
408                                                                                       : Integer
409                                                                                               .parseInt(num);
410                                                                           }
411                                                                       };
412
413     public static Comparator<SingleResource> singleResourceComparator = new Comparator<SingleResource>() {
414                                                                           public int compare(
415                                                                                   SingleResource res1,
416                                                                                   SingleResource res2) {
417                                                                               String s1 = res1
418                                                                                       .getResourceName();
419                                                                               String s2 = res2
420                                                                                       .getResourceName();
421
422                                                                               String s1Part = s1
423                                                                                       .replaceAll(
424                                                                                               "\\d",
425                                                                                               "");
426                                                                               String s2Part = s2
427                                                                                       .replaceAll(
428                                                                                               "\\d",
429                                                                                               "");
430
431                                                                               if (s1Part
432                                                                                       .equalsIgnoreCase(s2Part)) {
433                                                                                   return extractInt(s1)
434                                                                                           - extractInt(s2);
435                                                                               }
436                                                                               return s1
437                                                                                       .compareTo(s2);
438                                                                           }
439
440                                                                           int extractInt(
441                                                                                   String s) {
442                                                                               String num = s
443                                                                                       .replaceAll(
444                                                                                               "\\D",
445                                                                                               "");
446                                                                               // return
447                                                                               // 0
448                                                                               // if
449                                                                               // no
450                                                                               // digits
451                                                                               // found
452                                                                               return num
453                                                                                       .isEmpty() ? 0
454                                                                                       : Integer
455                                                                                               .parseInt(num);
456                                                                           }
457                                                                       };
458
459     // This method only works for attributes whose values are of type int,
460     // double, bool, string and 1-D array of primitive types
461     public static String getAttributeValueAsString(AttributeValue val) {
462         if (null == val) {
463             return null;
464         }
465         Object value = val.get();
466         if (null == value) {
467             return null;
468         }
469         TypeInfo type = val.typeInfo();
470         if (type.mType == ValueType.RESOURCEMODEL
471                 || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL)
472                 || (type.mType == ValueType.ARRAY && type.mDepth > 1)) {
473             return null;
474         }
475         if (type.mType == ValueType.ARRAY) {
476             if (type.mBaseType == ValueType.INTEGER) {
477                 Integer[] values = (Integer[]) value;
478                 if (null == values || values.length < 1) {
479                     return null;
480                 }
481                 List<Integer> list = new ArrayList<Integer>();
482                 for (Integer i : values) {
483                     list.add(i);
484                 }
485                 return list.toString();
486             } else if (type.mBaseType == ValueType.DOUBLE) {
487                 Double[] values = (Double[]) value;
488                 if (null == values || values.length < 1) {
489                     return null;
490                 }
491                 List<Double> list = new ArrayList<Double>();
492                 for (Double i : values) {
493                     list.add(i);
494                 }
495                 return list.toString();
496             } else if (type.mBaseType == ValueType.BOOLEAN) {
497                 Boolean[] values = (Boolean[]) value;
498                 if (null == values || values.length < 1) {
499                     return null;
500                 }
501                 List<Boolean> list = new ArrayList<Boolean>();
502                 for (Boolean i : values) {
503                     list.add(i);
504                 }
505                 return list.toString();
506             } else if (type.mBaseType == ValueType.STRING) {
507                 String[] values = (String[]) value;
508                 if (null == values || values.length < 1) {
509                     return null;
510                 }
511                 List<String> list = new ArrayList<String>();
512                 for (String i : values) {
513                     list.add(i);
514                 }
515                 return list.toString();
516             } else {
517                 return null;
518             }
519         } else {
520             return String.valueOf(value);
521         }
522     }
523
524     public static boolean isUriValid(String resURI) {
525         if (null == resURI || resURI.length() < 2 || resURI.length() > 63
526                 || !resURI.startsWith("/") || resURI.endsWith("/")
527                 || resURI.contains("/..") || resURI.contains("//")
528                 || resURI.contains("/./") || resURI.contains("?")
529                 || resURI.contains("#") || resURI.contains("%")) {
530             return false;
531         }
532         return true;
533     }
534
535     public static boolean isResourceTypeValid(String resType) {
536         if (null == resType || resType.isEmpty()) {
537             return false;
538         }
539
540         char[] ch = resType.toCharArray();
541         for (char c : ch) {
542             if (c != '.' && c != '-' && (c < 'a' || c > 'z')
543                     && (c < '0' || c > '9')) {
544                 return false;
545             }
546         }
547
548         return true;
549     }
550
551     public static Map<String, String> getResourceInterfaces(
552             Class<? extends Resource> resourceClass) {
553         Map<String, String> ifTypes = null;
554         if (resourceClass == SingleResource.class) {
555             ifTypes = new HashMap<String, String>();
556             ifTypes.put(Constants.BASELINE_INTERFACE, "Baseline");
557             ifTypes.put(Constants.READ_ONLY_INTERFACE, "Read-Only");
558             ifTypes.put(Constants.READ_WRITE_INTERFACE, "Read-Write");
559             ifTypes.put(Constants.ACTUATOR_INTERFACE, "Actuator");
560             ifTypes.put(Constants.SENSOR_INTERFACE, "Sensor");
561         }
562         return ifTypes;
563     }
564 }