/*******************************************************************************
 * Copyright (c) 2007 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.cosmos.internal.dr.drs.service.handler.common;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.IOutputter;
import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.IOutputterFactory;

/**
 * This is a factory class that creates instances of IOutputter based on an id value.
 * The id value represents the class name of the outputter that will be instantiated.
 */
public class OutputterFactoryImpl implements IOutputterFactory {

	/**
	 * Caches outputters that have been created.
	 */
	protected Map<String, IOutputter> outputterCache = new HashMap<String, IOutputter>();

	/**
	 * Factory method that creates outputters based on an id.
	 * The id contains '/' characters that specifies the path of the outputter class.
	 */
	public IOutputter createOutputter(String id) throws Exception{
		IOutputter retObj = outputterCache.get(id);
		if (retObj == null){
			String classString = id.replaceAll("/", "."); //$NON-NLS-1$ //$NON-NLS-2$
	  		Class clazz = Class.forName(classString);
	        Constructor ct = clazz.getConstructor();
	        Object arglist[] = new Object[0];
	        retObj = (IOutputter)ct.newInstance(arglist);
	        outputterCache.put(id, retObj);
		}
		return retObj;
	}

}
