1 package org.openecomp.config;
3 import com.google.common.collect.ImmutableMap;
4 import com.virtlink.commons.configuration2.jackson.JsonConfiguration;
5 import net.sf.corn.cps.CPScanner;
6 import net.sf.corn.cps.ResourceFilter;
7 import org.apache.commons.configuration2.CompositeConfiguration;
8 import org.apache.commons.configuration2.Configuration;
9 import org.apache.commons.configuration2.FileBasedConfiguration;
10 import org.apache.commons.configuration2.PropertiesConfiguration;
11 import org.apache.commons.configuration2.XMLConfiguration;
12 import org.apache.commons.configuration2.builder.BasicConfigurationBuilder;
13 import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
14 import org.apache.commons.configuration2.builder.fluent.Configurations;
15 import org.apache.commons.configuration2.builder.fluent.Parameters;
16 import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
17 import org.apache.commons.configuration2.ex.ConfigurationException;
18 import org.apache.commons.io.IOUtils;
19 import org.openecomp.config.api.ConfigurationManager;
20 import org.openecomp.config.impl.AgglomerateConfiguration;
21 import org.openecomp.config.impl.ConfigurationDataSource;
22 import org.openecomp.config.impl.ConfigurationRepository;
23 import org.openecomp.config.impl.YamlConfiguration;
24 import org.openecomp.config.type.ConfigurationMode;
25 import org.openecomp.config.type.ConfigurationType;
27 import javax.sql.DataSource;
29 import java.lang.reflect.Field;
30 import java.lang.reflect.ParameterizedType;
31 import java.lang.reflect.Type;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.sql.Connection;
36 import java.sql.PreparedStatement;
37 import java.sql.ResultSet;
38 import java.sql.Statement;
39 import java.util.ArrayDeque;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collection;
43 import java.util.Deque;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.Iterator;
47 import java.util.LinkedHashMap;
48 import java.util.List;
50 import java.util.Queue;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.concurrent.BlockingQueue;
55 import java.util.concurrent.ConcurrentLinkedQueue;
56 import java.util.concurrent.Executors;
57 import java.util.concurrent.LinkedBlockingQueue;
58 import java.util.concurrent.LinkedTransferQueue;
59 import java.util.concurrent.ThreadFactory;
60 import java.util.concurrent.TransferQueue;
61 import java.util.regex.Matcher;
62 import java.util.regex.Pattern;
63 import java.util.stream.Collectors;
64 import java.util.stream.Stream;
66 import static com.google.common.collect.ImmutableMap.builder;
67 import static org.openecomp.config.api.Hint.EXTERNAL_LOOKUP;
68 import static org.openecomp.config.api.Hint.LATEST_LOOKUP;
69 import static org.openecomp.config.api.Hint.NODE_SPECIFIC;
72 * The type Configuration utils.
74 public class ConfigurationUtils {
76 private ConfigurationUtils() {
79 private static ImmutableMap<Class,Class> arrayClassMap;
82 ImmutableMap.Builder<Class,Class> builder = builder();
83 builder.put(Byte.class,Byte[].class).put(Short.class, Short[].class)
84 .put(Integer.class,Integer[].class).put(Long.class,Long[].class)
85 .put(Float.class,Float[].class).put(Double.class,Double[].class)
86 .put(Boolean.class,Boolean[].class).put(Character.class,Character[].class)
87 .put(String.class,String[].class);
88 arrayClassMap = builder.build();
92 * Gets thread factory.
94 * @return the thread factory
96 public static ThreadFactory getThreadFactory() {
98 Thread thread = Executors.privilegedThreadFactory().newThread(r1);
99 thread.setDaemon(true);
107 * @param file the file
108 * @param recursive the recursive
109 * @param onlyDirectory the only directory
110 * @return the all files
112 public static Collection<File> getAllFiles(File file, boolean recursive, boolean onlyDirectory) {
113 ArrayList<File> collection = new ArrayList<>();
114 if (file.isDirectory() && file.exists()) {
115 File[] files = file.listFiles();
116 for (File innerFile : files) {
117 if (innerFile.isFile() && !onlyDirectory) {
118 collection.add(innerFile);
119 } else if (innerFile.isDirectory()) {
120 collection.add(innerFile);
122 collection.addAll(getAllFiles(innerFile, recursive, onlyDirectory));
131 * Gets comma saperated list.
133 * @param list the list
134 * @return the comma separated list
136 public static String getCommaSeparatedList(List list) {
137 return ((Stream<String>) list.stream().filter(o -> o != null && !o.toString().trim().isEmpty()).map(o -> o.toString().trim())).collect(Collectors.joining(","));
141 * Gets comma saperated list.
143 * @param list the list
144 * @return the comma saperated list
146 public static String getCommaSeparatedList(String[] list) {
147 return getCommaSeparatedList(list == null ? Arrays.asList() : Arrays.asList(list));
154 * @return the config type
156 public static ConfigurationType getConfigType(URL url) {
157 return Enum.valueOf(ConfigurationType.class,
158 url.getFile().substring(url.getFile().lastIndexOf('.') + 1).toUpperCase());
164 * @param file the file
165 * @return the config type
167 public static ConfigurationType getConfigType(File file) {
168 return Enum.valueOf(ConfigurationType.class,
169 file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf('.') + 1)
177 * @return the boolean
179 public static boolean isConfig(URL url) {
180 return isConfig(url.getFile());
186 * @param file the file
187 * @return the boolean
189 public static boolean isConfig(File file) {
190 return file != null && file.exists() && isConfig(file.getName());
196 * @param file the file
197 * @return the boolean
199 public static boolean isConfig(String file) {
200 file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
201 file = file.substring(file.lastIndexOf('/') + 1);
203 "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
204 + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
205 + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
206 + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$")
207 || file.matches("CONFIG(.)*\\.(" + ConfigurationType.PROPERTIES.name() + "|"
208 + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
209 + ConfigurationType.YAML.name() + ")$");
216 * @return the namespace
218 public static String getNamespace(URL url) {
219 String namespace = getNamespace(getConfiguration(url));
220 if (namespace != null) {
221 return namespace.toUpperCase();
223 return getNamespace(url.getFile().toUpperCase());
229 * @param file the file
230 * @return the namespace
232 public static String getNamespace(File file) {
233 String namespace = getNamespace(getConfiguration(file));
234 if (namespace != null) {
235 return namespace.toUpperCase();
237 return getNamespace(file.getName().toUpperCase());
240 private static String getNamespace(Configuration config) {
241 return config.getString(Constants.NAMESPACE_KEY) == null ? null
242 : config.getString(Constants.NAMESPACE_KEY).toUpperCase();
248 * @param file the file
249 * @return the namespace
251 public static String getNamespace(String file) {
252 file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
253 file = file.substring(file.lastIndexOf('/') + 1);
254 Pattern pattern = Pattern.compile(
255 "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
256 + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
257 + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
258 + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
259 Matcher matcher = pattern.matcher(file);
260 boolean b1 = matcher.matches();
262 if (matcher.group(1) != null) {
263 String moduleName = matcher.group(1).substring(1);
264 return moduleName.equalsIgnoreCase(ConfigurationMode.OVERRIDE.name())
265 || moduleName.equalsIgnoreCase(ConfigurationMode.UNION.name())
266 || moduleName.equalsIgnoreCase(ConfigurationMode.MERGE.name())
267 ? Constants.DEFAULT_NAMESPACE : moduleName;
269 return Constants.DEFAULT_NAMESPACE;
271 } else if (isConfig(file)) {
272 return Constants.DEFAULT_NAMESPACE;
279 * Gets merge strategy.
282 * @return the merge strategy
284 public static ConfigurationMode getMergeStrategy(URL url) {
285 String configMode = getMergeStrategy(getConfiguration(url));
286 if (configMode != null) {
288 return Enum.valueOf(ConfigurationMode.class, configMode);
289 } catch (Exception exception) {
293 return getMergeStrategy(url.getFile().toUpperCase());
296 private static String getMergeStrategy(Configuration config) {
297 return config.getString(Constants.MODE_KEY) == null ? null
298 : config.getString(Constants.MODE_KEY).toUpperCase();
302 * Gets merge strategy.
304 * @param file the file
305 * @return the merge strategy
307 public static ConfigurationMode getMergeStrategy(File file) {
308 String configMode = getMergeStrategy(getConfiguration(file));
309 if (configMode != null) {
311 return Enum.valueOf(ConfigurationMode.class, configMode);
312 } catch (Exception exception) {
316 return getMergeStrategy(file.getName().toUpperCase());
320 * Gets merge strategy.
322 * @param file the file
323 * @return the merge strategy
325 public static ConfigurationMode getMergeStrategy(String file) {
326 file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
327 file = file.substring(file.lastIndexOf('/') + 1);
328 Pattern pattern = Pattern.compile(
329 "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
330 + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
331 + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
332 + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
333 Matcher matcher = pattern.matcher(file);
334 boolean b1 = matcher.matches();
336 for (int i = 1; i <= matcher.groupCount(); i++) {
337 String modeName = matcher.group(i);
338 if (modeName != null) {
339 modeName = modeName.substring(1);
342 return Enum.valueOf(ConfigurationMode.class, modeName);
343 } catch (Exception exception) {
353 * Gets configuration.
356 * @return the configuration
358 public static FileBasedConfiguration getConfiguration(URL url) {
359 FileBasedConfiguration builder = null;
361 ConfigurationType configType = ConfigurationUtils.getConfigType(url);
362 switch (configType) {
364 builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
367 builder = new Configurations().fileBased(XMLConfiguration.class, url);
370 builder = new Configurations().fileBased(JsonConfiguration.class, url);
373 builder = new Configurations().fileBased(YamlConfiguration.class, url);
376 throw new ConfigurationException("Configuration type not supported:"+ configType);
378 } catch (ConfigurationException exception) {
379 exception.printStackTrace();
385 * Gets configuration.
387 * @param file the file
388 * @return the configuration
390 public static FileBasedConfiguration getConfiguration(File file) {
391 FileBasedConfiguration builder = null;
393 ConfigurationType configType = ConfigurationUtils.getConfigType(file);
394 switch (configType) {
396 builder = new Configurations().fileBased(PropertiesConfiguration.class, file);
399 builder = new Configurations().fileBased(XMLConfiguration.class, file);
402 builder = new Configurations().fileBased(JsonConfiguration.class, file);
405 builder = new Configurations().fileBased(YamlConfiguration.class, file);
408 throw new ConfigurationException("Configuration type not supported:"+ configType);
410 } catch (ConfigurationException exception) {
411 exception.printStackTrace();
417 * Gets collection generic type.
419 * @param field the field
420 * @return the collection generic type
422 public static Class getCollectionGenericType(Field field) {
423 Type type = field.getGenericType();
425 if (type instanceof ParameterizedType) {
427 ParameterizedType paramType = (ParameterizedType) type;
428 Type[] arr = paramType.getActualTypeArguments();
430 for (Type tp : arr) {
431 Class<?> clzz = (Class<?>) tp;
432 if (isWrapperClass(clzz)) {
435 throw new RuntimeException("Collection of type " + clzz.getName() + " not supported.");
439 return String[].class;
447 * @param clazz the clazz
448 * @return the array class
450 public static Class getArrayClass(Class clazz) {
451 return arrayClassMap.getOrDefault(clazz, null);
455 * Gets all class path resources.
457 * @return the all class path resources
459 public static List<URL> getAllClassPathResources() {
460 return CPScanner.scanResources(new ResourceFilter());
464 * Execute ddlsql boolean.
467 * @return the boolean
468 * @throws Exception the exception
470 public static boolean executeDdlSql(String sql) throws Exception {
471 DataSource datasource = ConfigurationDataSource.lookup();
472 if (datasource == null) {
473 System.err.println("DB configuration not found. Configuration management will be using "
474 + "in-memory persistence.");
477 try (Connection con = datasource.getConnection(); Statement stmt = con.createStatement()) {
478 stmt.executeQuery(sql);
479 } catch (Exception exception) {
480 System.err.println("Datasource initialization error. Configuration management will be using in-memory persistence.");
487 * Gets configuration builder.
490 * @return the configuration builder
492 public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(URL url) {
493 ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = null;
494 ConfigurationType configType = ConfigurationUtils.getConfigType(url);
495 switch (configType) {
497 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
498 PropertiesConfiguration.class);
501 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
502 XMLConfiguration.class);
505 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
506 JsonConfiguration.class);
509 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
510 YamlConfiguration.class);
513 throw new IllegalArgumentException("Configuration type not supported:"+ configType);
515 builder.configure(new Parameters().fileBased().setURL(url)
516 .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
521 * Gets configuration builder.
523 * @param file the file
524 * @param autoSave the auto save
525 * @return the configuration builder
527 public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(File file,
529 ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = null;
530 ConfigurationType configType = ConfigurationUtils.getConfigType(file);
531 switch (configType) {
533 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
534 PropertiesConfiguration.class);
537 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
538 XMLConfiguration.class);
541 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
542 JsonConfiguration.class);
545 builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
546 YamlConfiguration.class);
549 throw new IllegalArgumentException("Configuration type not supported:"+ configType);
551 builder.configure(new Parameters().fileBased().setFile(file)
552 .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
553 builder.setAutoSave(autoSave);
559 * Execute select sql collection.
562 * @param params the params
563 * @return the collection
564 * @throws Exception the exception
566 public static Collection<String> executeSelectSql(String sql, String[] params) throws Exception {
567 Collection<String> coll = new ArrayList<>();
568 DataSource datasource = ConfigurationDataSource.lookup();
569 try (Connection con = datasource.getConnection();
570 PreparedStatement stmt = con.prepareStatement(sql)) {
571 if (params != null) {
572 for (int i = 0; i < params.length; i++) {
573 stmt.setString(i + 1, params[i]);
577 try (ResultSet rs = stmt.executeQuery()) {
580 coll.add(rs.getString(1));
584 } catch (Exception exception) {
585 //exception.printStackTrace();
593 * Execute insert sql boolean.
596 * @param params the params
597 * @return the boolean
598 * @throws Exception the exception
600 public static boolean executeInsertSql(String sql, Object[] params) throws Exception {
601 Collection<String> coll = new ArrayList<>();
602 DataSource datasource = ConfigurationDataSource.lookup();
603 try (Connection con = datasource.getConnection();
604 PreparedStatement stmt = con.prepareStatement(sql)) {
605 if (params != null) {
607 for (Object obj : params) {
611 switch (obj.getClass().getName()) {
612 case "java.lang.String":
613 stmt.setString(++counter, obj.toString());
615 case "java.lang.Integer":
616 stmt.setInt(++counter, ((Integer) obj).intValue());
618 case "java.lang.Long":
619 stmt.setLong(++counter, ((Long) obj).longValue());
622 stmt.setString(++counter, obj.toString());
627 stmt.executeUpdate();
629 } catch (Exception exception) {
630 exception.printStackTrace();
638 * @param <T> the type parameter
639 * @param config the config
640 * @param clazz the clazz
641 * @param keyPrefix the key prefix
643 * @throws Exception the exception
645 public static <T> T read(Configuration config, Class<T> clazz, String keyPrefix)
647 org.openecomp.config.api.Config confAnnot =
648 clazz.getAnnotation(org.openecomp.config.api.Config.class);
649 if (confAnnot != null) {
650 keyPrefix += (confAnnot.key() + ".");
652 T objToReturn = clazz.newInstance();
653 for (Field field : clazz.getDeclaredFields()) {
654 org.openecomp.config.api.Config fieldConfAnnot =
655 field.getAnnotation(org.openecomp.config.api.Config.class);
656 if (fieldConfAnnot != null) {
657 field.setAccessible(true);
658 field.set(objToReturn, config.getProperty(keyPrefix + fieldConfAnnot.key()));
659 } else if (field.getType().getAnnotation(org.openecomp.config.api.Config.class) != null) {
660 field.set(objToReturn, read(config, field.getType(), keyPrefix));
667 * Gets db configuration builder.
669 * @param configName the config name
670 * @return the db configuration builder
671 * @throws Exception the exception
673 public static BasicConfigurationBuilder<AgglomerateConfiguration> getDbConfigurationBuilder(
674 String configName) throws Exception {
675 Configuration dbConfig = ConfigurationRepository.lookup()
676 .getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE);
677 BasicConfigurationBuilder<AgglomerateConfiguration> builder =
678 new BasicConfigurationBuilder<AgglomerateConfiguration>(AgglomerateConfiguration.class);
680 new Parameters().database()
681 .setDataSource(ConfigurationDataSource.lookup())
682 .setTable(dbConfig.getString("config.Table"))
683 .setKeyColumn(dbConfig.getString("configKey"))
684 .setValueColumn(dbConfig.getString("configValue"))
685 .setConfigurationNameColumn(dbConfig.getString("configNameColumn"))
686 .setConfigurationName(configName)
695 * @param config the config
697 * @param processingHints the processing hints
698 * @return the property
700 public static Object getProperty(Configuration config, String key, int processingHints) {
701 if (!isDirectLookup(processingHints)) {
702 if (config instanceof AgglomerateConfiguration) {
703 return ((AgglomerateConfiguration) config).getPropertyValue(key);
704 } else if (config instanceof CompositeConfiguration) {
705 CompositeConfiguration conf = (CompositeConfiguration) config;
706 for (int i = 0; i < conf.getNumberOfConfigurations(); i++) {
707 if (conf.getConfiguration(i) instanceof AgglomerateConfiguration) {
708 return ((AgglomerateConfiguration) conf.getConfiguration(i)).getPropertyValue(key);
709 } else if (isNodeSpecific(processingHints)) {
710 Object obj = conf.getConfiguration(i).getProperty(key);
718 return config.getProperty(key);
722 * Gets primitive array.
724 * @param collection the collection
725 * @param clazz the clazz
726 * @return the primitive array
728 public static Object getPrimitiveArray(Collection collection, Class clazz) {
729 if (clazz == int.class) {
730 int[] array = new int[collection.size()];
731 Object[] objArray = collection.toArray();
732 for (int i = 0; i < collection.size(); i++) {
733 array[i] = (int) objArray[i];
737 if (clazz == byte.class) {
738 byte[] array = new byte[collection.size()];
739 Object[] objArray = collection.toArray();
740 for (int i = 0; i < collection.size(); i++) {
741 array[i] = (byte) objArray[i];
745 if (clazz == short.class) {
746 short[] array = new short[collection.size()];
747 Object[] objArray = collection.toArray();
748 for (int i = 0; i < collection.size(); i++) {
749 array[i] = (short) objArray[i];
753 if (clazz == long.class) {
754 long[] array = new long[collection.size()];
755 Object[] objArray = collection.toArray();
756 for (int i = 0; i < collection.size(); i++) {
757 array[i] = (long) objArray[i];
761 if (clazz == float.class) {
762 float[] array = new float[collection.size()];
763 Object[] objArray = collection.toArray();
764 for (int i = 0; i < collection.size(); i++) {
765 array[i] = (float) objArray[i];
769 if (clazz == double.class) {
770 double[] array = new double[collection.size()];
771 Object[] objArray = collection.toArray();
772 for (int i = 0; i < collection.size(); i++) {
773 array[i] = (double) objArray[i];
777 if (clazz == boolean.class) {
778 boolean[] array = new boolean[collection.size()];
779 Object[] objArray = collection.toArray();
780 for (int i = 0; i < collection.size(); i++) {
781 array[i] = (boolean) objArray[i];
790 * Is wrapper class boolean.
792 * @param clazz the clazz
793 * @return the boolean
795 public static boolean isWrapperClass(Class clazz) {
796 return clazz == String.class || clazz == Boolean.class || clazz == Character.class
797 || Number.class.isAssignableFrom(clazz);
801 * Gets collection string.
803 * @param input the input
804 * @return the collection string
806 public static String getCollectionString(String input) {
807 Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
808 Matcher matcher = pattern.matcher(input);
809 if (matcher.matches()) {
810 input = matcher.group(1);
816 * Is collection boolean.
818 * @param input the input
819 * @return the boolean
821 public static boolean isCollection(String input) {
822 Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
823 Matcher matcher = pattern.matcher(input);
824 return matcher.matches();
828 * Process variables if present string.
830 * @param tenant the tenant
831 * @param namespace the namespace
832 * @param data the data
835 public static String processVariablesIfPresent(String tenant, String namespace, String data) {
836 Pattern pattern = Pattern.compile("^.*\\$\\{(.*)\\}.*");
837 Matcher matcher = pattern.matcher(data);
838 if (matcher.matches()) {
839 String key = matcher.group(1);
840 if (key.toUpperCase().startsWith("ENV:")) {
841 String envValue = System.getenv(key.substring(4));
842 return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
843 envValue == null ? "" : envValue.replace("\\", "\\\\")));
844 } else if (key.toUpperCase().startsWith("SYS:")) {
845 String sysValue = System.getProperty(key.substring(4));
846 return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
847 sysValue == null ? "" : sysValue.replace("\\", "\\\\")));
849 String propertyValue = ConfigurationUtils.getCollectionString(
850 ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key).toString());
851 return processVariablesIfPresent(tenant, namespace, data.replaceAll("\\$\\{" + key + "\\}",
852 propertyValue == null ? "" : propertyValue.replace("\\", "\\\\")));
860 * Gets file contents.
862 * @param path the path
863 * @return the file contents
865 public static String getFileContents(String path) {
868 return IOUtils.toString(new URL(path));
870 } catch (Exception exception) {
871 exception.printStackTrace();
877 * Gets file contents.
879 * @param path the path
880 * @return the file contents
882 public static String getFileContents(Path path) {
885 return new String(Files.readAllBytes(path));
887 } catch (Exception exception) {
888 exception.printStackTrace();
894 * Gets concrete collection.
896 * @param clazz the clazz
897 * @return the concrete collection
899 public static Collection getConcreteCollection(Class clazz) {
900 switch (clazz.getName()) {
901 case "java.util.Collection":
902 case "java.util.List":
903 return new ArrayList<>();
904 case "java.util.Set":
905 return new HashSet<>();
906 case "java.util.SortedSet":
907 return new TreeSet<>();
908 case "java.util.Queue":
909 return new ConcurrentLinkedQueue<>();
910 case "java.util.Deque":
911 return new ArrayDeque<>();
912 case "java.util.concurrent.TransferQueue":
913 return new LinkedTransferQueue<>();
914 case "java.util.concurrent.BlockingQueue":
915 return new LinkedBlockingQueue<>();
924 * @param clazz the clazz
925 * @return the default for
927 public static Object getDefaultFor(Class clazz) {
928 if (byte.class == clazz) {
929 return new Byte("0");
930 } else if (short.class == clazz) {
931 return new Short("0");
932 } else if (int.class == clazz) {
933 return new Integer("0");
934 } else if (float.class == clazz) {
935 return new Float("0");
936 } else if (long.class == clazz) {
937 return new Long("0");
938 } else if (double.class == clazz) {
939 return new Double("0");
940 } else if (boolean.class == clazz) {
941 return Boolean.FALSE;
943 return new Character((char) 0);
947 * Gets compatible collection for abstract def.
949 * @param clazz the clazz
950 * @return the compatible collection for abstract def
952 public static Collection getCompatibleCollectionForAbstractDef(Class clazz) {
953 if (BlockingQueue.class.isAssignableFrom(clazz)) {
954 return getConcreteCollection(BlockingQueue.class);
956 if (TransferQueue.class.isAssignableFrom(clazz)) {
957 return getConcreteCollection(TransferQueue.class);
959 if (Deque.class.isAssignableFrom(clazz)) {
960 return getConcreteCollection(Deque.class);
962 if (Queue.class.isAssignableFrom(clazz)) {
963 return getConcreteCollection(Queue.class);
965 if (SortedSet.class.isAssignableFrom(clazz)) {
966 return getConcreteCollection(SortedSet.class);
968 if (Set.class.isAssignableFrom(clazz)) {
969 return getConcreteCollection(Set.class);
971 if (List.class.isAssignableFrom(clazz)) {
972 return getConcreteCollection(List.class);
978 * Gets configuration repository key.
980 * @param array the array
981 * @return the configuration repository key
983 public static String getConfigurationRepositoryKey(String[] array) {
984 Deque<String> stack = new ArrayDeque<>();
985 stack.push(Constants.DEFAULT_TENANT);
986 for (String element : array) {
989 String toReturn = stack.pop();
990 return stack.pop() + Constants.KEY_ELEMENTS_DELEMETER + toReturn;
994 * Gets configuration repository key.
996 * @param file the file
997 * @return the configuration repository key
999 public static String getConfigurationRepositoryKey(File file) {
1000 return getConfigurationRepositoryKey(
1001 ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SAPERATOR));
1005 * Gets configuration repository key.
1007 * @param url the url
1008 * @return the configuration repository key
1010 public static String getConfigurationRepositoryKey(URL url) {
1011 return getConfigurationRepositoryKey(
1012 ConfigurationUtils.getNamespace(url).split(Constants.TENANT_NAMESPACE_SAPERATOR));
1016 * To map linked hash map.
1018 * @param config the config
1019 * @return the linked hash map
1021 public static LinkedHashMap toMap(Configuration config) {
1022 Iterator<String> iterator = config.getKeys();
1023 LinkedHashMap<String, String> map = new LinkedHashMap<>();
1024 while (iterator.hasNext()) {
1025 String key = iterator.next();
1026 if (!(key.equals(Constants.MODE_KEY) || key.equals(Constants.NAMESPACE_KEY)
1027 || key.equals(Constants.LOAD_ORDER_KEY))) {
1028 map.put(key, config.getProperty(key).toString());
1038 * @param orig the orig
1039 * @param latest the latest
1042 public static Map diff(LinkedHashMap orig, LinkedHashMap latest) {
1043 orig = new LinkedHashMap<>(orig);
1044 latest = new LinkedHashMap<>(latest);
1045 List<String> set = new ArrayList(orig.keySet());
1046 for (String key : set) {
1047 if (latest.remove(key, orig.get(key))) {
1051 Set<String> keys = latest.keySet();
1052 for (String key : keys) {
1055 set = new ArrayList(orig.keySet());
1056 for (String key : set) {
1057 latest.put(key, "");
1059 return new HashMap<>(latest);
1065 * @param tenant the tenant
1066 * @param namespace the namespace
1067 * @param key the key
1068 * @param processingHints the processing hints
1069 * @return the boolean
1070 * @throws Exception the exception
1072 public static boolean isArray(String tenant, String namespace, String key, int processingHints)
1074 Object obj = ConfigurationUtils
1075 .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key,
1077 return (obj == null) ? false : ConfigurationUtils.isCollection(obj.toString());
1081 * Is direct lookup boolean.
1083 * @param hints the hints
1084 * @return the boolean
1086 public static boolean isDirectLookup(int hints) {
1087 return (hints & LATEST_LOOKUP.value()) == LATEST_LOOKUP.value();
1091 * Is external lookup boolean.
1093 * @param hints the hints
1094 * @return the boolean
1096 public static boolean isExternalLookup(int hints) {
1097 return (hints & EXTERNAL_LOOKUP.value()) == EXTERNAL_LOOKUP.value();
1101 * Is node specific boolean.
1103 * @param hints the hints
1104 * @return the boolean
1106 public static boolean isNodeSpecific(int hints) {
1107 return (hints & NODE_SPECIFIC.value()) == NODE_SPECIFIC.value();
1110 public static boolean isZeroLengthArray(Class clazz, Object obj) {
1111 if (clazz.isArray() && clazz.getComponentType().isPrimitive()) {
1112 if (clazz.getComponentType() == int.class) {
1113 return ((int[]) obj).length == 0;
1114 } else if (clazz.getComponentType() == byte.class) {
1115 return ((byte[]) obj).length == 0;
1116 } else if (clazz.getComponentType() == short.class) {
1117 return ((short[]) obj).length == 0;
1118 } else if (clazz.getComponentType() == float.class) {
1119 return ((float[]) obj).length == 0;
1120 } else if (clazz.getComponentType() == boolean.class) {
1121 return ((boolean[]) obj).length == 0;
1122 } else if (clazz.getComponentType() == double.class) {
1123 return ((double[]) obj).length == 0;
1124 } else if (clazz.getComponentType() == long.class) {
1125 return ((long[]) obj).length == 0;
1127 return ((Object[]) obj).length == 0;
1135 * Checks if value is blank
1140 public static boolean isBlank(String value) {
1141 return value == null || value.trim().length() == 0;