package com.hammurapi.common;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * Helper class.
 * @author Pavel Vlasov
 *
 */
public class Util {
	
	/**
	 * Loads single instance of service.
	 * @param <T>
	 * @param type
	 * @return
	 */
	static Context loadContext() {
		List<Context> parts = new ArrayList<Context>();
		Iterator<Context> it = ServiceLoader.load(Context.class, Util.class.getClassLoader()).iterator();
		while (it.hasNext()) {
			parts.add(it.next());
		}
		parts.add(new DefaultContext(Util.class.getClassLoader(), null));
		return new CompositeContext(parts.toArray(new Context[parts.size()]));
	}

	/**
	 * Wraps a single object into array to avoid problems with generic arrays.
	 * @param <V>
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <V> V[] wrap(V obj) {
		if (obj == null) {
			return (V[]) new Object[] {null};
		}
		V[] ret = (V[]) Array.newInstance(obj.getClass(), 1);
		ret[0] = obj;
		return ret;
	}

}
