import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;

/**
 * This is an object factory that when given a DirContext that
 * has the objectclass=drink attribute,
 * will create an instance of the corresponding Drink.
 */
public class DrinkFactory implements ObjectFactory {
    public DrinkFactory() {
    }

    public Object getObjectInstance(Object obj, Name name, Context ctx,
	Hashtable env) throws Exception {
	if (obj instanceof DirContext) {
	    DirContext thisCtx = (DirContext)obj;
	    try {
		Attributes attrs = thisCtx.getAttributes("");
//System.out.println("DrinkFactory got: " + attrs); // for debugging
		Attribute dt = attrs.get("drinktype");
		if (dt != null) {
		    String drinkType = (String)dt.get();

		    return new Drink(drinkType);
		}
	    } catch (NamingException e) {
		// debug
		System.err.println(e);
		e.printStackTrace();
	    }
	}

	// return null to indicate other factories should be tried
	return null;
    }
}
