package eu.dnetlib.springutils.collections;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;

import eu.dnetlib.miscutils.collections.MappedCollection;
import eu.dnetlib.miscutils.functional.UnaryFunction;

/**
 * very useful in unit tests when you want to read many resources obtained from the spring resource loader into a
 * collection of strings.
 * 
 * @author marko
 * 
 */
public class ResourceReaderCollection extends MappedCollection<String, Resource> {

	/**
	 * construct a ResourceReaderCollection from a collection of resources.
	 * @param coll
	 */
	public ResourceReaderCollection(Collection<Resource> coll) {
		super(coll, new UnaryFunction<String, Resource>() {

			public String evaluate(Resource resource) {
				try {
					final StringWriter buffer = new StringWriter();
					IOUtils.copy(resource.getInputStream(), buffer);
					return buffer.toString();
				} catch (IOException e) {
					throw new IllegalArgumentException("cannot read resource", e);
				}
			}
		});
	}

}
