PropertiesUtilities.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */


  20. package org.openspcoop2.utils.properties;

  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.InputStream;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.Properties;
  27. import java.util.Scanner;

  28. import org.openspcoop2.utils.Costanti;
  29. import org.openspcoop2.utils.SortedMap;
  30. import org.openspcoop2.utils.UtilsException;
  31. import org.slf4j.Logger;


  32. /**
  33. * PropertiesUtilities
  34. *
  35. * @author Andrea Poli (apoli@link.it)
  36. * @author $Author$
  37. * @version $Rev$, $Date$
  38. */

  39. public class PropertiesUtilities {

  40.     /*
  41.      * // RICERCA
  42.         // 1. VARIABILE DI SISTEMA che identifica il singolo file di properties (es. OPENSPCOOP_PROPERTIES o OPENSPCOOP_LOGGER_PROPERTIES)
  43.         // 2. PROPRIETA' JAVA che identifica il singolo file di properties (es. OPENSPCOOP_PROPERTIES o OPENSPCOOP_LOGGER_PROPERTIES)
  44.         // 3. VARIABILE DI SISTEMA: OPENSPCOOP_HOME dove deve essere specificata una directory in cui verra' cercato il file path
  45.         // 4. PROPRIETA' JAVA (es. ApplicationServer o Java con -D): OPENSPCOOP_HOME dove deve essere specificata una directory in cui verra' cercato il file path
  46.         // 5. CLASSPATH con nome path
  47.         // 6. (DIRECTORY DI CONFIGURAZIONE)/path
  48.     */
  49.     public static CollectionProperties searchLocalImplementation(String OPENSPCOOP2_LOCAL_HOME, Logger log,String variabile,String path,String confDirectory){  
  50.         return searchLocalImplementation(OPENSPCOOP2_LOCAL_HOME, log, variabile, path, confDirectory, true);
  51.     }
  52.     public static CollectionProperties searchLocalImplementation(String OPENSPCOOP2_LOCAL_HOME, Logger log,String variabile,String path,String confDirectory,boolean readCallsNotSynchronized){
  53.        
  54.         CollectionProperties cp = new CollectionProperties();
  55.        
  56.         String envP = System.getenv(Costanti.OPENSPCOOP2_FORCE_CONFIG_FILE);
  57.         if(envP!=null && "true".equalsIgnoreCase(envP)) {
  58.             cp.setForceConfigDir(true);
  59.         }
  60.         else {
  61.             String javaP = System.getProperty(Costanti.OPENSPCOOP2_FORCE_CONFIG_FILE);
  62.             if(javaP!=null && "true".equalsIgnoreCase(javaP)) {
  63.                 cp.setForceConfigDir(true);
  64.             }
  65.         }
  66.        
  67.        
  68.         Properties p1 = PropertiesUtilities.examineStep1(log,variabile);
  69.         if(p1!=null){
  70.             cp.setSystemVariable(new PropertiesReader(p1,readCallsNotSynchronized));
  71.         }
  72.        
  73.         Properties p2 = PropertiesUtilities.examineStep2(log,variabile);
  74.         if(p2!=null){
  75.             cp.setJavaVariable(new PropertiesReader(p2,readCallsNotSynchronized));
  76.         }
  77.        
  78.         Properties p3 = PropertiesUtilities.examineStep3(OPENSPCOOP2_LOCAL_HOME,log,path);
  79.         if(p3!=null){
  80.             cp.setSystemOpenSPCoopHome(new PropertiesReader(p3,readCallsNotSynchronized));
  81.         }
  82.        
  83.         Properties p4 = PropertiesUtilities.examineStep4(OPENSPCOOP2_LOCAL_HOME,log,path);
  84.         if(p4!=null){
  85.             cp.setJavaOpenSPCoopHome(new PropertiesReader(p4,readCallsNotSynchronized));
  86.         }
  87.            
  88.         Properties p5 = PropertiesUtilities.examineStep5(log,path);
  89.         if(p5!=null){
  90.             cp.setClasspath(new PropertiesReader(p5,readCallsNotSynchronized));
  91.         }
  92.                
  93.         File fConfDirectory = null;
  94.         if(confDirectory!=null){
  95.             fConfDirectory = new File(confDirectory);
  96.         }
  97.         if(fConfDirectory!=null && fConfDirectory.exists() && fConfDirectory.isDirectory() ){
  98.             Properties p6 = PropertiesUtilities.examineStep6(log,path,fConfDirectory);
  99.             if(p6!=null){
  100.                 cp.setConfigDir(new PropertiesReader(p6,readCallsNotSynchronized));
  101.             }
  102.         }
  103.            
  104.         return cp;
  105.     }
  106.    
  107.     private static Properties examineStep1(Logger log,String variabile){
  108.         /*
  109.         System.out.println("--------- ENV --------------");
  110.         java.util.Map<String, String> env = System.getenv();
  111.         for (java.util.Iterator<String> iterator = env.keySet().iterator(); iterator.hasNext();) {
  112.             String key = (String) iterator.next();
  113.             System.out.println("\t["+key+"]=["+env.get(key)+"]");          
  114.         }
  115.         System.out.println("--------- ENV --------------");
  116.         */
  117.         String file = System.getenv(variabile);
  118.         String subject =  "Variabile di sistema "+variabile;
  119.         if(file!=null){
  120.             File ffile = new File(file);
  121.             if(ffile.exists()==false){
  122.                 log.error("["+subject+"] File non esistente: "+ffile.getAbsolutePath());
  123.                 return null;
  124.             }
  125.             if(ffile.canRead()==false){
  126.                 log.error("["+subject+"] File non accessibile: "+ffile.getAbsolutePath());
  127.                 return null;
  128.             }
  129.             InputStream is = null;
  130.             try{
  131.                 is = new FileInputStream(ffile);
  132.                 return PropertiesUtilities.getPropertiesReader(log,is,subject);
  133.             }catch(java.io.IOException e) {
  134.                 log.error("["+subject+"] file di properties non utilizzabile: "+e.getMessage(),e);
  135.             }finally{
  136.                 try{
  137.                     if(is!=null) {
  138.                         is.close();
  139.                     }
  140.                 }catch(Exception eClose){
  141.                     // close
  142.                 }
  143.             }
  144.         }
  145.         return null;
  146.     }
  147.    
  148.     private static Properties examineStep2(Logger log,String variabile){
  149.         /*
  150.         System.out.println("--------- ENV --------------");
  151.         java.util.Map<String, String> env = System.getenv();
  152.         for (java.util.Iterator<String> iterator = env.keySet().iterator(); iterator.hasNext();) {
  153.             String key = (String) iterator.next();
  154.             System.out.println("\t["+key+"]=["+env.get(key)+"]");          
  155.         }
  156.         System.out.println("--------- ENV --------------");
  157.         */
  158.         String file = System.getProperty(variabile);
  159.         String subject =  "Proprieta' di sistema "+variabile;
  160.         if(file!=null){
  161.             File ffile = new File(file);
  162.             if(ffile.exists()==false){
  163.                 log.error("["+subject+"] File non esistente: "+ffile.getAbsolutePath());
  164.                 return null;
  165.             }
  166.             if(ffile.canRead()==false){
  167.                 log.error("["+subject+"] File non accessibile: "+ffile.getAbsolutePath());
  168.                 return null;
  169.             }
  170.             InputStream is = null;
  171.             try{
  172.                 is = new FileInputStream(ffile);
  173.                 return PropertiesUtilities.getPropertiesReader(log,is,subject);
  174.             }catch(java.io.IOException e) {
  175.                 log.error("["+subject+"] file di properties non utilizzabile: "+e.getMessage(),e);
  176.             }finally{
  177.                 try{
  178.                     if(is!=null) {
  179.                         is.close();
  180.                     }
  181.                 }catch(Exception eClose){
  182.                     // close
  183.                 }
  184.             }
  185.         }
  186.         return null;
  187.     }
  188.    
  189.     private static Properties examineStep3(String OPENSPCOOP2_LOCAL_HOME,Logger log,String path){
  190.         /*
  191.         System.out.println("--------- ENV --------------");
  192.         java.util.Map<String, String> env = System.getenv();
  193.         for (java.util.Iterator<String> iterator = env.keySet().iterator(); iterator.hasNext();) {
  194.             String key = (String) iterator.next();
  195.             System.out.println("\t["+key+"]=["+env.get(key)+"]");          
  196.         }
  197.         System.out.println("--------- ENV --------------");
  198.         */
  199.         String dir = System.getenv(OPENSPCOOP2_LOCAL_HOME);
  200.         String subject =  "Variabile di sistema "+OPENSPCOOP2_LOCAL_HOME;
  201.         if(dir!=null){
  202.             File fDir = new File(dir);
  203.             if(fDir.exists()==false){
  204.                 log.error("["+subject+"] Directory non esistente: "+fDir.getAbsolutePath());
  205.                 return null;
  206.             }
  207.             if(fDir.canRead()==false){
  208.                 log.error("["+subject+"] Directory non accessibile: "+fDir.getAbsolutePath());
  209.                 return null;
  210.             }
  211.             return PropertiesUtilities.getPropertiesReader(log,fDir.getAbsolutePath()+File.separatorChar+path,subject);
  212.         }
  213.         return null;
  214.     }
  215.    
  216.     private static Properties examineStep4(String OPENSPCOOP2_LOCAL_HOME,Logger log,String path){
  217.         /*  
  218.         System.out.println("--------- PROPERTIES --------------");
  219.         java.util.Properties properties = System.getProperties();
  220.         java.util.Enumeration<?> enumProperties = properties.keys();
  221.         while (enumProperties.hasMoreElements()) {
  222.             Object object = (Object) enumProperties.nextElement();
  223.             System.out.println("\t["+object+"]=["+properties.get(object)+"]");          
  224.         }
  225.         System.out.println("--------- PROPERTIES --------------");
  226.         */
  227.         String dir = System.getProperty(OPENSPCOOP2_LOCAL_HOME);
  228.         String subject =  "Proprieta' di sistema "+OPENSPCOOP2_LOCAL_HOME;
  229.         if(dir!=null){
  230.             File fDir = new File(dir);
  231.             if(fDir.exists()==false){
  232.                 log.error("["+subject+"] Directory non esistente: "+fDir.getAbsolutePath());
  233.                 return null;
  234.             }
  235.             if(fDir.canRead()==false){
  236.                 log.error("["+subject+"] Directory non accessibile: "+fDir.getAbsolutePath());
  237.                 return null;
  238.             }
  239.             return PropertiesUtilities.getPropertiesReader(log,fDir.getAbsolutePath()+File.separatorChar+path,subject);
  240.         }
  241.         return null;
  242.     }
  243.    
  244.     private static Properties examineStep5(Logger log,String path){
  245.         return PropertiesUtilities.getPropertiesReader(log, PropertiesUtilities.class.getResourceAsStream("/"+path), "CLASSPATH: "+path);
  246.     }
  247.    
  248.     private static Properties examineStep6(Logger log,String path,File fConfDirectory){
  249.         File f = new File(fConfDirectory,path);
  250.         if(f.exists()){
  251.             return PropertiesUtilities.getPropertiesReader(log,f.getAbsolutePath(), "CONFIG_DIR_OPENSPCOOP/"+path);
  252.         }
  253.         return null;
  254.     }
  255.    
  256.     private static Properties getPropertiesReader(Logger log,String path,String subject){
  257.         if(path!=null){
  258.             File f = new File(path);
  259.             if(!f.exists()){
  260.                 // NON DEVO SEGNALARE L'ERRORE log.error("["+subject+"] file di properties non esistente: "+f.getAbsolutePath());
  261.                 return null;
  262.             }
  263.             if(!f.canRead()){
  264.                 log.error("["+subject+"] file di properties non accessibile: "+f.getAbsolutePath());
  265.                 return null;
  266.             }
  267.             InputStream is = null;
  268.             try{
  269.                 is = new FileInputStream(f);
  270.                 return PropertiesUtilities.getPropertiesReader(log,is,subject);
  271.             }catch(java.io.IOException e) {
  272.                 log.error("["+subject+"] file di properties non utilizzabile: "+e.getMessage(),e);
  273.             }finally{
  274.                 try{
  275.                     if(is!=null) {
  276.                         is.close();
  277.                     }
  278.                 }catch(Exception eClose){
  279.                     // close
  280.                 }
  281.             }
  282.         }
  283.         return null;
  284.     }
  285.     private static Properties getPropertiesReader(Logger log,InputStream is,String subject){
  286.         if(is!=null){
  287.             Properties propertiesReader = null;
  288.             try{  
  289.                 propertiesReader = new Properties();
  290.                 propertiesReader.load(is);
  291.             }catch(java.io.IOException e) {
  292.                 propertiesReader = null;
  293.                 log.error("["+subject+"] file di properties non utilizzabile: "+e.getMessage(),e);
  294.             }finally{
  295.                 try{
  296.                     if(is!=null) {
  297.                         is.close();
  298.                     }
  299.                 }catch(Exception eClose){
  300.                     // close
  301.                 }
  302.             }
  303.                
  304.             if(propertiesReader!=null){
  305.                 return propertiesReader;
  306.             }
  307.             return null;
  308.         }
  309.         return null;
  310.     }

  311.    
  312.    
  313.     public static Properties convertTextToProperties(String text) {
  314.         Scanner scanner = new Scanner(text);
  315.         Properties properties = new Properties();
  316.         try {
  317.             while (scanner.hasNextLine()) {
  318.                 String line = scanner.nextLine();
  319.                 if(line==null || line.trim().equals("")) {
  320.                     continue;
  321.                 }
  322.                 line = line.trim();
  323.                 if(line!=null && line.startsWith("#")) {
  324.                     continue;
  325.                 }
  326.                 if(line!=null && line.contains("=") && !line.startsWith("=")) {
  327.                     String key = line.split("=")[0];
  328.                     key = key.trim();
  329.                     int valueIndex = line.indexOf("=");
  330.                     String value = "";
  331.                     if(valueIndex<line.length()) {
  332.                         value = line.substring(valueIndex+1);
  333.                         value = value.trim();
  334.                     }
  335.                     properties.put(key, value);
  336.                 }
  337.             }
  338.         }finally {
  339.             scanner.close();
  340.         }
  341.         return properties;
  342.     }
  343.    
  344.     private static String EMPTY_COMMENT_VALUE = " "; // non uso "" senno su oracle non viene serializzato essendo null
  345.     private static String KEY_COMMENT_UNIQUE = "#C_ID#_";
  346.     private static String getKeyComment(int index) {
  347.         return KEY_COMMENT_UNIQUE.replace("ID", index+"");
  348.     }
  349.     private static String removeKeyComment(String keyComment, int index) {
  350.         String prefix = KEY_COMMENT_UNIQUE.replace("ID", index+"");
  351.         return keyComment.replace(prefix,"");
  352.     }
  353.     public static SortedMap<String> convertTextToSortedMap(String text) throws UtilsException {
  354.         return convertTextToSortedMap(text, false);
  355.     }
  356.     @SuppressWarnings("unchecked")
  357.     public static SortedMap<String> convertTextToSortedMap(String text, boolean addCommentAsEntry) throws UtilsException {
  358.         return (SortedMap<String>) _convertTextToSortedMap(text, addCommentAsEntry, false);
  359.     }
  360.     public static SortedMap<List<String>> convertTextToSortedListMap(String text) throws UtilsException {
  361.         return convertTextToSortedListMap(text, false);
  362.     }
  363.     @SuppressWarnings("unchecked")
  364.     public static SortedMap<List<String>> convertTextToSortedListMap(String text, boolean addCommentAsEntry) throws UtilsException {
  365.         return (SortedMap<List<String>>) _convertTextToSortedMap(text, addCommentAsEntry, true);
  366.     }
  367.     private static SortedMap<?> _convertTextToSortedMap(String text, boolean addCommentAsEntry, boolean listEnabled) throws UtilsException {
  368.         Scanner scanner = new Scanner(text);
  369.         SortedMap<String> propertiesString = null;
  370.         SortedMap<List<String>> propertiesList = null;
  371.         if(listEnabled) {
  372.             propertiesList = new SortedMap<List<String>>();
  373.         }
  374.         else {
  375.             propertiesString = new SortedMap<String>();
  376.         }
  377.         try {
  378.             int index = 0;
  379.             while (scanner.hasNextLine()) {
  380.                 String line = scanner.nextLine();
  381.                 if(line==null || line.trim().equals("")) {
  382.                     continue;
  383.                 }
  384.                 line = line.trim();
  385.                 if(line.startsWith("#")) {
  386.                     if(addCommentAsEntry) {
  387.                         String key = getKeyComment(index)+line;
  388.                         //System.out.println("ADD COMMENT '"+key+"'");
  389.                         if(listEnabled) {
  390.                             List<String> l = new ArrayList<>();
  391.                             l.add(EMPTY_COMMENT_VALUE);
  392.                             propertiesList.add(key, l);
  393.                         }
  394.                         else {
  395.                             propertiesString.add(key, EMPTY_COMMENT_VALUE);
  396.                         }
  397.                         index++;
  398.                     }
  399.                     continue;
  400.                 }
  401.                 if(line.contains("=")) {
  402.                     String key = line.split("=")[0];
  403.                     key = key.trim();
  404.                     int valueIndex = line.indexOf("=");
  405.                     String value = "";
  406.                     if(valueIndex<line.length()) {
  407.                         value = line.substring(valueIndex+1);
  408.                         value = value.trim();
  409.                     }
  410.                     if(listEnabled) {
  411.                         List<String> l = propertiesList.get(key);
  412.                         if(l==null) {
  413.                             l = new ArrayList<>();
  414.                             propertiesList.add(key, l);
  415.                         }
  416.                         l.add(value);
  417.                     }
  418.                     else {
  419.                         propertiesString.add(key, value);
  420.                     }
  421.                 }
  422.             }
  423.         }finally {
  424.             scanner.close();
  425.         }
  426.         return listEnabled ? propertiesList : propertiesString;
  427.     }
  428.    
  429.     public static String convertSortedMapToText(SortedMap<String> map) throws UtilsException {
  430.         return convertSortedMapToText(map, false);
  431.     }
  432.     public static String convertSortedMapToText(SortedMap<String> map, boolean commentAsEntry) throws UtilsException {
  433.         return _convertSortedMapToText(map, commentAsEntry, false);
  434.     }
  435.     public static String convertSorteListdMapToText(SortedMap<List<String>> map) throws UtilsException {
  436.         return convertSortedListMapToText(map, false);
  437.     }
  438.     public static String convertSortedListMapToText(SortedMap<List<String>> map, boolean commentAsEntry) throws UtilsException {
  439.         return _convertSortedMapToText(map, commentAsEntry, true);
  440.     }
  441.     private static String _convertSortedMapToText(SortedMap<?> map, boolean commentAsEntry, boolean listEnabled) throws UtilsException {
  442.         StringBuilder sb = new StringBuilder();
  443.         if(map!=null && !map.isEmpty()) {
  444.             int index = 0;
  445.             for (String key : map.keys()) {
  446.                
  447.                 if(key==null) {
  448.                     continue;
  449.                 }
  450.                                
  451.                 if(key.startsWith("#") && commentAsEntry) {
  452.                    
  453.                     if(sb.length() >0)
  454.                         sb.append("\n");
  455.                    
  456.                     //System.out.println("READ COMMENT '"+key+"'");
  457.                     String keyComment = getKeyComment(index);
  458.                     if(key.startsWith(keyComment)) {
  459.                         String line = removeKeyComment(key, index);
  460.                         //System.out.println("READ ADD COMMENT '"+line+"'");
  461.                         sb.append(line);
  462.                         index++;
  463.                     }
  464.                     else {
  465.                         //System.out.println("READ ADD ORIGINAL '"+key+"'");
  466.                         sb.append(key);
  467.                     }
  468.                     continue;
  469.                 }
  470.                                
  471.                 if(listEnabled) {
  472.                     @SuppressWarnings("unchecked")
  473.                     List<String> values = (List<String>) map.get(key);
  474.                     if(values!=null && !values.isEmpty()) {
  475.                         for (String value : values) {
  476.                             if(sb.length() >0)
  477.                                 sb.append("\n");
  478.                             sb.append(key).append("=").append(value);
  479.                         }
  480.                     }
  481.                 }else {
  482.                     if(sb.length() >0)
  483.                         sb.append("\n");
  484.                     String value = (String) map.get(key);
  485.                     sb.append(key).append("=").append(value);
  486.                 }
  487.             }  
  488.         }
  489.         return sb.toString();
  490.     }
  491. }