Tuesday, November 10, 2020

Property file loader

 properties file is used to store project configuration data or settings. You can write your own property file loader or use Java java.util.Properties directly.

Here is an sample of custom property file loader.


import com.test.properties.exception.PropertyException;

import org.apache.log4j.Logger;


import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

import java.util.Properties;


public class PropertyLoader {

    private final Map<String, Properties> propertyRepo;

    private static final Logger LOGGER = Logger.getLogger(PropertyLoader.class);

    private PropertyLoader() {

        propertyRepo = new HashMap<String, Properties>();

    }

    public String getProperty(final String propertyFileLocation, final String property, final String defaultValue) throws PropertyException {

        Properties properties = propertyRepo.get(propertyFileLocation);

        if (properties == null) {

            properties = loadPropertes(propertyFileLocation);

            propertyRepo.put(propertyFileLocation, properties);

        }

        return properties.getProperty(property) != null ? properties.getProperty(property) : defaultValue;

    }

    public String getProperty(final String propertyFileLocation, final String property) throws PropertyException {

        return getProperty(propertyFileLocation, property, null);

    }

    private static Properties loadPropertes(final String fileLocation) throws PropertyException {

        Properties properties = new Properties();

        try {

            try (InputStream inputStream = new FileInputStream(fileLocation)) {

                properties.load(inputStream);

            }

        } catch (IOException e) {

            LOGGER.error("Error in loading property file : " + fileLocation, e);

            throw new PropertyException("Error in loading property file : " + fileLocation);

        }

        return properties;

    }

    public static PropertyLoader getInstance() {

        return HOLDER.INSTANCE;

    }

    private static final class HOLDER {

        private static final PropertyLoader INSTANCE = new PropertyLoader();

    }

}


No comments:

Post a Comment