aboutsummaryrefslogtreecommitdiffstats
path: root/common/openecomp-common-configuration-management/openecomp-configuration-management-core/src/main/java/org/openecomp/config/ConfigurationUtils.java
blob: c0a1e0ceb0b6087e13e38e4041c25ea7345ad290 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
package org.openecomp.config;

import static org.openecomp.config.api.Hint.EXTERNAL_LOOKUP;
import static org.openecomp.config.api.Hint.LATEST_LOOKUP;
import static org.openecomp.config.api.Hint.NODE_SPECIFIC;

import com.virtlink.commons.configuration2.jackson.JsonConfiguration;
import net.sf.corn.cps.CPScanner;
import net.sf.corn.cps.ResourceFilter;
import org.apache.commons.configuration2.CompositeConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.BasicConfigurationBuilder;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.io.IOUtils;
import org.openecomp.config.api.ConfigurationManager;
import org.openecomp.config.impl.AgglomerateConfiguration;
import org.openecomp.config.impl.ConfigurationDataSource;
import org.openecomp.config.impl.ConfigurationRepository;
import org.openecomp.config.impl.YamlConfiguration;
import org.openecomp.config.type.ConfigurationMode;
import org.openecomp.config.type.ConfigurationType;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TransferQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;

/**
 * The type Configuration utils.
 */
public class ConfigurationUtils {

  /**
   * Gets scheduled executor service.
   *
   * @return the scheduled executor service
   */
  public static ScheduledExecutorService getScheduledExecutorService() {
    return Executors.newScheduledThreadPool(1, (r1) -> {
      Thread thread = Executors.privilegedThreadFactory().newThread(r1);
      thread.setDaemon(true);
      return thread;
    });
  }

  /**
   * Gets thread factory.
   *
   * @return the thread factory
   */
  public static ThreadFactory getThreadFactory() {
    return (r1) -> {
      Thread thread = Executors.privilegedThreadFactory().newThread(r1);
      thread.setDaemon(true);
      return thread;
    };
  }

  /**
   * Gets all files.
   *
   * @param file          the file
   * @param recursive     the recursive
   * @param onlyDirectory the only directory
   * @return the all files
   */
  public static Collection<File> getAllFiles(File file, boolean recursive, boolean onlyDirectory) {
    ArrayList<File> collection = new ArrayList<>();
    if (file.isDirectory() && file.exists()) {
      File[] files = file.listFiles();
      for (File innerFile : files) {
        if (innerFile.isFile() && !onlyDirectory) {
          collection.add(innerFile);
        } else if (innerFile.isDirectory()) {
          collection.add(innerFile);
          if (recursive) {
            collection.addAll(getAllFiles(innerFile, recursive, onlyDirectory));
          }
        }
      }
    }
    return collection;
  }

  /**
   * Gets comma saperated list.
   *
   * @param list the list
   * @return the comma saperated list
   */
  public static String getCommaSaperatedList(List list) {
    String toReturn = "";

    for (Object obj : list) {
      if (!toReturn.trim().isEmpty()) {
        toReturn += ",";
      }
      toReturn += obj;
    }

    return toReturn;
  }

  /**
   * Gets comma saperated list.
   *
   * @param list the list
   * @return the comma saperated list
   */
  public static String getCommaSaperatedList(String[] list) {
    return getCommaSaperatedList(list == null ? Arrays.asList() : Arrays.asList(list));
  }

  /**
   * Gets config type.
   *
   * @param url the url
   * @return the config type
   */
  public static ConfigurationType getConfigType(URL url) {
    return Enum.valueOf(ConfigurationType.class,
        url.getFile().substring(url.getFile().lastIndexOf('.') + 1).toUpperCase());
  }

