001 package org.nanocontainer.script.groovy; 002 003 import org.picocontainer.ComponentAdapter; 004 import org.picocontainer.MutablePicoContainer; 005 006 import java.util.Collection; 007 import java.util.Iterator; 008 009 /** 010 * This class can generate a Groovy script from a preconfigured container. 011 * This script can be passed to {@link GroovyContainerBuilder} to recreate 012 * a new container with the same configuration. 013 * <p/> 014 * This is practical in situations where a container configuration needs 015 * to be saved. 016 * 017 * @author Aslak Hellesøy 018 * @version $Revision: 3144 $ 019 */ 020 public class GroovyScriptGenerator { 021 // This implementation is ugly and naive. But it's all I need for now. 022 // When there are more requirements (in the form of tests), we can improve this. 023 public String generateScript(MutablePicoContainer pico) { 024 StringBuffer groovy = new StringBuffer(); 025 groovy.append("pico = new org.nanocontainer.reflection.DefaultNanoPicoContainer()\n"); 026 027 Collection componentAdapters = pico.getComponentAdapters(); 028 for (Iterator iterator = componentAdapters.iterator(); iterator.hasNext();) { 029 ComponentAdapter componentAdapter = (ComponentAdapter) iterator.next(); 030 031 Object componentKey = componentAdapter.getComponentKey(); 032 String groovyKey = null; 033 if (componentKey instanceof Class) { 034 groovyKey = ((Class) componentKey).getName(); 035 } else if (componentKey instanceof String) { 036 groovyKey = "\"" + componentKey + "\""; 037 } 038 039 Object componentInstance = componentAdapter.getComponentInstance(pico); 040 041 if (componentInstance instanceof String) { 042 groovy.append("pico.registerComponentInstance(" + groovyKey + ", \"" + componentInstance + "\")\n"); 043 } else { 044 groovy.append("pico.registerComponentImplementation(" + groovyKey + ", " + componentInstance.getClass().getName() + ")\n"); 045 } 046 } 047 return groovy.toString(); 048 } 049 }