Coverage Report - com.ctrip.apollo.core.utils.ResourceUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
ResourceUtils
67%
23/34
50%
7/14
10
 
 1  
 package com.ctrip.apollo.core.utils;
 2  
 
 3  
 import java.io.File;
 4  
 import java.io.FileInputStream;
 5  
 import java.io.IOException;
 6  
 import java.io.InputStream;
 7  
 import java.nio.file.Files;
 8  
 import java.nio.file.Path;
 9  
 import java.util.Enumeration;
 10  
 import java.util.Properties;
 11  
 
 12  
 import org.slf4j.Logger;
 13  
 import org.slf4j.LoggerFactory;
 14  
 
 15  0
 public class ResourceUtils {
 16  
 
 17  1
   private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);
 18  
 
 19  
   @SuppressWarnings("unchecked")
 20  
   public static Properties readConfigFile(String configPath, Properties defaults) {
 21  1
     InputStream in = ClassLoaderUtil.getLoader().getResourceAsStream(configPath);
 22  1
     logger.info("Reading config from resource {}", configPath);
 23  1
     Properties props = new Properties();
 24  
     try {
 25  1
       if (in == null) {
 26  
         // load outside resource under current user path
 27  0
         Path path = new File(System.getProperty("user.dir") + configPath).toPath();
 28  0
         if (Files.isReadable(path)) {
 29  0
           in = new FileInputStream(path.toFile());
 30  0
           logger.info("Reading config from file {} ", path);
 31  
         } else {
 32  0
           logger.info("Could not find available config file");
 33  
         }
 34  
       }
 35  1
       if (defaults != null) {
 36  1
         props.putAll(defaults);
 37  
       }
 38  
 
 39  1
       if (in != null) {
 40  1
         props.load(in);
 41  1
         in.close();
 42  
       }
 43  0
     } catch (Exception ex) {
 44  0
       logger.warn("Reading config failed: {}", ex.getMessage());
 45  
     } finally {
 46  1
       if (in != null) {
 47  
         try {
 48  1
           in.close();
 49  0
         } catch (IOException ex) {
 50  0
           logger.warn("Close config failed: {}", ex.getMessage());
 51  1
         }
 52  
       }
 53  
     }
 54  1
     StringBuilder sb = new StringBuilder();
 55  1
     for (Enumeration<String> e = (Enumeration<String>) props.propertyNames(); e
 56  3
         .hasMoreElements();) {
 57  2
       String key = e.nextElement();
 58  2
       String val = (String) props.getProperty(key);
 59  2
       sb.append(key).append('=').append(val).append('\n');
 60  2
     }
 61  1
     if (sb.length() > 0) {
 62  1
       logger.info("Reading properties: \n" + sb.toString());
 63  
     } else {
 64  0
       logger.info("No available properties");
 65  
     }
 66  1
     return props;
 67  
   }
 68  
 }