  /**
   * Gets config type.
   *
   * @param file the file
   * @return the config type
   */
  public static ConfigurationType getConfigType(File file) {
    return Enum.valueOf(ConfigurationType.class,
        file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf('.') + 1)
            .toUpperCase());
  }

  /**
   * Is config boolean.
   *
   * @param url the url
   * @return the boolean
   */
  public static boolean isConfig(URL url) {
    return isConfig(url.getFile());
  }

  /**
   * Is config boolean.
   *
   * @param file the file
   * @return the boolean
   */
  public static boolean isConfig(File file) {
    return file != null && file.exists() && isConfig(file.getName());
  }

  /**
   * Is config boolean.
   *
   * @param file the file
   * @return the boolean
   */
  public static boolean isConfig(String file) {
    file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
    file = file.substring(file.lastIndexOf('/') + 1);
    return file.matches(
        "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
            + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
            + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
            + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$")
        || file.matches("CONFIG(.)*\\.(" + ConfigurationType.PROPERTIES.name() + "|"
            + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
            + ConfigurationType.YAML.name() + ")$");
  }

  /**
   * Gets namespace.
   *
   * @param url the url
   * @return the namespace
   */
  public static String getNamespace(URL url) {
    String namespace = getNamespace(getConfiguration(url));
    if (namespace != null) {
      return namespace.toUpperCase();
    }
    return getNamespace(url.getFile().toUpperCase());
  }

  /**
   * Gets namespace.
   *
   * @param file the file
   * @return the namespace
   */
  public static String getNamespace(File file) {
    String namespace = getNamespace(getConfiguration(file));
    if (namespace != null) {
      return namespace.toUpperCase();
    }
    return getNamespace(file.getName().toUpperCase());
  }

  private static String getNamespace(Configuration config) {
    return config.getString(Constants.NAMESPACE_KEY) == null ? null
        : config.getString(Constants.NAMESPACE_KEY).toUpperCase();
  }

  /**
   * Gets namespace.
   *
   * @param file the file
   * @return the namespace
   */
  public static String getNamespace(String file) {
    file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
    file = file.substring(file.lastIndexOf('/') + 1);
    Pattern pattern = Pattern.compile(
        "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
            + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
            + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
            + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
    Matcher matcher = pattern.matcher(file);
    boolean b1 = matcher.matches();
    if (b1) {
      if (matcher.group(1) != null) {
        String moduleName = matcher.group(1).substring(1);
        return moduleName.equalsIgnoreCase(ConfigurationMode.OVERRIDE.name())
            || moduleName.equalsIgnoreCase(ConfigurationMode.UNION.name())
            || moduleName.equalsIgnoreCase(ConfigurationMode.MERGE.name())
            ? Constants.DEFAULT_NAMESPACE : moduleName;
      } else {
        return Constants.DEFAULT_NAMESPACE;
      }
    } else if (isConfig(file)) {
      return Constants.DEFAULT_NAMESPACE;
    }

    return null;
  }

  /**
   * Gets merge strategy.
   *
   * @param url the url
   * @return the merge strategy
   */
  public static ConfigurationMode getMergeStrategy(URL url) {
    String configMode = getMergeStrategy(getConfiguration(url));
    if (configMode != null) {
      try {
        return Enum.valueOf(ConfigurationMode.class, configMode);
      } catch (Exception exception) {
        //do nothing
      }
    }
    return getMergeStrategy(url.getFile().toUpperCase());
  }

  private static String getMergeStrategy(Configuration config) {
    return config.getString(Constants.MODE_KEY) == null ? null
        : config.getString(Constants.MODE_KEY).toUpperCase();
  }

  /**
   * Gets merge strategy.
   *
   * @param file the file
   * @return the merge strategy
   */
  public static ConfigurationMode getMergeStrategy(File file) {
    String configMode = getMergeStrategy(getConfiguration(file));
    if (configMode != null) {
      try {
        return Enum.valueOf(ConfigurationMode.class, configMode);
      } catch (Exception exception) {
        //do nothing
      }
    }
    return getMergeStrategy(file.getName().toUpperCase());
  }

  /**
   * Gets merge strategy.
   *
   * @param file the file
   * @return the merge strategy
   */
  public static ConfigurationMode getMergeStrategy(String file) {
    file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
    file = file.substring(file.lastIndexOf('/') + 1);
    Pattern pattern = Pattern.compile(
        "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
            + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
            + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
            + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
    Matcher matcher = pattern.matcher(file);
    boolean b1 = matcher.matches();
    if (b1) {
      for (int i = 1; i <= matcher.groupCount(); i++) {
        String modeName = matcher.group(i);
        if (modeName != null) {
          modeName = modeName.substring(1);
        }
        try {
          return Enum.valueOf(ConfigurationMode.class, modeName);
        } catch (Exception exception) {
          //do nothing
        }
      }
    }

    return null;
  }

  /**
   * Gets configuration.
   *
   * @param url the url
   * @return the configuration
   */
  public static FileBasedConfiguration getConfiguration(URL url) {
    FileBasedConfiguration builder = null;
    try {
      switch (ConfigurationUtils.getConfigType(url)) {
        case PROPERTIES:
          builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
          break;
        case XML:
          builder = new Configurations().fileBased(XMLConfiguration.class, url);
          break;
        case JSON:
          builder = new Configurations().fileBased(JsonConfiguration.class, url);
          break;
        case YAML:
          builder = new Configurations().fileBased(YamlConfiguration.class, url);
          break;
        default:
      }
    } catch (ConfigurationException exception) {
      exception.printStackTrace();
    }
    return builder;
  }

  /**
   * Gets configuration.
   *
   * @param url the url
   * @return the configuration
   */
  public static FileBasedConfiguration getConfiguration(File url) {
    FileBasedConfiguration builder = null;
    try {
      switch (ConfigurationUtils.getConfigType(url)) {
        case PROPERTIES:
          builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
          break;
        case XML:
          builder = new Configurations().fileBased(XMLConfiguration.class, url);
          break;
        case JSON:
          builder = new Configurations().fileBased(JsonConfiguration.class, url);
          break;
        case YAML:
          builder = new Configurations().fileBased(YamlConfiguration.class, url);
          break;
        default:
      }
    } catch (ConfigurationException exception) {
      exception.printStackTrace();
    }
    return builder;
  }

  /**
   * Gets collection generic type.
   *
   * @param field the field
   * @return the collection generic type
   */
  public static Class getCollectionGenericType(Field field) {
    Type type = field.getGenericType();

    if (type instanceof ParameterizedType) {

      ParameterizedType paramType = (ParameterizedType) type;
      Type[] arr = paramType.getActualTypeArguments();

      for (Type tp : arr) {
        Class<?> clzz = (Class<?>) tp;
        if (isWrapperClass(clzz)) {
          return clzz;
        } else {
          throw new RuntimeException("Collection of type " + clzz.getName() + " not supported.");
        }
      }
    }
    return String[].class;
  }

  /**
   * Gets array class.
   *
   * @param clazz the clazz
   * @return the array class
   */
  public static Class getArrayClass(Class clazz) {
    switch (clazz.getName()) {
      case "java.lang.Byte":
        return Byte[].class;
      case "java.lang.Short":
        return Short[].class;
      case "java.lang.Integer":
        return Integer[].class;
      case "java.lang.Long":
        return Long[].class;
      case "java.lang.Float":
        return Float[].class;
      case "java.lang.Double":
        return Double[].class;
      case "java.lang.Boolean":
        return Boolean[].class;
      case "java.lang.Character":
        return Character[].class;
      case "java.lang.String":
        return String[].class;
      default:
    }
    return null;
  }

  /**
   * Gets all class path resources.
   *
   * @return the all class path resources
   */
  public static List<URL> getAllClassPathResources() {
    return CPScanner.scanResources(new ResourceFilter());
  }

  /**
   * Execute ddlsql boolean.
   *
   * @param sql the sql
   * @return the boolean
   * @throws Exception the exception
   */
  public static boolean executeDdlSql(String sql) throws Exception {
    DataSource datasource = ConfigurationDataSource.lookup();
    try (Connection con = datasource.getConnection(); Statement stmt = con.createStatement()) {
      stmt.executeQuery(sql);
    } catch (Exception exception) {
      System.err.println("Datasource initialization error. Configuration management will be using in-memory persistence.");
      return false;
    }
    return true;
  }

  /**
   * Gets configuration builder.
   *
   * @param url the url
   * @return the configuration builder
   */
  public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(URL url) {
    ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = null;
    switch (ConfigurationUtils.getConfigType(url)) {
      case PROPERTIES:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class);
        break;
      case XML:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            XMLConfiguration.class);
        break;
      case JSON:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            JsonConfiguration.class);
        break;
      case YAML:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            YamlConfiguration.class);
        break;
      default:
    }
    builder.configure(new Parameters().fileBased().setURL(url)
        .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
    return builder;
  }

  /**
   * Gets configuration builder.
   *
   * @param file     the file
   * @param autoSave the auto save
   * @return the configuration builder
   */
  public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(File file,
                                                                                boolean autoSave) {
    ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = null;
    switch (ConfigurationUtils.getConfigType(file)) {
      case PROPERTIES:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class);
        break;
      case XML:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            XMLConfiguration.class);
        break;
      case JSON:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            JsonConfiguration.class);
        break;
      case YAML:
        builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
            YamlConfiguration.class);
        break;
      default:
    }
    builder.configure(new Parameters().fileBased().setFile(file)
        .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
    builder.setAutoSave(autoSave);
    return builder;
  }


  /**
   * Execute select sql collection.
   *
   * @param sql    the sql
   * @param params the params
   * @return the collection
   * @throws Exception the exception
   */
  public static Collection<String> executeSelectSql(String sql, String[] params) throws Exception {
    Collection<String> coll = new ArrayList<>();
    DataSource datasource = ConfigurationDataSource.lookup();
    try (Connection con = datasource.getConnection();
         PreparedStatement stmt = con.prepareStatement(sql)) {
      if (params != null) {
        for (int i = 0; i < params.length; i++) {
          stmt.setString(i + 1, params[i]);
        }
      }
      ResultSet rs = stmt.executeQuery();
      while (rs.next()) {
        coll.add(rs.getString(1));
      }
    } catch (Exception exception) {
      //exception.printStackTrace();
      return null;
    }
    return coll;
  }

  /**
   * Execute insert sql boolean.
   *
   * @param sql    the sql
   * @param params the params
   * @return the boolean
   * @throws Exception the exception
   */
  public static boolean executeInsertSql(String sql, Object[] params) throws Exception {
    Collection<String> coll = new ArrayList<>();
    DataSource datasource = ConfigurationDataSource.lookup();
    try (Connection con = datasource.getConnection();
         PreparedStatement stmt = con.prepareStatement(sql)) {
      if (params != null) {
        int counter = 0;
        for (Object obj : params) {
          if (obj == null) {
            obj = "";
          }
          switch (obj.getClass().getName()) {
            case "java.lang.String":
              stmt.setString(++counter, obj.toString());
              break;
            case "java.lang.Integer":
              stmt.setInt(++counter, ((Integer) obj).intValue());
              break;
            case "java.lang.Long":
              stmt.setLong(++counter, ((Long) obj).longValue());
              break;
            default:
              stmt.setString(++counter, obj.toString());
              break;
          }
        }
      }
      stmt.executeUpdate();
      return true;
    } catch (Exception exception) {
      exception.printStackTrace();
    }
    return false;
  }

  /**
   * Read t.
   *
   * @param <T>       the type parameter
   * @param config    the config
   * @param clazz     the clazz
   * @param keyPrefix the key prefix
   * @return the t
   * @throws Exception the exception
   */
  public static <T> T read(Configuration config, Class<T> clazz, String keyPrefix)
      throws Exception {
    org.openecomp.config.api.Config confAnnot =
        clazz.getAnnotation(org.openecomp.config.api.Config.class);
    if (confAnnot != null) {
      keyPrefix += (confAnnot.key() + ".");
    }
    T objToReturn = clazz.newInstance();
    for (Field field : clazz.getDeclaredFields()) {
      org.openecomp.config.api.Config fieldConfAnnot =
          field.getAnnotation(org.openecomp.config.api.Config.class);
      if (fieldConfAnnot != null) {
        field.setAccessible(true);
        field.set(objToReturn, config.getProperty(keyPrefix + fieldConfAnnot.key()));
      } else if (field.getType().getAnnotation(org.openecomp.config.api.Config.class) != null) {
        field.set(objToReturn, read(config, field.getType(), keyPrefix));
      }
    }
    return objToReturn;
  }

  /**
   * Gets db configuration builder.
   *
   * @param configName the config name
   * @return the db configuration builder
   * @throws Exception the exception
   */
  public static BasicConfigurationBuilder<AgglomerateConfiguration> getDbConfigurationBuilder(
      String configName) throws Exception {
    Configuration dbConfig = ConfigurationRepository.lookup()
        .getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE);
    BasicConfigurationBuilder<AgglomerateConfiguration> builder =
        new BasicConfigurationBuilder<AgglomerateConfiguration>(AgglomerateConfiguration.class);
    builder.configure(
        new Parameters().database()
            .setDataSource(ConfigurationDataSource.lookup())
            .setTable(dbConfig.getString("config.Table"))
            .setKeyColumn(dbConfig.getString("configKey"))
            .setValueColumn(dbConfig.getString("configValue"))
            .setConfigurationNameColumn(dbConfig.getString("configNameColumn"))
            .setConfigurationName(configName)
            .setAutoCommit(true)
    );
    return builder;
  }

  /**
   * Gets property.
   *
   * @param config          the config
   * @param key             the key
   * @param processingHints the processing hints
   * @return the property
   */
  public static Object getProperty(Configuration config, String key, int processingHints) {
    if (!isDirectLookup(processingHints)) {
      if (config instanceof AgglomerateConfiguration) {
        return ((AgglomerateConfiguration) config).getPropertyValue(key);
      } else if (config instanceof CompositeConfiguration) {
        CompositeConfiguration conf = (CompositeConfiguration) config;
        for (int i = 0; i < conf.getNumberOfConfigurations(); i++) {
          if (conf.getConfiguration(i) instanceof AgglomerateConfiguration) {
            return ((AgglomerateConfiguration) conf.getConfiguration(i)).getPropertyValue(key);
          } else if (isNodeSpecific(processingHints)) {
            Object obj = conf.getConfiguration(i).getProperty(key);
            if (obj != null) {
              return obj;
            }
          }
        }
      }
    }
    return config.getProperty(key);
  }

  /**
   * Gets primitive array.
   *
   * @param collection the collection
   * @param clazz      the clazz
   * @return the primitive array
   */
  public static Object getPrimitiveArray(Collection collection, Class clazz) {

    if (clazz == int.class) {
      int[] array = new int[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (int) objArray[i];
      }
      return array;
    }
    if (clazz == byte.class) {
      byte[] array = new byte[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (byte) objArray[i];
      }
      return array;
    }
    if (clazz == short.class) {
      short[] array = new short[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (short) objArray[i];
      }
      return array;
    }
    if (clazz == long.class) {
      long[] array = new long[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (long) objArray[i];
      }
      return array;
    }
    if (clazz == float.class) {
      float[] array = new float[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (float) objArray[i];
      }
      return array;
    }
    if (clazz == double.class) {
      double[] array = new double[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (double) objArray[i];
      }
      return array;
    }
    if (clazz == boolean.class) {
      boolean[] array = new boolean[collection.size()];
      Object[] objArray = collection.toArray();
      for (int i = 0; i < collection.size(); i++) {
        array[i] = (boolean) objArray[i];
      }
      return array;
    }
    Object obj = null;
    return obj;
  }

  /**
   * Is wrapper class boolean.
   *
   * @param clazz the clazz
   * @return the boolean
   */
  public static boolean isWrapperClass(Class clazz) {
    return clazz == String.class || clazz == Boolean.class || clazz == Character.class
        || Number.class.isAssignableFrom(clazz);
  }

  /**
   * Gets collection string.
   *
   * @param input the input
   * @return the collection string
   */
  public static String getCollectionString(String input) {
    Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
    Matcher matcher = pattern.matcher(input);
    if (matcher.matches()) {
      input = matcher.group(1);
    }
    return input;
  }

  /**
   * Is collection boolean.
   *
   * @param input the input
   * @return the boolean
   */
  public static boolean isCollection(String input) {
    Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
    Matcher matcher = pattern.matcher(input);
    return matcher.matches();
  }

  /**
   * Process variables if present string.
   *
   * @param tenant    the tenant
   * @param namespace the namespace
   * @param data      the data
   * @return the string
   */
  public static String processVariablesIfPresent(String tenant, String namespace, String data) {
    Pattern pattern = Pattern.compile("^.*\\$\\{(.*)\\}.*");
    Matcher matcher = pattern.matcher(data);
    if (matcher.matches()) {
      String key = matcher.group(1);
      if (key.toUpperCase().startsWith("ENV:")) {
        String envValue = System.getenv(key.substring(4));
        return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
            envValue == null ? "" : envValue.replace("\\", "\\\\")));
      } else if (key.toUpperCase().startsWith("SYS:")) {
        String sysValue = System.getProperty(key.substring(4));
        return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
            sysValue == null ? "" : sysValue.replace("\\", "\\\\")));
      } else {
        String propertyValue = ConfigurationUtils.getCollectionString(
            ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key).toString());
        return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
            propertyValue == null ? "" : propertyValue.replace("\\", "\\\\")));
      }
    } else {
      return data;
    }
  }

  /**
   * Gets file contents.
   *
   * @param path the path
   * @return the file contents
   */
  public static String getFileContents(String path) {
    try {
      if (path != null) {
        return IOUtils.toString(new URL(path));
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    }
    return null;
  }

  /**
   * Gets file contents.
   *
   * @param path the path
   * @return the file contents
   */
  public static String getFileContents(Path path) {
    try {
      if (path != null) {
        return new String(Files.readAllBytes(path));
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    }
    return null;
  }

  /**
   * Gets concrete collection.
   *
   * @param clazz the clazz
   * @return the concrete collection
   */
  public static Collection getConcreteCollection(Class clazz) {
    Collection collection = null;

    switch (clazz.getName()) {
      case "java.util.Collection":
      case "java.util.List":
        return new ArrayList<>();
      case "java.util.Set":
        return new HashSet<>();
      case "java.util.SortedSet":
        return new TreeSet<>();
      case "java.util.Queue":
        return new ConcurrentLinkedQueue<>();
      case "java.util.Deque":
        return new ArrayDeque<>();
      case "java.util.concurrent.TransferQueue":
        return new LinkedTransferQueue<>();
      case "java.util.concurrent.BlockingQueue":
        return new LinkedBlockingQueue<>();
      default:
    }

    return collection;
  }

  /**
   * Gets default for.
   *
   * @param clazz the clazz
   * @return the default for
   */
  public static Object getDefaultFor(Class clazz) {
    if (byte.class == clazz) {
      return new Byte("0");
    } else if (short.class == clazz) {
      return new Short("0");
    } else if (int.class == clazz) {
      return new Integer("0");
    } else if (float.class == clazz) {
      return new Float("0");
    } else if (long.class == clazz) {
      return new Long("0");
    } else if (double.class == clazz) {
      return new Double("0");
    } else if (boolean.class == clazz) {
      return Boolean.FALSE;
    }
    return new Character((char) 0);
  }

  /**
   * Gets compatible collection for abstract def.
   *
   * @param clazz the clazz
   * @return the compatible collection for abstract def
   */
  public static Collection getCompatibleCollectionForAbstractDef(Class clazz) {
    if (BlockingQueue.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(BlockingQueue.class);
    }
    if (TransferQueue.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(TransferQueue.class);
    }
    if (Deque.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(Deque.class);
    }
    if (Queue.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(Queue.class);
    }
    if (SortedSet.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(SortedSet.class);
    }
    if (Set.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(Set.class);
    }
    if (List.class.isAssignableFrom(clazz)) {
      return getConcreteCollection(List.class);
    }
    return null;
  }

  /**
   * Gets configuration repository key.
   *
   * @param array the array
   * @return the configuration repository key
   */
  public static String getConfigurationRepositoryKey(String[] array) {
    Stack<String> stack = new Stack<>();
    stack.push(Constants.DEFAULT_TENANT);
    for (String element : array) {
      stack.push(element);
    }
    String toReturn = stack.pop();
    return stack.pop() + Constants.KEY_ELEMENTS_DELEMETER + toReturn;
  }

  /**
   * Gets configuration repository key.
   *
   * @param file the file
   * @return the configuration repository key
   */
  public static String getConfigurationRepositoryKey(File file) {
    return getConfigurationRepositoryKey(
        ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SAPERATOR));
  }

  /**
   * Gets configuration repository key.
   *
   * @param url the url
   * @return the configuration repository key
   */
  public static String getConfigurationRepositoryKey(URL url) {
    return getConfigurationRepositoryKey(
        ConfigurationUtils.getNamespace(url).split(Constants.TENANT_NAMESPACE_SAPERATOR));
  }

  /**
   * To map linked hash map.
   *
   * @param config the config
   * @return the linked hash map
   */
  public static LinkedHashMap toMap(Configuration config) {
    Iterator<String> iterator = config.getKeys();
    LinkedHashMap<String, String> map = new LinkedHashMap<>();
    while (iterator.hasNext()) {
      String key = iterator.next();
      if (!(key.equals(Constants.MODE_KEY) || key.equals(Constants.NAMESPACE_KEY)
          || key.equals(Constants.LOAD_ORDER_KEY))) {
        map.put(key, config.getProperty(key).toString());
      }
    }

    return map;
  }

  /**
   * Diff map.
   *
   * @param orig   the orig
   * @param latest the latest
   * @return the map
   */
  public static Map diff(LinkedHashMap orig, LinkedHashMap latest) {
    orig = new LinkedHashMap<>(orig);
    latest = new LinkedHashMap<>(latest);
    List<String> set = new ArrayList(orig.keySet());
    for (String key : set) {
      if (latest.remove(key, orig.get(key))) {
        orig.remove(key);
      }
    }
    Set<String> keys = latest.keySet();
    for (String key : keys) {
      orig.remove(key);
    }
    set = new ArrayList(orig.keySet());
    for (String key : set) {
      latest.put(key, "");
    }
    return new HashMap<>(latest);
  }

  /**
   * Is array boolean.
   *
   * @param tenant          the tenant
   * @param namespace       the namespace
   * @param key             the key
   * @param processingHints the processing hints
   * @return the boolean
   * @throws Exception the exception
   */
  public static boolean isArray(String tenant, String namespace, String key, int processingHints)
      throws Exception {
    Object obj = ConfigurationUtils
        .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key,
            processingHints);
    return (obj == null) ? false : ConfigurationUtils.isCollection(obj.toString());
  }

  /**
   * Is direct lookup boolean.
   *
   * @param hints the hints
   * @return the boolean
   */
  public static boolean isDirectLookup(int hints) {
    return (hints & LATEST_LOOKUP.value()) == LATEST_LOOKUP.value();
  }

  /**
   * Is external lookup boolean.
   *
   * @param hints the hints
   * @return the boolean
   */
  public static boolean isExternalLookup(int hints) {
    return (hints & EXTERNAL_LOOKUP.value()) == EXTERNAL_LOOKUP.value();
  }

  /**
   * Is node specific boolean.
   *
   * @param hints the hints
   * @return the boolean
   */
  public static boolean isNodeSpecific(int hints) {
    return (hints & NODE_SPECIFIC.value()) == NODE_SPECIFIC.value();
  }

  public static boolean isZeroLengthArray(Class clazz, Object obj){
    if (clazz.isArray() && clazz.getComponentType().isPrimitive()){
      if (clazz.getComponentType()==int.class){
        return ((int[])obj).length==0;
      }else if (clazz.getComponentType()==byte.class){
        return ((byte[])obj).length==0;
      }else if (clazz.getComponentType()==short.class){
        return ((short[])obj).length==0;
      }else if (clazz.getComponentType()==float.class){
        return ((float[])obj).length==0;
      }else if (clazz.getComponentType()==boolean.class){
        return ((boolean[])obj).length==0;
      }else if (clazz.getComponentType()==double.class){
        return ((double[])obj).length==0;
      }else if (clazz.getComponentType()==long.class){
        return ((long[])obj).length==0;
      }else{
        return ((Object[])obj).length==0;
      }
    }

    return false;
  }

  /**
   * Checks if value is blank
   * @param value
   * @return
   */
  public static boolean isBlank(String value){
    return value==null || value.trim().length()==0;
  }
}