1 package org.openecomp.config;
3 import static org.openecomp.config.api.Hint.EXTERNAL_LOOKUP;
4 import static org.openecomp.config.api.Hint.LATEST_LOOKUP;
5 import static org.openecomp.config.api.Hint.NODE_SPECIFIC;
7 import com.virtlink.commons.configuration2.jackson.JsonConfiguration;
8 import net.sf.corn.cps.CPScanner;
9 import net.sf.corn.cps.ResourceFilter;
10 import org.apache.commons.configuration2.CompositeConfiguration;
11 import org.apache.commons.configuration2.Configuration;
12 import org.apache.commons.configuration2.FileBasedConfiguration;
13 import org.apache.commons.configuration2.PropertiesConfiguration;
14 import org.apache.commons.configuration2.XMLConfiguration;
15 import org.apache.commons.configuration2.builder.BasicConfigurationBuilder;
16 import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
17 import org.apache.commons.configuration2.builder.fluent.Configurations;
18 import org.apache.commons.configuration2.builder.fluent.Parameters;
19 import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
20 import org.apache.commons.configuration2.ex.ConfigurationException;
21 import org.apache.commons.io.IOUtils;
22 import org.openecomp.config.api.ConfigurationManager;
23 import org.openecomp.config.impl.AgglomerateConfiguration;
24 import org.openecomp.config.impl.ConfigurationDataSource;
25 import org.openecomp.config.impl.ConfigurationRepository;
26 import org.openecomp.config.impl.YamlConfiguration;
27 import org.openecomp.config.type.ConfigurationMode;
28 import org.openecomp.config.type.ConfigurationType;
31 import java.lang.reflect.Field;
32 import java.lang.reflect.ParameterizedType;
33 import java.lang.reflect.Type;
35 import java.nio.file.Files;
36 import java.nio.file.Path;
37 import java.sql.Connection;
38 import java.sql.PreparedStatement;
39 import java.sql.ResultSet;
40 import java.sql.Statement;
41 import java.util.ArrayDeque;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Deque;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.LinkedHashMap;
50 import java.util.List;
52 import java.util.Queue;
54 import java.util.SortedSet;
55 import java.util.Stack;
56 import java.util.TreeSet;
57 import java.util.concurrent.BlockingQueue;
58 import java.util.concurrent.ConcurrentLinkedQueue;
59 import java.util.concurrent.Executors;
60 import java.util.concurrent.LinkedBlockingQueue;
61 import java.util.concurrent.LinkedTransferQueue;
62 import java.util.concurrent.ScheduledExecutorService;
63 import java.util.concurrent.ThreadFactory;
64 import java.util.concurrent.TransferQueue;
65 import java.util.regex.Matcher;
66 import java.util.regex.Pattern;
67 import javax.sql.DataSource;
70 * The type Configuration utils.
72 public class ConfigurationUtils {
75 * Gets scheduled executor service.
77 * @return the scheduled executor service
79 public static ScheduledExecutorService getScheduledExecutorService() {
80 return Executors.newScheduledThreadPool(1, (r1) -> {
81 Thread thread = Executors.privilegedThreadFactory().newThread(r1);
82 thread.setDaemon(true);
88 * Gets thread factory.
90 * @return the thread factory
92 public static ThreadFactory getThreadFactory() {
94 Thread thread = Executors.privilegedThreadFactory().newThread(r1);
95 thread.setDaemon(true);
103 * @param file the file
104 * @param recursive the recursive
105 * @param onlyDirectory the only directory
106 * @return the all files
108 public static Collection<File> getAllFiles(File file, boolean recursive, boolean onlyDirectory) {
109 ArrayList<File> collection = new ArrayList<>();
110 if (file.isDirectory() && file.exists()) {
111 File[] files = file.listFiles();
112 for (File innerFile : files) {
113 if (innerFile.isFile() && !onlyDirectory) {
114 collection.add(innerFile);
115 } else if (innerFile.isDirectory()) {
116 collection.add(innerFile);
118 collection.addAll(getAllFiles(innerFile, recursive, onlyDirectory));
127 * Gets comma saperated list.
129 * @param list the list
130 * @return the comma saperated list
132 public static String getCommaSaperatedList(List list) {
133 String toReturn = "";
135 for (Object obj : list) {
136 if (!toReturn.trim().isEmpty()) {
146 * Gets comma saperated list.
148 * @param list the list
149 * @return the comma saperated list
151 public static String getCommaSaperatedList(String[] list) {
152 return getCommaSaperatedList(list == null ? Arrays.asList() : Arrays.asList(list));
159 * @return the config type
161 public static ConfigurationType getConfigType(URL url) {
162 return Enum.valueOf(ConfigurationType.class,
163 url.getFile().substring(url.getFile().lastIndexOf('.') + 1).toUpperCase());
169 * @param file the file
170 * @return the config type
172 public static ConfigurationType getConfigType(File file) {
173 return Enum.valueOf(ConfigurationType.class,
174 file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf('.') + 1)
182 * @return the boolean
184 public static boolean isConfig(URL url) {
185 return isConfig(url.getFile());
191 * @param file the file
192 * @return the boolean
194 public static boolean isConfig(File file) {
195 return file != null && file.exists() && isConfig(file.getName());
201 * @param file the file
202 * @return the boolean
204 public static boolean isConfig(String file) {
205 file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
206 file = file.substring(file.lastIndexOf('/') + 1);
208 "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
209 + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
210 + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
211 + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$")
212 || file.matches("CONFIG(.)*\\.(" + ConfigurationType.PROPERTIES.name() + "|"
213 + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
214 + ConfigurationType.YAML.name() + ")$");
221 * @return the namespace
223 public static String getNamespace(URL url) {
224 String namespace = getNamespace(getConfiguration(url));
225 if (namespace != null) {
226 return namespace.toUpperCase();
228 return getNamespace(url.getFile().toUpperCase());
234 * @param file the file
235 * @return the namespace
237 public static String getNamespace(File file) {
238 String namespace = getNamespace(getConfiguration(file));
239 if (namespace != null) {
240 return namespace.toUpperCase();
242 return getNamespace(file.getName().toUpperCase());
245 private static String getNamespace(Configuration config) {
246 return config.getString(Constants.NAMESPACE_KEY) == null ? null
247 : config.getString(Constants.NAMESPACE_KEY).toUpperCase();
253 * @param file the file
254 * @return the namespace
256 public static String getNamespace(String file) {
257 file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
258 file = file.substring(file.lastIndexOf('/') + 1);
259 Pattern pattern = Pattern.compile(
260 "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
261 + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
262 + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
263 + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
264 Matcher matcher = pattern.matcher(file);
265 boolean b1 = matcher.matches();
267 if (matcher.group(1) != null) {
268 String moduleName = matcher.group(1).substring(1);
269 return moduleName.equalsIgnoreCase(ConfigurationMode.OVERRIDE.name())
270 || moduleName.equalsIgnoreCase(ConfigurationMode.UNION.name())
271 || moduleName.equalsIgnoreCase(ConfigurationMode.MERGE.name())
272 ? Constants.DEFAULT_NAMESPACE : moduleName;
274 return Constants.DEFAULT_NAMESPACE;
276 } else if (isConfig(file)) {
277 return Constants.DEFAULT_NAMESPACE;
284 * Gets merge strategy.
287 * @return the merge strategy
289 public static ConfigurationMode getMergeStrategy(URL url) {
290 String configMode = getMergeStrategy(getConfiguration(url));
291 if (configMode != null) {
293 return Enum.valueOf(ConfigurationMode.class, configMode);
294 } catch (Exception exception) {
298 return getMergeStrategy(url.getFile().toUpperCase());
301 private static String getMergeStrategy(Configuration config) {
302 return config.getString(Constants.MODE_KEY) == null ? null
303 : config.getString(Constants.MODE_KEY).toUpperCase();
307 * Gets merge strategy.
309 * @param file the file
310 * @return the merge strategy
312 public static ConfigurationMode getMergeStrategy(File file) {
313 String configMode = getMergeStrategy(getConfiguration(file));
314 if (configMode != null) {
316 return Enum.valueOf(ConfigurationMode.class, configMode);
317 } catch (Exception exception) {
321 return getMergeStrategy(file.getName().toUpperCase());
325 * Gets merge strategy.
327 * @param file the file
328 * @return the merge strategy
330 public static ConfigurationMode getMergeStrategy(String file) {
331 file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
332 file = file.substring(file.lastIndexOf('/') + 1);
333 Pattern pattern = Pattern.compile(
334 "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
335 + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
336 + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
337 + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
338 Matcher matcher = pattern.matcher(file);
339 boolean b1 = matcher.matches();
341 for (int i = 1; i <= matcher.groupCount(); i++) {
342 String modeName = matcher.group(i);
343 if (modeName != null) {
344 modeName = modeName.substring(1);
347 return Enum.valueOf(ConfigurationMode.class, modeName);
348 } catch (Exception exception) {
358 * Gets configuration.
361 * @return the configuration
363 public static FileBasedConfiguration getConfiguration(URL url) {
364 FileBasedConfiguration builder = null;
366 switch (ConfigurationUtils.getConfigType(url)) {
368 builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
371 builder = new Configurations().fileBased(XMLConfiguration.class, url);
374 builder = new Configurations().fileBased(JsonConfiguration.class, url);
377 builder = new Configurations().fileBased(YamlConfiguration.class, url);
381 } catch (ConfigurationException exception) {
382 exception.printStackTrace();
388 * Gets configuration.
391 * @return the configuration
393 public static FileBasedConfiguration getConfiguration(File url) {
394 FileBasedConfiguration builder = null;
396 switch (ConfigurationUtils.getConfigType(url)) {
398 builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
401 builder = new Configurations().fileBased(XMLConfiguration.class, url);
404 builder = new Configurations().fileBased(JsonConfiguration.class, url);
407 builder = new Configurations().fileBased(YamlConfiguration.class, url);
411 } catch (ConfigurationException exception) {
412 exception.printStackTrace();
418 * Gets collection generic type.
420 * @param field the field
421 * @return the collection generic type
423 public static Class getCollectionGenericType(Field field) {
424 Type type = field.getGenericType();
426 if (type instanceof ParameterizedType) {
428 ParameterizedType paramType = (ParameterizedType) type;
429 Type[] arr = paramType.getActualTypeArguments();
431 for (Type tp : arr) {
432 Class<?> clzz = (Class<?>) tp;
433 if (isWrapperClass(clzz)) {
436 throw new RuntimeException("Collection of type " + clzz.getName() + " not supported.");
440 return String[].class;
446 * @param clazz the clazz
447 * @return the array class
449 public static Class getArrayClass(Class clazz) {
450 switch (clazz.getName()) {
451 case "java.lang.Byte":
453 case "java.lang.Short":
454 return Short[].class;
455 case "java.lang.Integer":
456 return Integer[].class;
457 case "java.lang.Long":
459 case "java.lang.Float":
460 return Float[].class;
461 case "java.lang.Double":
462 return Double[].class;
463 case "java.lang.Boolean":
464 return Boolean[].class;
465 case "java.lang.Character":
466 return Character[].class;
467 case "java.lang.String":
468 return String[].class;
475 * Gets all class path resources.
477 * @return the all class path resources
479 public static List<URL> getAllClassPathResources() {
480 return CPScanner.scanResources(new ResourceFilter());
484 * Execute ddlsql boolean.
487 * @return the boolean
488 * @throws Exception the exception
490 public static boolean executeDdlSql(String sql) throws Exception {
491 DataSource datasource = ConfigurationDataSource.lookup();
492 try (Connection con = datasource.getConnection(); Statement stmt = con.createStatement()) {
493 stmt.executeQuery(sql);
494 } catch (Exception exception) {
495 System.err.println("Datasource initialization error. Configuration management will be using in-memory persistence.");
502 * Gets configuration builder.
505 * @return the configuration builder
507 public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(URL url) {
508 ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = null;
509 switch (ConfigurationUtils.getConfigType(url)) {
511 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
512 PropertiesConfiguration.class);
515 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
516 XMLConfiguration.class);
519 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
520 JsonConfiguration.class);
523 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
524 YamlConfiguration.class);
528 builder.configure(new Parameters().fileBased().setURL(url)
529 .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
534 * Gets configuration builder.
536 * @param file the file
537 * @param autoSave the auto save
538 * @return the configuration builder
540 public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(File file,
542 ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = null;
543 switch (ConfigurationUtils.getConfigType(file)) {
545 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
546 PropertiesConfiguration.class);
549 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
550 XMLConfiguration.class);
553 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
554 JsonConfiguration.class);
557 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
558 YamlConfiguration.class);
562 builder.configure(new Parameters().fileBased().setFile(file)
563 .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
564 builder.setAutoSave(autoSave);
570 * Execute select sql collection.
573 * @param params the params
574 * @return the collection
575 * @throws Exception the exception
577 public static Collection<String> executeSelectSql(String sql, String[] params) throws Exception {
578 Collection<String> coll = new ArrayList<>();
579 DataSource datasource = ConfigurationDataSource.lookup();
580 try (Connection con = datasource.getConnection();
581 PreparedStatement stmt = con.prepareStatement(sql)) {
582 if (params != null) {
583 for (int i = 0; i < params.length; i++) {
584 stmt.setString(i + 1, params[i]);
588 try (ResultSet rs = stmt.executeQuery()) {
591 coll.add(rs.getString(1));
595 } catch (Exception exception) {
596 //exception.printStackTrace();
604 * Execute insert sql boolean.
607 * @param params the params
608 * @return the boolean
609 * @throws Exception the exception
611 public static boolean executeInsertSql(String sql, Object[] params) throws Exception {
612 Collection<String> coll = new ArrayList<>();
613 DataSource datasource = ConfigurationDataSource.lookup();
614 try (Connection con = datasource.getConnection();
615 PreparedStatement stmt = con.prepareStatement(sql)) {
616 if (params != null) {
618 for (Object obj : params) {
622 switch (obj.getClass().getName()) {
623 case "java.lang.String":
624 stmt.setString(++counter, obj.toString());
626 case "java.lang.Integer":
627 stmt.setInt(++counter, ((Integer) obj).intValue());
629 case "java.lang.Long":
630 stmt.setLong(++counter, ((Long) obj).longValue());
633 stmt.setString(++counter, obj.toString());
638 stmt.executeUpdate();
640 } catch (Exception exception) {
641 exception.printStackTrace();
649 * @param <T> the type parameter
650 * @param config the config
651 * @param clazz the clazz
652 * @param keyPrefix the key prefix
654 * @throws Exception the exception
656 public static <T> T read(Configuration config, Class<T> clazz, String keyPrefix)
658 org.openecomp.config.api.Config confAnnot =
659 clazz.getAnnotation(org.openecomp.config.api.Config.class);
660 if (confAnnot != null) {
661 keyPrefix += (confAnnot.key() + ".");
663 T objToReturn = clazz.newInstance();
664 for (Field field : clazz.getDeclaredFields()) {
665 org.openecomp.config.api.Config fieldConfAnnot =
666 field.getAnnotation(org.openecomp.config.api.Config.class);
667 if (fieldConfAnnot != null) {
668 field.setAccessible(true);
669 field.set(objToReturn, config.getProperty(keyPrefix + fieldConfAnnot.key()));
670 } else if (field.getType().getAnnotation(org.openecomp.config.api.Config.class) != null) {
671 field.set(objToReturn, read(config, field.getType(), keyPrefix));
678 * Gets db configuration builder.
680 * @param configName the config name
681 * @return the db configuration builder
682 * @throws Exception the exception
684 public static BasicConfigurationBuilder<AgglomerateConfiguration> getDbConfigurationBuilder(
685 String configName) throws Exception {
686 Configuration dbConfig = ConfigurationRepository.lookup()
687 .getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE);
688 BasicConfigurationBuilder<AgglomerateConfiguration> builder =
689 new BasicConfigurationBuilder<AgglomerateConfiguration>(AgglomerateConfiguration.class);
691 new Parameters().database()
692 .setDataSource(ConfigurationDataSource.lookup())
693 .setTable(dbConfig.getString("config.Table"))
694 .setKeyColumn(dbConfig.getString("configKey"))
695 .setValueColumn(dbConfig.getString("configValue"))
696 .setConfigurationNameColumn(dbConfig.getString("configNameColumn"))
697 .setConfigurationName(configName)
706 * @param config the config
708 * @param processingHints the processing hints
709 * @return the property
711 public static Object getProperty(Configuration config, String key, int processingHints) {
712 if (!isDirectLookup(processingHints)) {
713 if (config instanceof AgglomerateConfiguration) {
714 return ((AgglomerateConfiguration) config).getPropertyValue(key);
715 } else if (config instanceof CompositeConfiguration) {
716 CompositeConfiguration conf = (CompositeConfiguration) config;
717 for (int i = 0; i < conf.getNumberOfConfigurations(); i++) {
718 if (conf.getConfiguration(i) instanceof AgglomerateConfiguration) {
719 return ((AgglomerateConfiguration) conf.getConfiguration(i)).getPropertyValue(key);
720 } else if (isNodeSpecific(processingHints)) {
721 Object obj = conf.getConfiguration(i).getProperty(key);
729 return config.getProperty(key);
733 * Gets primitive array.
735 * @param collection the collection
736 * @param clazz the clazz
737 * @return the primitive array
739 public static Object getPrimitiveArray(Collection collection, Class clazz) {
741 if (clazz == int.class) {
742 int[] array = new int[collection.size()];
743 Object[] objArray = collection.toArray();
744 for (int i = 0; i < collection.size(); i++) {
745 array[i] = (int) objArray[i];
749 if (clazz == byte.class) {
750 byte[] array = new byte[collection.size()];
751 Object[] objArray = collection.toArray();
752 for (int i = 0; i < collection.size(); i++) {
753 array[i] = (byte) objArray[i];
757 if (clazz == short.class) {
758 short[] array = new short[collection.size()];
759 Object[] objArray = collection.toArray();
760 for (int i = 0; i < collection.size(); i++) {
761 array[i] = (short) objArray[i];
765 if (clazz == long.class) {
766 long[] array = new long[collection.size()];
767 Object[] objArray = collection.toArray();
768 for (int i = 0; i < collection.size(); i++) {
769 array[i] = (long) objArray[i];
773 if (clazz == float.class) {
774 float[] array = new float[collection.size()];
775 Object[] objArray = collection.toArray();
776 for (int i = 0; i < collection.size(); i++) {
777 array[i] = (float) objArray[i];
781 if (clazz == double.class) {
782 double[] array = new double[collection.size()];
783 Object[] objArray = collection.toArray();
784 for (int i = 0; i < collection.size(); i++) {
785 array[i] = (double) objArray[i];
789 if (clazz == boolean.class) {
790 boolean[] array = new boolean[collection.size()];
791 Object[] objArray = collection.toArray();
792 for (int i = 0; i < collection.size(); i++) {
793 array[i] = (boolean) objArray[i];
802 * Is wrapper class boolean.
804 * @param clazz the clazz
805 * @return the boolean
807 public static boolean isWrapperClass(Class clazz) {
808 return clazz == String.class || clazz == Boolean.class || clazz == Character.class
809 || Number.class.isAssignableFrom(clazz);
813 * Gets collection string.
815 * @param input the input
816 * @return the collection string
818 public static String getCollectionString(String input) {
819 Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
820 Matcher matcher = pattern.matcher(input);
821 if (matcher.matches()) {
822 input = matcher.group(1);
828 * Is collection boolean.
830 * @param input the input
831 * @return the boolean
833 public static boolean isCollection(String input) {
834 Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
835 Matcher matcher = pattern.matcher(input);
836 return matcher.matches();
840 * Process variables if present string.
842 * @param tenant the tenant
843 * @param namespace the namespace
844 * @param data the data
847 public static String processVariablesIfPresent(String tenant, String namespace, String data) {
848 Pattern pattern = Pattern.compile("^.*\\$\\{(.*)\\}.*");
849 Matcher matcher = pattern.matcher(data);
850 if (matcher.matches()) {
851 String key = matcher.group(1);
852 if (key.toUpperCase().startsWith("ENV:")) {
853 String envValue = System.getenv(key.substring(4));
854 return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
855 envValue == null ? "" : envValue.replace("\\", "\\\\")));
856 } else if (key.toUpperCase().startsWith("SYS:")) {
857 String sysValue = System.getProperty(key.substring(4));
858 return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
859 sysValue == null ? "" : sysValue.replace("\\", "\\\\")));
861 String propertyValue = ConfigurationUtils.getCollectionString(
862 ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key).toString());
863 return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
864 propertyValue == null ? "" : propertyValue.replace("\\", "\\\\")));
872 * Gets file contents.
874 * @param path the path
875 * @return the file contents
877 public static String getFileContents(String path) {
880 return IOUtils.toString(new URL(path));
882 } catch (Exception exception) {
883 exception.printStackTrace();
889 * Gets file contents.
891 * @param path the path
892 * @return the file contents
894 public static String getFileContents(Path path) {
897 return new String(Files.readAllBytes(path));
899 } catch (Exception exception) {
900 exception.printStackTrace();
906 * Gets concrete collection.
908 * @param clazz the clazz
909 * @return the concrete collection
911 public static Collection getConcreteCollection(Class clazz) {
912 Collection collection = null;
914 switch (clazz.getName()) {
915 case "java.util.Collection":
916 case "java.util.List":
917 return new ArrayList<>();
918 case "java.util.Set":
919 return new HashSet<>();
920 case "java.util.SortedSet":
921 return new TreeSet<>();
922 case "java.util.Queue":
923 return new ConcurrentLinkedQueue<>();
924 case "java.util.Deque":
925 return new ArrayDeque<>();
926 case "java.util.concurrent.TransferQueue":
927 return new LinkedTransferQueue<>();
928 case "java.util.concurrent.BlockingQueue":
929 return new LinkedBlockingQueue<>();
939 * @param clazz the clazz
940 * @return the default for
942 public static Object getDefaultFor(Class clazz) {
943 if (byte.class == clazz) {
944 return new Byte("0");
945 } else if (short.class == clazz) {
946 return new Short("0");
947 } else if (int.class == clazz) {
948 return new Integer("0");
949 } else if (float.class == clazz) {
950 return new Float("0");
951 } else if (long.class == clazz) {
952 return new Long("0");
953 } else if (double.class == clazz) {
954 return new Double("0");
955 } else if (boolean.class == clazz) {
956 return Boolean.FALSE;
958 return new Character((char) 0);
962 * Gets compatible collection for abstract def.
964 * @param clazz the clazz
965 * @return the compatible collection for abstract def
967 public static Collection getCompatibleCollectionForAbstractDef(Class clazz) {
968 if (BlockingQueue.class.isAssignableFrom(clazz)) {
969 return getConcreteCollection(BlockingQueue.class);
971 if (TransferQueue.class.isAssignableFrom(clazz)) {
972 return getConcreteCollection(TransferQueue.class);
974 if (Deque.class.isAssignableFrom(clazz)) {
975 return getConcreteCollection(Deque.class);
977 if (Queue.class.isAssignableFrom(clazz)) {
978 return getConcreteCollection(Queue.class);
980 if (SortedSet.class.isAssignableFrom(clazz)) {
981 return getConcreteCollection(SortedSet.class);
983 if (Set.class.isAssignableFrom(clazz)) {
984 return getConcreteCollection(Set.class);
986 if (List.class.isAssignableFrom(clazz)) {
987 return getConcreteCollection(List.class);
993 * Gets configuration repository key.
995 * @param array the array
996 * @return the configuration repository key
998 public static String getConfigurationRepositoryKey(String[] array) {
999 Stack<String> stack = new Stack<>();
1000 stack.push(Constants.DEFAULT_TENANT);
1001 for (String element : array) {
1002 stack.push(element);
1004 String toReturn = stack.pop();
1005 return stack.pop() + Constants.KEY_ELEMENTS_DELEMETER + toReturn;
1009 * Gets configuration repository key.
1011 * @param file the file
1012 * @return the configuration repository key
1014 public static String getConfigurationRepositoryKey(File file) {
1015 return getConfigurationRepositoryKey(
1016 ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SAPERATOR));
1020 * Gets configuration repository key.
1022 * @param url the url
1023 * @return the configuration repository key
1025 public static String getConfigurationRepositoryKey(URL url) {
1026 return getConfigurationRepositoryKey(
1027 ConfigurationUtils.getNamespace(url).split(Constants.TENANT_NAMESPACE_SAPERATOR));
1031 * To map linked hash map.
1033 * @param config the config
1034 * @return the linked hash map
1036 public static LinkedHashMap toMap(Configuration config) {
1037 Iterator<String> iterator = config.getKeys();
1038 LinkedHashMap<String, String> map = new LinkedHashMap<>();
1039 while (iterator.hasNext()) {
1040 String key = iterator.next();
1041 if (!(key.equals(Constants.MODE_KEY) || key.equals(Constants.NAMESPACE_KEY)
1042 || key.equals(Constants.LOAD_ORDER_KEY))) {
1043 map.put(key, config.getProperty(key).toString());
1053 * @param orig the orig
1054 * @param latest the latest
1057 public static Map diff(LinkedHashMap orig, LinkedHashMap latest) {
1058 orig = new LinkedHashMap<>(orig);
1059 latest = new LinkedHashMap<>(latest);
1060 List<String> set = new ArrayList(orig.keySet());
1061 for (String key : set) {
1062 if (latest.remove(key, orig.get(key))) {
1066 Set<String> keys = latest.keySet();
1067 for (String key : keys) {
1070 set = new ArrayList(orig.keySet());
1071 for (String key : set) {
1072 latest.put(key, "");
1074 return new HashMap<>(latest);
1080 * @param tenant the tenant
1081 * @param namespace the namespace
1082 * @param key the key
1083 * @param processingHints the processing hints
1084 * @return the boolean
1085 * @throws Exception the exception
1087 public static boolean isArray(String tenant, String namespace, String key, int processingHints)
1089 Object obj = ConfigurationUtils
1090 .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key,
1092 return (obj == null) ? false : ConfigurationUtils.isCollection(obj.toString());
1096 * Is direct lookup boolean.
1098 * @param hints the hints
1099 * @return the boolean
1101 public static boolean isDirectLookup(int hints) {
1102 return (hints & LATEST_LOOKUP.value()) == LATEST_LOOKUP.value();
1106 * Is external lookup boolean.
1108 * @param hints the hints
1109 * @return the boolean
1111 public static boolean isExternalLookup(int hints) {
1112 return (hints & EXTERNAL_LOOKUP.value()) == EXTERNAL_LOOKUP.value();
1116 * Is node specific boolean.
1118 * @param hints the hints
1119 * @return the boolean
1121 public static boolean isNodeSpecific(int hints) {
1122 return (hints & NODE_SPECIFIC.value()) == NODE_SPECIFIC.value();
1125 public static boolean isZeroLengthArray(Class clazz, Object obj){
1126 if (clazz.isArray() && clazz.getComponentType().isPrimitive()){
1127 if (clazz.getComponentType()==int.class){
1128 return ((int[])obj).length==0;
1129 }else if (clazz.getComponentType()==byte.class){
1130 return ((byte[])obj).length==0;
1131 }else if (clazz.getComponentType()==short.class){
1132 return ((short[])obj).length==0;
1133 }else if (clazz.getComponentType()==float.class){
1134 return ((float[])obj).length==0;
1135 }else if (clazz.getComponentType()==boolean.class){
1136 return ((boolean[])obj).length==0;
1137 }else if (clazz.getComponentType()==double.class){
1138 return ((double[])obj).length==0;
1139 }else if (clazz.getComponentType()==long.class){
1140 return ((long[])obj).length==0;
1142 return ((Object[])obj).length==0;
1150 * Checks if value is blank
1154 public static boolean isBlank(String value){
1155 return value==null || value.trim().length()==0;