package eu.dnetlib.springutils.condbean;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;

/**
 * Load properties from a spring resource (classpath, filesystem, etc).
 * 
 * @author marko
 * 
 */
public class ResourcePropertyFinder implements PropertyFinder {

	/**
	 * logger. 
	 */
	private static final Log log = LogFactory.getLog(ResourcePropertyFinder.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * properties are loaded from this resource.
	 */
	private Resource resource;

	/** 
	 * {@inheritDoc}
	 * @see eu.dnetlib.springutils.condbean.PropertyFinder#getProperty(java.lang.String)
	 */
	@Override
	public String getProperty(final String name) {
		if(resource == null)
			return null;
		try {
			final Properties props = new Properties();
			props.load(resource.getInputStream());

			final String res = props.getProperty(name);
			if (res != null && !res.isEmpty())
				return res;
		} catch(final FileNotFoundException e) {
				return null;
		} catch (final IOException e) {
			log.warn("cannot open properties", e);
		}
		return null;
	}

	public Resource getResource() {
		return resource;
	}

	public void setResource(final Resource resource) {
		this.resource = resource;
	}

}
