package eu.dnetlib.contract.utils;

import java.util.ArrayList;
import java.util.Collection;

import org.opensaml.common.SAMLObject;

import eu.dnetlib.enabling.aas.saml.adapter.AdapterFactoryRegistry;
import eu.dnetlib.enabling.aas.saml.adapter.IAdapterFactory;

/**
 * Spring auxiliary class for performing collection -> array conversion.
 * Additionaly all openSAML model objects are proxied to SAML-lite object model.
 * @author mhorst
 *
 */
public class SAMLObjectCollectionToProxyArrayConverter {

	
	@SuppressWarnings("unchecked")
	public static org.opensaml.lite.common.SAMLObject[] convert(Collection<SAMLObject> source) throws Exception {
		if (source==null) {
			return null;
		} else {
			Collection<org.opensaml.lite.common.SAMLObject> results 
				= new ArrayList<org.opensaml.lite.common.SAMLObject>();
			for (SAMLObject currentSource : source) {
				IAdapterFactory adapterFactory = AdapterFactoryRegistry.lookup(currentSource.getClass());
				if (adapterFactory!=null) {
					results.add(adapterFactory.newInstance(currentSource));
				} else {
					throw new RuntimeException("no SAML-lite adapter factory " +
							"found for openSAML class " + currentSource.getClass().getCanonicalName());
				}
			}
			return results.toArray(new org.opensaml.lite.common.SAMLObject[results.size()]);
		}
	}
	
}
