Author: tchemit Date: 2012-07-02 14:49:19 +0200 (Mon, 02 Jul 2012) New Revision: 732 Url: http://nuiton.org/repositories/revision/jrst/732 Log: refs #2139: Improve RST generation mecanism (rewrite pdf generation from maven site) Modified: trunk/jrst-site-util/src/main/java/org/nuiton/jrst/AbstractJrstParser.java trunk/jrst-site-util/src/main/java/org/nuiton/jrst/JrstSiteRenderer.java Modified: trunk/jrst-site-util/src/main/java/org/nuiton/jrst/AbstractJrstParser.java =================================================================== --- trunk/jrst-site-util/src/main/java/org/nuiton/jrst/AbstractJrstParser.java 2012-07-02 10:18:35 UTC (rev 731) +++ trunk/jrst-site-util/src/main/java/org/nuiton/jrst/AbstractJrstParser.java 2012-07-02 12:49:19 UTC (rev 732) @@ -106,19 +106,20 @@ mavenProject.getBasedir(), "target" + File.separator + "generated-jrst"); - sourceFile = new File(temporayDirectory, renderingContext.getInputName()); + sourceFile = new File(temporayDirectory, + renderingContext.getInputName()); FileUtil.createDirectoryIfNecessary(sourceFile.getParentFile()); - -// // Write the source in a file to use it with JRST -// sourceFile = File.createTempFile(renderingContext.getInputName(), ".rst", -// temporayDirectory); } if (verbose) { - log.info("Copy " + renderingContext.getInputName() + - " to " + sourceFile); + log.info("Transform rst file: " + sourceFile); + if (log.isDebugEnabled()) { + log.info("Copy " + renderingContext.getInputName() + + " to " + sourceFile); + } } + FileWriter fileWriter = new FileWriter(sourceFile); try { IOUtil.copy(source, fileWriter); Modified: trunk/jrst-site-util/src/main/java/org/nuiton/jrst/JrstSiteRenderer.java =================================================================== --- trunk/jrst-site-util/src/main/java/org/nuiton/jrst/JrstSiteRenderer.java 2012-07-02 10:18:35 UTC (rev 731) +++ trunk/jrst-site-util/src/main/java/org/nuiton/jrst/JrstSiteRenderer.java 2012-07-02 12:49:19 UTC (rev 732) @@ -23,11 +23,12 @@ */ package org.nuiton.jrst; +import com.google.common.collect.Maps; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.maven.doxia.parser.Parser; import org.apache.maven.doxia.sink.render.RenderingContext; -import org.apache.maven.doxia.site.decoration.DecorationModel; import org.apache.maven.doxia.site.decoration.Menu; import org.apache.maven.doxia.site.decoration.MenuItem; import org.apache.maven.doxia.siterenderer.DefaultSiteRenderer; @@ -54,7 +55,6 @@ import java.lang.reflect.Field; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; @@ -83,8 +83,6 @@ protected boolean pdfGenerationEnabled; - protected Map<String, String> map; - protected boolean verbose; @Requirement(role = Parser.class, hint = "jrst", optional = true) @@ -109,37 +107,45 @@ verbose = getBooleanProperty("site.verbose") || getLogger().isDebugEnabled(); - map = new HashMap<String, String>(); - pdfGenerationEnabled = getBooleanProperty("pdfGenerationEnabled"); super.render(documents, siteRenderingContext, outputDirectory); if (pdfGenerationEnabled) { - if (verbose) { - getLogger().info("Will generate the site pdf."); - } + // Get relative paths of documents from menu definition (from site.xml model) + List<String> relativPathsFromMenu = + getDocumentRelativePathsFromMenu(siteRenderingContext); - // get pdfFilename - String pdfFilename = getStringProperty("pdfFilename"); - if (StringUtils.isBlank(pdfFilename)) { - pdfFilename = DEFAULT_PDF_FILENAME; - } + // Get relatifs map of all documents + Map<String, String> relatifPaths = buildDocMap(documents); - if (!locales.isEmpty() && !locale.equals(locales.get(0))) { - // not default locale, prefix with locale country. - pdfFilename += "_" + locale.getCountry(); + // merge to have documents refs (to be used in pdf template) + List<String> documentRefs = getDocumentRefs(relatifPaths, + relativPathsFromMenu); + + if (CollectionUtils.isEmpty(documentRefs)) { + // no docuemnts to render, skip pdf generation + + if (getLogger().isInfoEnabled()) { + getLogger().info("No document to put in pdf, skip pdf generation."); + } + } else { + String pdfFilename = getPdfFileName(); + + try { + Field i18nField = ReflectUtil.getField(DefaultSiteRenderer.class, "i18n"); + I18N i18n = (I18N) i18nField.get(this); + + renderPdf(i18n, documentRefs, + siteRenderingContext, + outputDirectory, + pdfFilename); + } catch (Exception e) { + getLogger().error("Can't find rst resource to generate pdf documentation", e); + } } - pdfFilename += ".pdf"; - try { - renderPdf(documents, siteRenderingContext, - outputDirectory, - pdfFilename); - } catch (Exception e) { - getLogger().error("Can't find rst resource to generate pdf documentation", e); - } } } @@ -161,127 +167,154 @@ super.renderDocument(writer, renderingContext, context); } - public void renderPdf(Collection<DocumentRenderer> documents, - SiteRenderingContext siteRenderingContext, - File outputDirectory, String pdfFilename) + protected String getPdfFileName() { + // get pdfFilename + String pdfFilename = getStringProperty("pdfFilename"); + if (StringUtils.isBlank(pdfFilename)) { + pdfFilename = DEFAULT_PDF_FILENAME; + } + + if (!locales.isEmpty() && !locale.equals(locales.get(0))) { + // not default locale, prefix with locale country. + pdfFilename += "_" + locale.getCountry(); + } + pdfFilename += ".pdf"; + return pdfFilename; + } + + protected void renderPdf(I18N i18n, + List<String> documentRefs, + SiteRenderingContext siteRenderingContext, + File outputDirectory, + String pdfFilename) throws RendererException, FileNotFoundException, UnsupportedEncodingException { - Context vc = new VelocityContext(); - if (getLogger().isInfoEnabled()) { - getLogger().info("Generate Site Pdf: " + pdfFilename); + if (getLogger().isDebugEnabled()) { + getLogger().debug("Generate Site Pdf: " + pdfFilename); } - vc.put("locale", locale); - vc.put("supportedLocales", locales); + Context vc = preparePdfVelocityContext(i18n, documentRefs); + + // Define the output file + File fileOut = new File(outputDirectory, pdfFilename); + if (verbose) { + getLogger().info("Will generate the site pdf: " + fileOut); + } + try { StringWriter sw = new StringWriter(); - Field velocityField = ReflectUtil.getField(DefaultSiteRenderer.class, "velocity"); + Field velocityField = + ReflectUtil.getField(DefaultSiteRenderer.class, "velocity"); VelocityComponent velocity = (VelocityComponent) velocityField.get(this); VelocityEngine engine = velocity.getEngine(); - Field i18nField = ReflectUtil.getField(DefaultSiteRenderer.class, "i18n"); + String inputEncoding = siteRenderingContext.getInputEncoding(); - I18N i18n = (I18N) i18nField.get(this); + // Aggregate all rst file info one file + //TODO tchemit-2012-06-29 : use a property + engine.mergeTemplate("/META-INF/maven/RstAggregation.vm", inputEncoding, vc, sw); + String fileContent = sw.toString(); + File pdfDoc = new File(outputDirectory, "pdfDoc.rst"); + FileUtils.writeStringToFile(pdfDoc, fileContent, inputEncoding); - String inputEncoding = siteRenderingContext.getInputEncoding(); - // Set velocity variables - String tableOfContent = i18n.getString("jrst-site-renderer", locale, "content"); - String docName = mavenProject.getName(); - String titleDecoration = StringUtils.rightPad("", docName.length(), '='); - vc.put("titleDecoration", titleDecoration); - vc.put("docName", docName); - vc.put("tableContentName", tableOfContent); + Document doc = jrstParser.getStrategy().generateRstToXml( + fileOut, inputEncoding); - // Build the map of html documents from .rst or .rst.vm files - File basedir = buildDocMap(documents); - vc.put("basedir", basedir.getAbsolutePath()); - vc.put("separator", File.separatorChar); + // Generate the pdf file + JRST.generatePdf(pdfDoc, fileOut, JRST.Overwrite.ALLTIME, doc); - // Build the list of item's href - DecorationModel decoration = siteRenderingContext.getDecoration(); - List<Menu> menus = decoration.getMenus(); - Collection<String> paths = new LinkedList<String>(); - for (Menu menu : menus) { - List<MenuItem> items = menu.getItems(); - for (MenuItem item : items) { - buildListPaths(item, paths, siteRenderingContext); - } - } + } catch (Exception e) { + getLogger().error("Can't generate pdf documentation of the project at " + fileOut, e); + } + } - // Merge of the map of html file and the list of paths - List<String> documentRefs = mergeListAndMap(paths); - if (documentRefs.size() > 0) { - vc.put("documentRefs", documentRefs); + protected Context preparePdfVelocityContext(I18N i18n, + List<String> documentRefs) { - // Aggregate all rst file info one file - //TODO tchemit-2012-06-29 : use a property - engine.mergeTemplate("/META-INF/maven/RstAggregation.vm", inputEncoding, vc, sw); - String fileContent = sw.toString(); - File pdfDoc = new File(outputDirectory, "pdfDoc.rst"); - FileUtils.writeStringToFile(pdfDoc, fileContent, inputEncoding); + Context vc = new VelocityContext(); + vc.put("locale", locale); + vc.put("supportedLocales", locales); + String tableOfContent = i18n.getString("jrst-site-renderer", locale, "content"); + String docName = mavenProject.getName(); + String titleDecoration = StringUtils.rightPad("", docName.length(), '='); + vc.put("titleDecoration", titleDecoration); + vc.put("docName", docName); + vc.put("tableContentName", tableOfContent); - // Define the output file - File fileOut = new File(outputDirectory, pdfFilename); + // Build the map of html documents from .rst or .rst.vm files - Document doc = jrstParser.getStrategy().generateRstToXml( - fileOut, inputEncoding); + vc.put("basedir", mavenProject.getBasedir()); + vc.put("separator", File.separatorChar); + vc.put("documentRefs", documentRefs); + return vc; + } - // Generate the pdf file - JRST.generatePdf(pdfDoc, fileOut, JRST.Overwrite.ALLTIME, doc); + protected List<String> getDocumentRelativePathsFromMenu(SiteRenderingContext siteRenderingContext) { + List<String> paths = new LinkedList<String>(); + for (Menu menu : siteRenderingContext.getDecoration().getMenus()) { + for (MenuItem item : menu.getItems()) { + buildListPathsFromMenuItem(item, paths); } + } + return paths; + } - } catch (Exception e) { - getLogger().error("Can't generate pdf documentation of the project", e); + protected List<String> getDocumentRefs(Map<String, String> relatifPaths, + List<String> relativPathsFromMenu) { + + // Merge the map and the list to obtain a list of rst files we can add in the pdf + List<String> documentRefs = new LinkedList<String>(); + for (String path : relativPathsFromMenu) { + // Seek in the hashmap if the rst file exists to add it in the doc list + String rstFilename = relatifPaths.get(path); + if (rstFilename != null) { + if (verbose) { + getLogger().info("Add document to render in pdf: " + + rstFilename); + } + documentRefs.add(rstFilename); + } } + return documentRefs; } - public File buildDocMap(Collection<DocumentRenderer> documents) { - File basedir = new File("."); + protected Map<String, String> buildDocMap(Collection<DocumentRenderer> documents) { + + Map<String, String> map = Maps.newTreeMap(); + for (DocumentRenderer doc : documents) { RenderingContext renderingContext = doc.getRenderingContext(); String inputName = renderingContext.getInputName(); - String relativeDir = renderingContext.getRelativePath(); +// String relativeDir = renderingContext.getRelativePath(); if (inputName.endsWith("rst") || inputName.endsWith("rst.vm")) { // Change the extension to html String[] splitName = inputName.split("\\."); String htmlName = splitName[0] + "." + "html"; String relativePath = "." + File.separator + htmlName; - if (getLogger().isInfoEnabled()) { - getLogger().info("relativePath: " + relativePath); + if (getLogger().isDebugEnabled()) { + getLogger().debug("relativePath: " + relativePath); } - // Add in a hashmap + // Add in map map.put(relativePath, inputName); - if (relativeDir.equals(".") && inputName.startsWith("index")) { - basedir = renderingContext.getBasedir(); - } + //TODO Why ? +// if (relativeDir.equals(".") && inputName.startsWith("index")) { +// basedir = renderingContext.getBasedir(); +// } } } - return basedir; + return map; } - public List<String> mergeListAndMap(Collection<String> paths) { - // Merge the map and the list to obtain a list of rst files we can add in the pdf - List<String> documentRefs = new LinkedList<String>(); - for (String path : paths) { - // Seek in the hashmap if the rst file exists to add it in the doc list - String rstFilename = map.get(path); - if (rstFilename != null) { - documentRefs.add(rstFilename); - } - } - return documentRefs; - } - - public Collection<String> buildListPaths(MenuItem item, Collection<String> paths, - SiteRenderingContext siteRenderingContext) { + protected Collection<String> buildListPathsFromMenuItem(MenuItem item, + Collection<String> paths) { // add hrefs to paths if they don't start with "http" or ".." String href = item.getHref(); if (!href.startsWith("http") && !href.startsWith("..")) { boolean addHref = true; - for (Locale loc : siteRenderingContext.getSiteLocales()) { + for (Locale loc : locales) { if (href.startsWith(loc.toString())) { addHref = false; } @@ -290,8 +323,8 @@ if (!href.startsWith("./")) { href = "./" + href; } - if (getLogger().isInfoEnabled()) { - getLogger().info("xml: " + href); + if (getLogger().isDebugEnabled()) { + getLogger().debug("document to render in pdf: " + href); } paths.add(href); } @@ -300,15 +333,16 @@ List<MenuItem> subItems = item.getItems(); if (!subItems.isEmpty()) { for (MenuItem subItem : subItems) { - paths = buildListPaths(subItem, paths, siteRenderingContext); + paths = buildListPathsFromMenuItem(subItem, paths); } } return paths; } protected String getStringProperty(String propertyName) { - String value = String.valueOf(mavenProject.getModel().getProperties().get(propertyName)); - return value; + Object value = mavenProject.getProperties().get(propertyName); + String result = value == null ? null : String.valueOf(value); + return result; } protected boolean getBooleanProperty(String propertyName) {