Update of /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24110/src/java/org/hibernate/tool/hbm2x Modified Files: AbstractExporter.java DocExporter.java XMLPrettyPrinter.java ArtifactCollector.java TemplateHelper.java HibernateMappingExporter.java TemplateProducer.java HibernateConfigurationExporter.java GenericExporter.java Removed Files: ImportProducer.java FreeMarkerTemplateHelper.java Log Message: hbm2hbmxml simplified Index: AbstractExporter.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/AbstractExporter.java,v retrieving revision 1.17 retrieving revision 1.18 diff -u -d -r1.17 -r1.18 --- AbstractExporter.java 6 Feb 2006 09:08:08 -0000 1.17 +++ AbstractExporter.java 7 Feb 2006 14:02:15 -0000 1.18 @@ -15,8 +15,8 @@ import org.hibernate.util.StringHelper; /** - * Base exporter for the velocity and direct output generation. - * Sets up the velocity environment + * Base exporter for the template and direct output generation. + * Sets up the template environment * * @author max and david */ @@ -87,11 +87,13 @@ } public void start() { + setTemplateHelper( new TemplateHelper() ); setupTemplates(); setupContext(); doStart(); - cleanUpContext(); + cleanUpContext(); setTemplateHelper(null); + getArtifactCollector().formatFiles(); } abstract public void doStart(); @@ -126,7 +128,6 @@ } protected void setupTemplates() { - setTemplateHelper( new FreeMarkerTemplateHelper() ); if(log.isDebugEnabled()) { log.debug(getClass().getName() + " outputdir:" + getOutputDirectory() + " templatePrefix: " + getTemplatePrefix() + " path: " + toString(templatePaths) ); } @@ -182,7 +183,7 @@ } } - // called to have "true"/"false" strings returned as real booleans in velocity code. + // called to have "true"/"false" strings returned as real booleans in templates code. private Object transformValue(Object value) { if("true".equals(value)) { return Boolean.TRUE; Index: DocExporter.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/DocExporter.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -d -r1.12 -r1.13 --- DocExporter.java 6 Feb 2006 09:08:08 -0000 1.12 +++ DocExporter.java 7 Feb 2006 14:02:15 -0000 1.13 @@ -45,67 +45,67 @@ private static final String FILE_HEADER = "doc/header.html"; /** - * Velocity Template used for the index of the table documentation. + * Template used for the index of the table documentation. */ private static final String VM_TABLES_INDEX = "doc/tables/index.ftl"; /** - * Velocity Template used for index of the entity documentation + * Template used for index of the entity documentation */ private static final String VM_ENTITIES_INDEX = "doc/entities/index.ftl"; /** - * Velocity Template used for the Classes Summary + * Template used for the Classes Summary */ private static final String VM_ENTITIES_SUMMARY = "doc/entities/summary.ftl"; /** - * Velocity Template used for Class details + * Template used for Class details */ private static final String VM_ENTITIES_ENTITY = "doc/entities/entity.ftl"; /** - * Velocity Template used to create the Package List + * Template used to create the Package List */ private static final String VM_ENTITIES_PACKAGE_LIST = "doc/entities/package-list.ftl"; /** - * Velocity Template used to create the list of all Classes + * Template used to create the list of all Classes */ private static final String VM_ENTITIES_ENTITY_LIST = "doc/entities/allEntity-list.ftl"; /** - * Velocity Template used to create List of Classes specific to packages. + * Template used to create List of Classes specific to packages. */ private static final String VM_ENTITIES_PERPACKAGE_ENTITY_LIST = "doc/entities/perPackageEntity-list.ftl"; /** - * Velocity Template used to show the specific package details + * Template used to show the specific package details */ private static final String VM_ENTITIES_PACKAGE_SUMMARY = "doc/entities/package-summary.ftl"; /** - * Velocity Template used for the Tables Summary. + * Template used for the Tables Summary. */ private static final String VM_TABLES_SUMMARY = "doc/tables/summary.ftl"; /** - * Velocity Template used for table lists. + * Template used for table lists. */ private static final String VM_TABLES_TABLE_LIST = "doc/tables/table-list.ftl"; /** - * Velocity Template used for schema lists. + * Template used for schema lists. */ private static final String VM_TABLES_SCHEMA_LIST = "doc/tables/schema-list.ftl"; /** - * Velocity Template used for Schema Summary. + * Template used for Schema Summary. */ private static final String VM_TABLES_SCHEMA_SUMMARY = "doc/tables/schema-summary.ftl"; /** - * Velocity Template used for the Table Details. + * Template used for the Table Details. */ private static final String VM_TABLES_TABLE = "doc/tables/table.ftl"; @@ -460,9 +460,9 @@ } /** - * Run Velocity. + * Run templates. * - * @param parameters the parameters to pass to the velocity template. + * @param parameters the parameters to pass to the templates template. * @param templateName the template to use. * @param outputFile the output file. */ @@ -470,7 +470,6 @@ File outputFile) { TemplateProducer producer = new TemplateProducer(getTemplateHelper(), getArtifactCollector() ); - String filename = outputFile.toString(); producer.produce(parameters, templateName, outputFile, templateName); } Index: XMLPrettyPrinter.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/XMLPrettyPrinter.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -d -r1.5 -r1.6 --- XMLPrettyPrinter.java 21 Sep 2005 18:20:07 -0000 1.5 +++ XMLPrettyPrinter.java 7 Feb 2006 14:02:15 -0000 1.6 @@ -17,6 +17,7 @@ import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; +import java.util.Arrays; import java.util.Properties; import org.apache.commons.logging.Log; @@ -55,6 +56,7 @@ } public void write(char[] cbuf, int off, int len) throws IOException { + } } ) ); @@ -69,7 +71,7 @@ } public static void prettyPrintFiles(Tidy tidy, File[] inputfiles, - File[] outputfiles) throws IOException { + File[] outputfiles, boolean silent) throws IOException { if ( (inputfiles == null || outputfiles == null ) || (inputfiles.length != outputfiles.length ) ) { @@ -78,12 +80,12 @@ } for (int i = 0; i < outputfiles.length; i++) { - prettyPrintFile( tidy, inputfiles[i], outputfiles[i] ); + prettyPrintFile( tidy, inputfiles[i], outputfiles[i], silent ); } } public static void prettyPrintFile(Tidy tidy, File inputFile, - File outputFile) throws IOException { + File outputFile, boolean silent) throws IOException { log.debug( "XMLPrettyPrinting " + inputFile.getAbsolutePath() ); InputStream is; @@ -127,8 +129,12 @@ } if ( tidy.getParseErrors() > 0 ) { - throw new ExporterException( "Tidy was unable to process file " - + inputFile + ", " + tidy.getParseErrors() + " errors found." ); + if(silent) { + log.info("Tidy was unable to process file " + inputFile + ", " + tidy.getParseErrors() + " errors found." ); + } else { + throw new ExporterException( "Tidy was unable to process file " + + inputFile + ", " + tidy.getParseErrors() + " errors found." ); + } } } @@ -136,7 +142,7 @@ * @param outputdir * @throws IOException */ - public static void prettyPrintDirectory(File outputdir, final String prefix) + public static void prettyPrintDirectory(File outputdir, final String prefix, boolean silent) throws IOException { File[] files = outputdir.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { @@ -145,6 +151,6 @@ } ); Tidy tidy = getDefaultTidy(); - prettyPrintFiles( tidy, files, files ); + prettyPrintFiles( tidy, files, files, silent ); } } Index: ArtifactCollector.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/ArtifactCollector.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -d -r1.1 -r1.2 --- ArtifactCollector.java 21 Sep 2005 18:20:07 -0000 1.1 +++ ArtifactCollector.java 7 Feb 2006 14:02:15 -0000 1.2 @@ -1,8 +1,10 @@ package org.hibernate.tool.hbm2x; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -39,5 +41,24 @@ public Set getFileTypes() { return files.keySet(); } + + public void formatFiles() { + + List list = (List) files.get("xml"); + if(list!=null && !list.isEmpty()) { + for (Iterator iter = list.iterator(); iter.hasNext();) { + File xmlFile = (File) iter.next(); + try { + XMLPrettyPrinter.prettyPrintFile(XMLPrettyPrinter.getDefaultTidy(), xmlFile, xmlFile, true); + } + catch (IOException e) { + throw new ExporterException("Could not format XML file: " + xmlFile,e); + } + } + } + + list = (List) files.get("java"); + // format java + } } Index: TemplateHelper.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/TemplateHelper.java,v retrieving revision 1.18 retrieving revision 1.19 diff -u -d -r1.18 -r1.19 --- TemplateHelper.java 6 Feb 2006 09:08:08 -0000 1.18 +++ TemplateHelper.java 7 Feb 2006 14:02:15 -0000 1.19 @@ -9,27 +9,50 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; import java.io.Writer; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import freemarker.cache.ClassTemplateLoader; +import freemarker.cache.FileTemplateLoader; +import freemarker.cache.MultiTemplateLoader; +import freemarker.cache.TemplateLoader; +import freemarker.template.Configuration; +import freemarker.template.ObjectWrapper; +import freemarker.template.SimpleDate; +import freemarker.template.SimpleHash; +import freemarker.template.Template; +import freemarker.template.TemplateDateModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import freemarker.template.TemplateModelException; + /** * - * Helper and wrapper for a Template engine (currently only Velocity). + * Helper and wrapper for a Template engine (currently only FreeMarker). * Exposes only the essential functions to avoid too much coupling else where. * * @author max * */ -public abstract class TemplateHelper { +public class TemplateHelper { static final Log log = LogFactory.getLog(TemplateHelper.class); private String templatePrefix; private File outputDirectory; + protected Configuration freeMarkerEngine; + + protected SimpleHash context; + public TemplateHelper() { } @@ -37,10 +60,28 @@ public void init(File outputDirectory, String templatePrefix, String[] templatePaths) { this.outputDirectory = outputDirectory; this.templatePrefix = templatePrefix; - } - - public void setupContext() { - + + context = new SimpleHash(ObjectWrapper.BEANS_WRAPPER); + freeMarkerEngine = new Configuration(); + + List loaders = new ArrayList(); + + for (int i = 0; i < templatePaths.length; i++) { + File file = new File(templatePaths[i]); + if(file.exists() && file.isDirectory()) { + try { + loaders.add(new FileTemplateLoader(file)); + } + catch (IOException e) { + throw new ExporterException("Problems with templatepath " + file, e); + } + } else { + log.warn("template path" + file + " either does not exist or is not a directory"); + } + } + loaders.add(new ClassTemplateLoader(this.getClass(),"/")); // the template names are like pojo/Somewhere so have to be a rooted classpathloader + + freeMarkerEngine.setTemplateLoader(new MultiTemplateLoader((TemplateLoader[]) loaders.toArray(new TemplateLoader[loaders.size()]))); } @@ -97,33 +138,19 @@ } } - /** look up the template named templateName via the paths and print the content to the output */ - abstract public void processTemplate(String templateName, Writer output); public File getOutputDirectory() { return outputDirectory; } - /** - * Check if the template exists. Tries to search with the templatePrefix first and then secondly without the template prefix. - * - * @param name - * @return - */ - abstract String getTemplateName(String name); - + - /** Uses the contents of template string as the template and write it directly to the output */ - abstract public void processString(String template, Writer output); - public void putInContext(String key, Object value) { log.trace("putInContext " + key + "=" + value); if(value == null) throw new IllegalStateException("value must not be null for " + key); Object replaced = internalPutInContext(key,value); if(replaced!=null) throw new IllegalStateException(replaced + " found when setting " + key); } - - abstract protected Object internalPutInContext(String key, Object value); - + public void removeFromContext(String key, Object expected) { log.trace("removeFromContext " + key + "=" + expected); Object replaced = internalRemoveFromContext(key); @@ -133,10 +160,6 @@ }*/ } - abstract protected Object internalRemoveFromContext(String key); - - abstract public boolean templateExists(String name); - public void ensureExistence(File destination) { // if the directory exists, make sure it is a directory File dir = destination.getAbsoluteFile().getParentFile(); @@ -153,4 +176,113 @@ protected String getTemplatePrefix() { return templatePrefix; } + + protected SimpleHash getContext() { + return context; + } + + public void processString(String template, Writer output) { + + try { + Reader r = new StringReader(template); + Template t = new Template("unknown", r, freeMarkerEngine); + + t.process(getContext(), output); + } + catch (IOException e) { + throw new ExporterException("Error while processing template string", e); + } + catch (TemplateException te) { + throw new ExporterException("Error while processing template string", te); + } + catch (Exception e) { + throw new ExporterException("Error while processing template string", e); + } + } + + + + + public void setupContext() { + getContext().put("version", Version.getDefault()); + getContext().put("ctx", getContext() ); //TODO: I would like to remove this, but don't know another way to actually get the list possible "root" keys for debugging. + getContext().put("templates", new Templates()); + + getContext().put("date", new SimpleDate(new Date(), TemplateDateModel.DATETIME)); + + } + + protected Object internalPutInContext(String key, Object value) { + TemplateModel model = null; + try { + model = getContext().get(key); + } + catch (TemplateModelException e) { + throw new ExporterException("Could not get key " + key, e); + } + getContext().put(key, value); + return model; + } + + protected Object internalRemoveFromContext(String key) { + TemplateModel model = null; + try { + model = getContext().get(key); + } + catch (TemplateModelException e) { + throw new ExporterException("Could not get key " + key, e); + } + getContext().remove(key); + return model; + } + + /** look up the template named templateName via the paths and print the content to the output */ + public void processTemplate(String templateName, Writer output) { + try { + Template template = freeMarkerEngine.getTemplate(getTemplateName(templateName)); + template.process(getContext(), output); + } + catch (IOException e) { + throw new ExporterException("Error while processing template " + templateName, e); + } + catch (TemplateException te) { + throw new ExporterException("Error while processing template string", te); + } + catch (Exception e) { + throw new ExporterException("Error while processing template " + templateName, e); + } + } + + /** + * Check if the template exists. Tries to search with the templatePrefix first and then secondly without the template prefix. + * + * @param name + * @return + */ + protected String getTemplateName(String name) { + if(!name.endsWith(".ftl")) { + name = name + ".ftl"; + } + + if(getTemplatePrefix()!=null && templateExists(getTemplatePrefix() + name)) { + return getTemplatePrefix() + name; + } + + if(templateExists(name)) { + return name; + } + + throw new ExporterException("Could not find template with name: " + name); + } + + public boolean templateExists(String templateName) { + TemplateLoader templateLoader = freeMarkerEngine.getTemplateLoader(); + + try { + return templateLoader.findTemplateSource(templateName)!=null; + } + catch (IOException e) { + throw new ExporterException("templateExists for " + templateName + " failed", e); + } + } } Index: HibernateMappingExporter.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/HibernateMappingExporter.java,v retrieving revision 1.28 retrieving revision 1.29 diff -u -d -r1.28 -r1.29 --- HibernateMappingExporter.java 6 Feb 2006 09:08:08 -0000 1.28 +++ HibernateMappingExporter.java 7 Feb 2006 14:02:15 -0000 1.29 @@ -3,158 +3,75 @@ */ package org.hibernate.tool.hbm2x; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; +import java.util.HashMap; +import java.util.Map; import org.hibernate.cfg.Configuration; -import org.hibernate.mapping.Component; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Property; +import org.hibernate.tool.hbm2x.pojo.POJOClass; +import org.hibernate.util.StringHelper; /** * @author david and max */ -public class HibernateMappingExporter extends AbstractExporter implements ConfigurationVisitor { +public class HibernateMappingExporter extends GenericExporter { - protected HibernateMappingGlobalSettings globalSettings = new HibernateMappingGlobalSettings(); - private Writer writer; - private File file; - - public HibernateMappingExporter(Configuration cfg, File outputdir) { - super(cfg, outputdir); + protected HibernateMappingGlobalSettings globalSettings = new HibernateMappingGlobalSettings(); + + protected void setupContext() { + super.setupContext(); + getTemplateHelper().putInContext("hmgs", globalSettings); } - - public HibernateMappingExporter() { - + + public void setGlobalSettings(HibernateMappingGlobalSettings hgs) { + this.globalSettings = hgs; } - - public void endComponent(Component componenet) throws ExporterException { } - public void endMapping(Configuration cfg) { } - public boolean startMapping(Configuration cfg) {return true; } - - public boolean startPersistentClass(PersistentClass clazz) { - - try { - getTemplateHelper().putInContext("clazz", clazz); - - file = getFileForClassName(getOutputDirectory(), clazz.getEntityName(), ".hbm.xml"); - getTemplateHelper().ensureExistence(file); - if(writer!=null) throw new IllegalStateException("Writer must be null when starting a new persistent class!"); - writer = new BufferedWriter(new FileWriter(file)); - getTemplateHelper().processTemplate("hbm/hibernate-mapping.hbm.ftl", writer); - getTemplateHelper().processTemplate("hbm/persistentclass.hbm.ftl", writer); - } - catch (IOException e) { - throw new ExporterException("Error while starting on " + clazz, e); - } - return true; + + public void doStart() { + exportGeneralSettings(); + + super.doStart(); } - public void endPersistentClass(PersistentClass clazz) throws ExporterException { - - try { - writer.write("</" + getCfg2HbmTool().getTag(clazz) +">\n"); - getTemplateHelper().removeFromContext("clazz", clazz); - - writer.write("</hibernate-mapping>"); - writer.flush(); - writer.close(); - writer = null; - - XMLPrettyPrinter.prettyPrintFile(XMLPrettyPrinter.getDefaultTidy(), file, file); - } - catch (IOException e) { - throw new ExporterException("Error while processing template", e); - } - - } - - public void startIdentifierProperty(Property identifierProperty) { - getTemplateHelper().putInContext("property", identifierProperty); - getTemplateHelper().processTemplate("hbm/id.hbm.ftl", writer); - } - - public void endIdentifierProperty(Property identifierProperty) { - getTemplateHelper().removeFromContext("property", identifierProperty); - } - - public void startEmbeddedIdentifier(Component identifierProperty) { - getTemplateHelper().putInContext("embeddedid", identifierProperty); - getTemplateHelper().processTemplate("hbm/id.hbm.ftl", writer); - } - - public void endEmbeddedIdentifier(Component identifierProperty) { - getTemplateHelper().removeFromContext("embeddedid", identifierProperty); - } - - public boolean startProperty(Property prop) { - getTemplateHelper().putInContext("property", prop); - String tag = getCfg2HbmTool().getTag(prop); - getTemplateHelper().processTemplate("hbm/" + tag + ".hbm.ftl", writer); - getTemplateHelper().removeFromContext("property", prop); - return false; - } - - public void endProperty(Property prop) { } - - public boolean startComponent(Component component) throws ExporterException { - return false; // we don't care about components here! - } - - public boolean startGeneralConfiguration(Configuration cfg) throws ExporterException { + private void exportGeneralSettings() { Cfg2HbmTool c2h = getCfg2HbmTool(); - + Configuration cfg = getConfiguration(); if(c2h.isImportData(cfg) && (c2h.isNamedQueries(cfg)) && (c2h.isNamedSQLQueries(cfg)) && (c2h.isFilterDefinitions(cfg))) { - String baseLocPath = globalSettings != null ? globalSettings.getDefaultPackage() != null ? globalSettings.getDefaultPackage() + "." : "" : ""; - try { - File generalFile = getFileForClassName(getOutputDirectory(), baseLocPath + "GeneralHbmSettings", ".hbm.xml"); - if(writer!=null) throw new IllegalStateException("Writer must be null when starting a new hbm output stream!"); - writer = new BufferedWriter(new FileWriter(generalFile)); - getTemplateHelper().processTemplate("hbm/generalhbm.hbm.ftl", writer); - } - catch (IOException e) { - throw new ExporterException("Error while starting on " + cfg, e); - } - return true; - } else { - return false; + TemplateProducer producer = new TemplateProducer(getTemplateHelper(),getArtifactCollector()); + producer.produce(new HashMap(), "generalhbm.hbm.ftl", new File(getOutputDirectory(),"GeneralHbmSettings.hbm.xml"), templateName); } } - public void endGeneralConfiguration(Configuration cfg) throws ExporterException { - try { - writer.flush(); - writer.close(); - writer = null; - } - catch (IOException e) { - throw new ExporterException("Error while processing template", e); - } + public HibernateMappingExporter(Configuration cfg, File outputdir) { + super(cfg, outputdir); + init(); + } + + protected void init() { + setTemplateName("hibernate-mapping.hbm"); + setFilePattern("{package-name}/{class-name}.hbm.xml"); + setTemplatePrefix("hbm/"); } - public void finish() throws ExporterException { - // Empty - } + public HibernateMappingExporter() { + init(); + } - public void setGlobalSettings(HibernateMappingGlobalSettings hgs) { - this.globalSettings = hgs; - + protected String getClassNameForFile(POJOClass element) { + return StringHelper.unqualify(((PersistentClass)element.getDecoratedObject()).getEntityName()); } - public void doStart() { - ConfigurationNavigator navigator = new ConfigurationNavigator(); - navigator.export(getConfiguration(), this); + protected String getPackageNameForFile(POJOClass element) { + return StringHelper.qualifier(((PersistentClass)element.getDecoratedObject()).getClassName()); } - - protected void setupContext() { - super.setupContext(); - getTemplateHelper().putInContext("hmgs", globalSettings); + + + protected void exportComponent(Map additionalContext, POJOClass element) { + // we don't want component's exported. } public String getName() { - return "cfg2hbm"; + return "hbm2hbmxml"; } } Index: TemplateProducer.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/TemplateProducer.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -d -r1.2 -r1.3 --- TemplateProducer.java 6 Feb 2006 09:08:08 -0000 1.2 +++ TemplateProducer.java 7 Feb 2006 14:02:15 -0000 1.3 @@ -25,10 +25,8 @@ void produce(Map additionalContext, String templateName, File destination, String identifier, String fileType) { - String tempResult = firstPass( additionalContext, templateName ); + String tempResult = produceToString( additionalContext, templateName ); - /*secondPass( additionalContext, destination, identifier, fileType, tempResult );*/ - if(tempResult.trim().length()==0) { log.warn("Generated output is empty. Skipped creation for file " + destination); return; @@ -40,7 +38,6 @@ ac.addFile(destination, fileType); log.info("Writing " + identifier + " to " + destination.getAbsolutePath() ); - // Second run - writes to file (allows for placing imports correctly and optimized ;) fileWriter = new FileWriter(destination); fileWriter.write(tempResult); } @@ -57,48 +54,12 @@ } } } - - } - private void secondPass(Map additionalContext, File destination, String identifier, String fileType, String tempResult) { - if(tempResult.trim().length()==0) { - log.warn("Generated output is empty. Skipped creation for file " + destination); - return; - } - FileWriter fileWriter = null; - try { - Map spctx = getContextForSecondPass(additionalContext); - putInContext(th, spctx); - - th.ensureExistence( destination ); - - ac.addFile(destination, fileType); - log.info("Writing " + identifier + " to " + destination.getAbsolutePath() ); - // Second run - writes to file (allows for placing imports correctly and optimized ;) - fileWriter = new FileWriter(destination); - th.processString(tempResult, fileWriter); - removeFromContext(th, spctx); - } - catch (Exception e) { - throw new ExporterException("Error while processing template the second time", e); - } finally { - if(fileWriter!=null) { - try { - fileWriter.flush(); - fileWriter.close(); - } - catch (IOException e) { - log.warn("Exception while flushing/closing " + destination,e); - } - } - } - } - - private String firstPass(Map additionalContext, String templateName) { - Map contextForFirstPass = getContextForFirstPass(additionalContext); + private String produceToString(Map additionalContext, String templateName) { + Map contextForFirstPass = additionalContext; putInContext( th, contextForFirstPass ); StringWriter tempWriter = new StringWriter(); BufferedWriter bw = new BufferedWriter(tempWriter); @@ -129,18 +90,10 @@ th.putInContext((String) element.getKey(), element.getValue()); } } - - protected Map getContextForSecondPass(Map additionalContext) { - return additionalContext; - } - - protected Map getContextForFirstPass(Map additionalContext) { - return additionalContext; - } public void produce(Map additionalContext, String templateName, File outputFile, String identifier) { - String filename = outputFile.getName(); - filename = filename.substring(filename.indexOf('.')+1); - produce(additionalContext, templateName, outputFile, identifier, filename); + String fileType = outputFile.getName(); + fileType = fileType.substring(fileType.indexOf('.')+1); + produce(additionalContext, templateName, outputFile, identifier, fileType); } } Index: HibernateConfigurationExporter.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java,v retrieving revision 1.19 retrieving revision 1.20 diff -u -d -r1.19 -r1.20 --- HibernateConfigurationExporter.java 3 Oct 2005 16:00:58 -0000 1.19 +++ HibernateConfigurationExporter.java 7 Feb 2006 14:02:15 -0000 1.20 @@ -120,15 +120,6 @@ } } - if(file!=null) { - try { - XMLPrettyPrinter.prettyPrintFile(XMLPrettyPrinter.getDefaultTidy(), file, file); - } - catch (IOException e) { - throw new ExporterException("Problems while creating hibernate.cfg.xml", e); - } - } - } /** Index: GenericExporter.java =================================================================== RCS file: /cvsroot/hibernate/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/GenericExporter.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -d -r1.8 -r1.9 --- GenericExporter.java 6 Feb 2006 09:08:08 -0000 1.8 +++ GenericExporter.java 7 Feb 2006 14:02:15 -0000 1.9 @@ -37,9 +37,10 @@ public void start() { if(exporterClassName!=null) { + Exporter exporter = null; try { Class exporterClass = ReflectHelper.classForName(exporterClassName); - Exporter exporter = (Exporter) exporterClass.newInstance(); + exporter = (Exporter) exporterClass.newInstance(); Properties p = getProperties(); if(getTemplateName()!=null) p.put(ExporterSettings.PREFIX_KEY + "template_name", getTemplateName()); if(filePattern!=null) p.put(ExporterSettings.PREFIX_KEY + "file_pattern", filePattern); @@ -47,13 +48,13 @@ exporter.setArtifactCollector(getArtifactCollector()); exporter.setConfiguration(getConfiguration()); exporter.setOutputDirectory(getOutputDirectory()); - exporter.setTemplatePath(getTemplatePaths()); - - exporter.start(); + exporter.setTemplatePath(getTemplatePaths()); } catch (Exception e) { - throw new ExporterException("Could not instantiate exporter of class " + exporterClassName,e); + throw new ExporterException("Could not instantiate/configure exporter of class " + exporterClassName,e); } + + exporter.start(); } else { super.start(); } @@ -101,20 +102,19 @@ } protected void exportPOJO(Map additionalContext, POJOClass element) { - TemplateProducer producer = new ImportProducer(getTemplateHelper(),getArtifactCollector(),element); + TemplateProducer producer = new TemplateProducer(getTemplateHelper(),getArtifactCollector()); additionalContext.put("pojo", element); additionalContext.put("clazz", element.getDecoratedObject()); - additionalContext.put("secondclassimports", "$secondpassclassimports"); String filename = resolveFilename( element ); - if(filename.indexOf('$')>=0) { - log.warn("Filename for " + element.getDeclarationName() + " contains a $. Innerclass generation is not supported."); + if(filename.endsWith(".java") && filename.indexOf('$')>=0) { + log.warn("Filename for " + getClassNameForFile( element ) + " contains a $. Innerclass generation is not supported."); } producer.produce(additionalContext, getTemplateName(), new File(getOutputDirectory(),filename), templateName); } - private String resolveFilename(POJOClass element) { - String filename = StringHelper.replace(filePattern, "{class-name}", element.getDeclarationName()); - String packageLocation = StringHelper.replace(element.getPackageName(),".", "/"); + protected String resolveFilename(POJOClass element) { + String filename = StringHelper.replace(filePattern, "{class-name}", getClassNameForFile( element )); + String packageLocation = StringHelper.replace(getPackageNameForFile( element ),".", "/"); if(StringHelper.isEmpty(packageLocation)) { packageLocation = "."; // done to ensure default package classes doesn't end up in the root of the filesystem when outputdir="" } @@ -122,6 +122,14 @@ return filename; } + protected String getPackageNameForFile(POJOClass element) { + return element.getPackageName(); + } + + protected String getClassNameForFile(POJOClass element) { + return element.getDeclarationName(); + } + public void setFilePattern(String filePattern) { this.filePattern = filePattern; } --- ImportProducer.java DELETED --- --- FreeMarkerTemplateHelper.java DELETED --- |