package eu.dnetlib.springutils.stringtemplate;

import java.io.StringWriter;

import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource;

/**
 * Construct a string template instance from a spring resource (classpath or filesystem).
 *
 * @author marko
 *
 */
public class StringTemplateFactory implements FactoryBean {

	/**
	 * template source.
	 */
	private Resource template;

	/**
	 * {@inheritDoc}
	 * @see org.springframework.beans.factory.FactoryBean#getObject()
	 */
	@Override
	public Object getObject() throws Exception {
		StringWriter body = new StringWriter();
		IOUtils.copy(template.getInputStream(), body);
		return new StringTemplate(body.toString());
	}

	/**
	 * {@inheritDoc}
	 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
	 */
	@Override
	public Class<?> getObjectType() {
		return StringTemplate.class;
	}

	/**
	 * {@inheritDoc}
	 * @see org.springframework.beans.factory.FactoryBean#isSingleton()
	 */
	@Override
	public boolean isSingleton() {
		return false;
	}

	public Resource getTemplate() {
		return template;
	}

	public void setTemplate(Resource template) {
		this.template = template;
	}

}
