Imported Upstream version 1.1.0
[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 org.oic.simulator.AttributeValue;
32 import org.oic.simulator.AttributeValue.TypeInfo;
33 import org.oic.simulator.AttributeValue.ValueType;
34 import org.oic.simulator.ILogger.Level;
35 import org.oic.simulator.InvalidArgsException;
36 import org.oic.simulator.SimulatorException;
37 import org.oic.simulator.SimulatorResourceModel;
38
39 import oic.simulator.serviceprovider.Activator;
40 import oic.simulator.serviceprovider.model.AttributeElement;
41 import oic.simulator.serviceprovider.model.Resource;
42 import oic.simulator.serviceprovider.model.SingleResource;
43
44 /**
45  * This class has common utility methods.
46  */
47 public class Utility {
48
49     public static String getAutomationStatus(boolean status) {
50         if (status) {
51             return Constants.ENABLED;
52         } else {
53             return Constants.DISABLED;
54         }
55     }
56
57     public static String getAutomationString(boolean status) {
58         if (status) {
59             return Constants.ENABLE;
60         } else {
61             return Constants.DISABLE;
62         }
63     }
64
65     public static boolean getAutomationBoolean(String status) {
66         if (null != status) {
67             if (status.equals(Constants.ENABLE)) {
68                 return true;
69             }
70         }
71         return false;
72     }
73
74     public static int getUpdateIntervalFromString(String value) {
75         int result = Constants.DEFAULT_AUTOMATION_INTERVAL;
76         if (null != value) {
77             try {
78                 result = Integer.parseInt(value);
79             } catch (NumberFormatException e) {
80                 Activator
81                         .getDefault()
82                         .getLogManager()
83                         .log(Level.ERROR.ordinal(),
84                                 new Date(),
85                                 getSimulatorErrorString(
86                                         e,
87                                         "Update interval convertion failed."
88                                                 + "Taking the default value("
89                                                 + Constants.DEFAULT_AUTOMATION_INTERVAL
90                                                 + ")"));
91             }
92         }
93         return result;
94     }
95
96     public static List<String> convertSetToList(Set<String> typeSet) {
97         if (null == typeSet) {
98             return null;
99         }
100         List<String> list = new ArrayList<String>();
101         Iterator<String> typeItr = typeSet.iterator();
102         while (typeItr.hasNext()) {
103             list.add(typeItr.next());
104         }
105         return list;
106     }
107
108     public static List<SingleResource> getSingleResourceListFromSet(
109             Set<SingleResource> resources) {
110         if (null == resources) {
111             return null;
112         }
113         List<SingleResource> list = new ArrayList<SingleResource>();
114         Iterator<SingleResource> typeItr = resources.iterator();
115         while (typeItr.hasNext()) {
116             list.add(typeItr.next());
117         }
118         return list;
119     }
120
121     public static Set<String> convertVectorToSet(Vector<String> vector) {
122         if (null == vector || vector.isEmpty()) {
123             return null;
124         }
125         Set<String> resultSet = new HashSet<String>();
126         Enumeration<String> e = vector.elements();
127         while (e.hasMoreElements()) {
128             resultSet.add(e.nextElement());
129         }
130         return resultSet;
131     }
132
133     public static String getSimulatorErrorString(Exception e, String info) {
134         if (null == e) {
135             return null;
136         }
137         String detail;
138         if (e instanceof SimulatorException) {
139             SimulatorException simEx = (SimulatorException) e;
140             detail = simEx.message() + "\n";
141             detail += "Exception Type: " + simEx.getClass().getSimpleName()
142                     + "\n";
143             detail += "Error code: " + simEx.code().toString();
144         } else {
145             if (null != info && !info.isEmpty())
146                 detail = info + "\n";
147             else
148                 detail = "Description not available\n";
149             detail += "Exception Type: " + e.getClass().getSimpleName() + "\n";
150             String msg = e.getMessage();
151             if (null != msg && !msg.isEmpty()) {
152                 detail += "Message: " + e.getMessage();
153             }
154         }
155         return detail;
156     }
157
158     public static Set<String> getAttributeTypes() {
159         Set<String> attTypes = new HashSet<String>();
160         ValueType[] types = ValueType.values();
161         if (null != types) {
162             attTypes.add(Constants.INT);
163             attTypes.add(Constants.DOUBLE);
164             attTypes.add(Constants.BOOL);
165             attTypes.add(Constants.STRING);
166         }
167         return attTypes;
168     }
169
170     public static ValueType getAttributeTypeEnum(String type) {
171         if (null != type && type.trim().length() > 0) {
172             if (type.equalsIgnoreCase(Constants.INT)) {
173                 return ValueType.INTEGER;
174             }
175             if (type.equalsIgnoreCase(Constants.DOUBLE)) {
176                 return ValueType.DOUBLE;
177             }
178             if (type.equalsIgnoreCase(Constants.BOOL)) {
179                 return ValueType.BOOLEAN;
180             }
181             if (type.equalsIgnoreCase(Constants.STRING)) {
182                 return ValueType.STRING;
183             }
184         }
185         return ValueType.UNKNOWN;
186     }
187
188     public static int[] convertSetToArrayInt(Set<Object> allowedValues) {
189         if (null == allowedValues || allowedValues.size() < 1) {
190             return null;
191         }
192         int[] arr = new int[allowedValues.size()];
193         Iterator<Object> itr = allowedValues.iterator();
194         try {
195             int i = 0;
196             while (itr.hasNext()) {
197                 arr[i++] = (int) itr.next();
198             }
199         } catch (Exception e) {
200             return null;
201         }
202         return arr;
203     }
204
205     public static double[] convertSetToArrayDouble(Set<Object> allowedValues) {
206         if (null == allowedValues || allowedValues.size() < 1) {
207             return null;
208         }
209         double[] arr = new double[allowedValues.size()];
210         Iterator<Object> itr = allowedValues.iterator();
211         try {
212             int i = 0;
213             while (itr.hasNext()) {
214                 arr[i++] = (double) itr.next();
215             }
216         } catch (Exception e) {
217             return null;
218         }
219         return arr;
220     }
221
222     public static boolean[] convertSetToArrayBoolean(Set<Object> allowedValues) {
223         if (null == allowedValues || allowedValues.size() < 1) {
224             return null;
225         }
226         boolean[] arr = new boolean[allowedValues.size()];
227         Iterator<Object> itr = allowedValues.iterator();
228         try {
229             int i = 0;
230             while (itr.hasNext()) {
231                 arr[i++] = (boolean) itr.next();
232             }
233         } catch (Exception e) {
234             return null;
235         }
236         return arr;
237     }
238
239     public static String[] convertSetToArrayString(Set<Object> allowedValues) {
240         if (null == allowedValues || allowedValues.size() < 1) {
241             return null;
242         }
243         String[] arr = new String[allowedValues.size()];
244         Iterator<Object> itr = allowedValues.iterator();
245         try {
246             int i = 0;
247             while (itr.hasNext()) {
248                 arr[i++] = (String) itr.next();
249             }
250         } catch (Exception e) {
251             return null;
252         }
253         return arr;
254     }
255
256     public static Vector<Integer> convertSetToVectorInt(
257             Set<Object> allowedValues) {
258         if (null == allowedValues || allowedValues.size() < 1) {
259             return null;
260         }
261         Vector<Integer> resultVec = new Vector<Integer>();
262         Iterator<Object> itr = allowedValues.iterator();
263         try {
264             while (itr.hasNext()) {
265                 resultVec.add((Integer) itr.next());
266             }
267         } catch (Exception e) {
268             return null;
269         }
270         return resultVec;
271     }
272
273     public static Vector<Double> convertSetToVectorDouble(
274             Set<Object> allowedValues) {
275         if (null == allowedValues || allowedValues.size() < 1) {
276             return null;
277         }
278         Vector<Double> resultVec = new Vector<Double>();
279         Iterator<Object> itr = allowedValues.iterator();
280         try {
281             while (itr.hasNext()) {
282                 resultVec.add((Double) itr.next());
283             }
284         } catch (Exception e) {
285             return null;
286         }
287         return resultVec;
288     }
289
290     public static Vector<String> convertSetToVectorString(
291             Set<String> allowedValues) {
292         if (null == allowedValues || allowedValues.size() < 1) {
293             return null;
294         }
295         Vector<String> resultVec = new Vector<String>();
296         Iterator<String> itr = allowedValues.iterator();
297         try {
298             while (itr.hasNext()) {
299                 resultVec.add((String) itr.next());
300             }
301         } catch (Exception e) {
302             return null;
303         }
304         return resultVec;
305     }
306
307     public static Set<Object> convertSetStringToSetObject(Set<String> values,
308             ValueType type) {
309         if (null == values || values.isEmpty()) {
310             return null;
311         }
312         Set<Object> resultSet = new HashSet<Object>();
313         if (AttributeValue.ValueType.INTEGER == type) {
314             int val;
315             Iterator<String> itr = values.iterator();
316             while (itr.hasNext()) {
317                 try {
318                     val = Integer.parseInt(itr.next());
319                     resultSet.add(val);
320                 } catch (NumberFormatException nfe) {
321                     Activator
322                             .getDefault()
323                             .getLogManager()
324                             .log(Level.ERROR.ordinal(),
325                                     new Date(),
326                                     "There is an error while doing internal convertion(string set to object set).\n"
327                                             + Utility.getSimulatorErrorString(
328                                                     nfe, null));
329                 }
330             }
331         } else if (AttributeValue.ValueType.DOUBLE == type) {
332             double val;
333             Iterator<String> itr = values.iterator();
334             while (itr.hasNext()) {
335                 try {
336                     val = Double.parseDouble(itr.next());
337                     resultSet.add(val);
338                 } catch (NumberFormatException nfe) {
339                     Activator
340                             .getDefault()
341                             .getLogManager()
342                             .log(Level.ERROR.ordinal(),
343                                     new Date(),
344                                     "There is an error while doing internal convertion(string set to object set).\n"
345                                             + Utility.getSimulatorErrorString(
346                                                     nfe, null));
347                 }
348             }
349         } else if (AttributeValue.ValueType.BOOLEAN == type) {
350             resultSet.add(true);
351             resultSet.add(false);
352         } else if (AttributeValue.ValueType.STRING == type) {
353             Iterator<String> itr = values.iterator();
354             while (itr.hasNext()) {
355                 resultSet.add(itr.next());
356             }
357         }
358         return resultSet;
359     }
360
361     public static List<Resource> convertSingleTypeResourceListToBaseType(
362             List<SingleResource> resources) {
363         if (null == resources || resources.isEmpty()) {
364             return null;
365         }
366         List<Resource> resultSet = new ArrayList<Resource>();
367         Iterator<SingleResource> itr = resources.iterator();
368         while (itr.hasNext()) {
369             resultSet.add(itr.next());
370         }
371         return resultSet;
372     }
373
374     public static String[] convertListToStringArray(List<String> valueList) {
375         String[] strArr;
376         if (null != valueList && valueList.size() > 0) {
377             strArr = valueList.toArray(new String[1]);
378         } else {
379             strArr = new String[1];
380         }
381         return strArr;
382     }
383
384     public static Comparator<Resource>         resourceComparator       = new Comparator<Resource>() {
385                                                                             public int compare(
386                                                                                     Resource res1,
387                                                                                     Resource res2) {
388                                                                                 String s1 = res1
389                                                                                         .getResourceName();
390                                                                                 String s2 = res2
391                                                                                         .getResourceName();
392
393                                                                                 String s1Part = s1
394                                                                                         .replaceAll(
395                                                                                                 "\\d",
396                                                                                                 "");
397                                                                                 String s2Part = s2
398                                                                                         .replaceAll(
399                                                                                                 "\\d",
400                                                                                                 "");
401
402                                                                                 if (s1Part
403                                                                                         .equalsIgnoreCase(s2Part)) {
404                                                                                     return extractInt(s1)
405                                                                                             - extractInt(s2);
406                                                                                 }
407                                                                                 return s1
408                                                                                         .compareTo(s2);
409                                                                             }
410
411                                                                             int extractInt(
412                                                                                     String s) {
413                                                                                 String num = s
414                                                                                         .replaceAll(
415                                                                                                 "\\D",
416                                                                                                 "");
417                                                                                 // return
418                                                                                 // 0
419                                                                                 // if
420                                                                                 // no
421                                                                                 // digits
422                                                                                 // found
423                                                                                 return num
424                                                                                         .isEmpty() ? 0
425                                                                                         : Integer
426                                                                                                 .parseInt(num);
427                                                                             }
428                                                                         };
429
430     public static Comparator<SingleResource>   singleResourceComparator = new Comparator<SingleResource>() {
431                                                                             public int compare(
432                                                                                     SingleResource res1,
433                                                                                     SingleResource res2) {
434                                                                                 String s1 = res1
435                                                                                         .getResourceName();
436                                                                                 String s2 = res2
437                                                                                         .getResourceName();
438
439                                                                                 String s1Part = s1
440                                                                                         .replaceAll(
441                                                                                                 "\\d",
442                                                                                                 "");
443                                                                                 String s2Part = s2
444                                                                                         .replaceAll(
445                                                                                                 "\\d",
446                                                                                                 "");
447
448                                                                                 if (s1Part
449                                                                                         .equalsIgnoreCase(s2Part)) {
450                                                                                     return extractInt(s1)
451                                                                                             - extractInt(s2);
452                                                                                 }
453                                                                                 return s1
454                                                                                         .compareTo(s2);
455                                                                             }
456
457                                                                             int extractInt(
458                                                                                     String s) {
459                                                                                 String num = s
460                                                                                         .replaceAll(
461                                                                                                 "\\D",
462                                                                                                 "");
463                                                                                 // return
464                                                                                 // 0
465                                                                                 // if
466                                                                                 // no
467                                                                                 // digits
468                                                                                 // found
469                                                                                 return num
470                                                                                         .isEmpty() ? 0
471                                                                                         : Integer
472                                                                                                 .parseInt(num);
473                                                                             }
474                                                                         };
475
476     public static Comparator<AttributeElement> attributeComparator      = new Comparator<AttributeElement>() {
477                                                                             public int compare(
478                                                                                     AttributeElement att1,
479                                                                                     AttributeElement att2) {
480                                                                                 String s1 = att1
481                                                                                         .getSimulatorResourceAttribute()
482                                                                                         .name();
483                                                                                 String s2 = att2
484                                                                                         .getSimulatorResourceAttribute()
485                                                                                         .name();
486
487                                                                                 String s1Part = s1
488                                                                                         .replaceAll(
489                                                                                                 "\\d",
490                                                                                                 "");
491                                                                                 String s2Part = s2
492                                                                                         .replaceAll(
493                                                                                                 "\\d",
494                                                                                                 "");
495
496                                                                                 if (s1Part
497                                                                                         .equalsIgnoreCase(s2Part)) {
498                                                                                     return extractInt(s1)
499                                                                                             - extractInt(s2);
500                                                                                 }
501                                                                                 return s1
502                                                                                         .compareTo(s2);
503                                                                             }
504
505                                                                             int extractInt(
506                                                                                     String s) {
507                                                                                 String num = s
508                                                                                         .replaceAll(
509                                                                                                 "\\D",
510                                                                                                 "");
511
512                                                                                 // Return
513                                                                                 // 0
514                                                                                 // if
515                                                                                 // no
516                                                                                 // digits
517                                                                                 // found
518                                                                                 return num
519                                                                                         .isEmpty() ? 0
520                                                                                         : Integer
521                                                                                                 .parseInt(num);
522                                                                             }
523                                                                         };
524
525     // This method only works for attributes whose values are of type int,
526     // double, bool, string and 1-D array of primitive types
527     public static String getAttributeValueAsString(AttributeValue val) {
528         if (null == val) {
529             return null;
530         }
531
532         Object value = val.get();
533         if (null == value) {
534             return null;
535         }
536
537         TypeInfo type = val.typeInfo();
538         if (type.mBaseType == ValueType.RESOURCEMODEL
539                 || (type.mType == ValueType.ARRAY && type.mDepth > 1)) {
540             return null;
541         }
542
543         AttributeValueStringConverter converter = new AttributeValueStringConverter(
544                 val);
545         return converter.toString();
546     }
547
548     public static boolean isUriValid(String resURI) {
549         if (null == resURI || resURI.length() < 2 || resURI.length() > 63
550                 || !resURI.startsWith("/") || resURI.endsWith("/")
551                 || resURI.contains("/..") || resURI.contains("//")
552                 || resURI.contains("/./") || resURI.contains("?")
553                 || resURI.contains("#") || resURI.contains("%")) {
554             return false;
555         }
556         return true;
557     }
558
559     public static boolean isResourceTypeValid(String resType) {
560         if (null == resType || resType.isEmpty()) {
561             return false;
562         }
563
564         char[] ch = resType.toCharArray();
565         for (char c : ch) {
566             if (c != '.' && c != '-' && (c < 'a' || c > 'z')
567                     && (c < '0' || c > '9')) {
568                 return false;
569             }
570         }
571
572         return true;
573     }
574
575     public static Map<String, String> getResourceInterfaces(
576             Class<? extends Resource> resourceClass) {
577         Map<String, String> ifTypes = null;
578         if (resourceClass == SingleResource.class) {
579             ifTypes = new HashMap<String, String>();
580             ifTypes.put(Constants.BASELINE_INTERFACE, "Baseline");
581             ifTypes.put(Constants.READ_ONLY_INTERFACE, "Read-Only");
582             ifTypes.put(Constants.READ_WRITE_INTERFACE, "Read-Write");
583             ifTypes.put(Constants.ACTUATOR_INTERFACE, "Actuator");
584             ifTypes.put(Constants.SENSOR_INTERFACE, "Sensor");
585         }
586         return ifTypes;
587     }
588
589     public static String removeWhiteSpacesInArrayValues(String value) {
590         if (null == value || value.isEmpty())
591             return null;
592
593         value = value.trim();
594
595         String token[] = value.split(",");
596         StringBuilder result = new StringBuilder();
597         for (int i = 0; i < token.length; i++) {
598             result.append(token[i].trim());
599             if (i + 1 < token.length) {
600                 result.append(",");
601             }
602         }
603
604         return result.toString();
605     }
606
607     public static AttributeValue cloneAttributeValue(AttributeValue value)
608             throws InvalidArgsException, NullPointerException {
609         AttributeValue clone = null;
610
611         AttributeValue.TypeInfo typeInfo = value.typeInfo();
612
613         if (typeInfo.mType == AttributeValue.ValueType.RESOURCEMODEL) {
614             SimulatorResourceModel resModel = (SimulatorResourceModel) value
615                     .get();
616             SimulatorResourceModel modelCopy = new SimulatorResourceModel();
617
618             for (Map.Entry<String, AttributeValue> entry : resModel.get()
619                     .entrySet()) {
620                 String attName = entry.getKey();
621                 AttributeValue attValue = entry.getValue();
622                 modelCopy.set(attName, cloneAttributeValue(attValue));
623             }
624             clone = new AttributeValue(modelCopy);
625         } else if (typeInfo.mType == AttributeValue.ValueType.ARRAY
626                 && typeInfo.mBaseType == AttributeValue.ValueType.RESOURCEMODEL) {
627             if (typeInfo.mDepth == 1) {
628                 SimulatorResourceModel[] resModelArray = (SimulatorResourceModel[]) value
629                         .get();
630                 SimulatorResourceModel[] modelArrayCopy = new SimulatorResourceModel[resModelArray.length];
631                 for (int i = 0; i < resModelArray.length; i++) {
632                     AttributeValue attValue = cloneAttributeValue(new AttributeValue(
633                             resModelArray[i]));
634                     if (null != attValue) {
635                         modelArrayCopy[i] = (SimulatorResourceModel) attValue
636                                 .get();
637                     }
638                 }
639                 clone = new AttributeValue(modelArrayCopy);
640             } else if (typeInfo.mDepth == 2) {
641                 SimulatorResourceModel[][] resModelArray = (SimulatorResourceModel[][]) value
642                         .get();
643                 SimulatorResourceModel[][] modelArrayCopy = new SimulatorResourceModel[resModelArray.length][];
644                 for (int i = 0; i < resModelArray.length; i++) {
645                     AttributeValue attValue = cloneAttributeValue(new AttributeValue(
646                             resModelArray[i]));
647                     if (null != attValue) {
648                         modelArrayCopy[i] = (SimulatorResourceModel[]) attValue
649                                 .get();
650                     }
651                 }
652                 clone = new AttributeValue(modelArrayCopy);
653             } else if (typeInfo.mDepth == 3) {
654                 SimulatorResourceModel[][][] resModelArray = (SimulatorResourceModel[][][]) value
655                         .get();
656                 SimulatorResourceModel[][][] modelArrayCopy = new SimulatorResourceModel[resModelArray.length][][];
657                 for (int i = 0; i < resModelArray.length; i++) {
658                     AttributeValue attValue = cloneAttributeValue(new AttributeValue(
659                             resModelArray[i]));
660                     if (null != attValue) {
661                         modelArrayCopy[i] = (SimulatorResourceModel[][]) attValue
662                                 .get();
663                     }
664                 }
665                 clone = new AttributeValue(modelArrayCopy);
666             }
667         } else {
668             String attValueInString = new AttributeValueStringConverter(value)
669                     .toString();
670             clone = AttributeValueBuilder.build(attValueInString,
671                     typeInfo.mBaseType);
672         }
673
674         return clone;
675     }
676 }