001 /******************************************************************************* 002 * Copyright (C) PicoContainer Organization. All rights reserved. 003 * --------------------------------------------------------------------------- 004 * The software in this package is published under the terms of the BSD style 005 * license a copy of which has been included with this distribution in the 006 * LICENSE.txt file. 007 ******************************************************************************/ 008 package org.picocontainer.script.groovy; 009 010 import org.picocontainer.ComponentAdapter; 011 import org.picocontainer.MutablePicoContainer; 012 013 import java.util.Collection; 014 015 /** 016 * This class can generate a Groovy script from a preconfigured container. 017 * This script can be passed to {@link GroovyContainerBuilder} to recreate 018 * a new container with the same configuration. 019 * <p/> 020 * This is practical in situations where a container configuration needs 021 * to be saved. 022 * 023 * @author Aslak Hellesøy 024 */ 025 public class GroovyScriptGenerator { 026 // This implementation is ugly and naive. But it's all I need for now. 027 // When there are more requirements (in the form of tests), we can improve this. 028 public String generateScript(MutablePicoContainer pico) { 029 StringBuffer groovy = new StringBuffer(); 030 groovy.append("pico = new org.picocontainer.classname.DefaultClassLoadingPicoContainer()\n"); 031 032 Collection<ComponentAdapter<?>> componentAdapters = pico.getComponentAdapters(); 033 for (ComponentAdapter<?> componentAdapter : componentAdapters) { 034 Object componentKey = componentAdapter.getComponentKey(); 035 String groovyKey = null; 036 if (componentKey instanceof Class) { 037 groovyKey = ((Class<?>) componentKey).getName(); 038 } else if (componentKey instanceof String) { 039 groovyKey = "\"" + componentKey + "\""; 040 } 041 042 Object componentInstance = componentAdapter.getComponentInstance(pico, null); 043 044 if (componentInstance instanceof String) { 045 groovy.append("pico.addComponent(") 046 .append(groovyKey) 047 .append(", (Object) \"") 048 .append(componentInstance) 049 .append("\")\n"); 050 } else { 051 groovy.append("pico.addComponent(") 052 .append(groovyKey) 053 .append(", ") 054 .append(componentInstance.getClass().getName()) 055 .append(")\n"); 056 } 057 } 058 return groovy.toString(); 059 } 060 }