/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.sis.internal.book;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;import java.io.File;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;// Share a convenience method.import static org.apache.sis.internal.book.CodeColorizer.toArray;/** * Generates the developer guide from the given input file. * This class performs the following processing: * * * * See package javadoc for usage example. * * @author Martin Desruisseaux (Geomatys) * @version 1.3 * @since 0.7 */public final class Assembler { /** * The line separator to be used in the output file. * We fix it to the Unix style (not the native style of the platform) for more compact output file. */ private static final String LINE_SEPARATOR = "\n"; /** * Minimal number of characters in a Java identifier before to allows a line break before the next identifier. * This value if used in expressions like {@code foo.bar()} for deciding whether or not we accept line break * between {@code foo} and {@code .bar()}. */ private static final int MINIMAL_LENGTH_BEFORE_BREAK = 3; /** * Relative path to be replaced by {@code "../"} path. We perform this substitution because the source files * defined in the {@code content/developer-guide/} directories reference directly the images in their * final {@code static/book/images} directory. */ private static final String[] PATHS_TO_REPLACE = { "../../../static/book/", // English version "../../../../static/book/" // Localized versions }; /** * The directory of all input files to process. */ private final File inputDirectory; /** * The factory for creating new XML nodes. */ private final DocumentBuilder builder; /** * The XML document to write. This is initially the XML document parsed from the given input file. * Then all included files are inserted in-place and some nodes are processed as documented in the * class javadoc. */ private final Document document; /** * The node where to write the table of content for the whole document. */ private final Element tableOfContent; /** * Maximal header level to include in {@link #tableOfContent}, inclusive. */ private static final int MAX_TOC_LEVEL = 3; /** * The {@code title} attributes found in abbreviations. */ private final Map abbreviations = new HashMap<>(); /** * Whether we found an abbreviation after the last {@code h?} element. * This is used in order to avoid inserting too many abbreviation title. */ private final Set writtenAbbreviations = new HashSet<>(); /** * Section numbers, incremented when a new {@code

}, {@code

}, etc. element is found. */ private final int[] sectionNumbering = new int[9]; /** * Helper class for applying colors on content of {@code } and {@code } elements. */ private final CodeColorizer colorizer; /** * Creates a new assembler for the given input and output files. * * @param input the input file (e.g. {@code "sis-site/main/content/developer-guide/index.html"}). * @throws ParserConfigurationException if this constructor cannot build the XML document. * @throws IOException if an error occurred while reading the file. * @throws SAXException if an error occurred while parsing the XML. * @throws BookException if a logical error occurred while initializing the assembler. */ public Assembler(final File input) throws ParserConfigurationException, IOException, SAXException, BookException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // No setXIncludeAware(true) - we will handle elements ourself. factory.setNamespaceAware(true); inputDirectory = input.getParentFile(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// builder = factory.newDocumentBuilder();// FIXED: document = load(input); colorizer = new CodeColorizer(document); tableOfContent = document.createElement("ul"); /* * Remove the "http://www.w3.org/2001/XInclude" namespace since we * should have no elements left in the output file. */ ((Element) document.getElementsByTagName("html").item(0)).removeAttribute("xmlns:xi"); /* * Replace the License comment by a shorter one followed by the * "This is an automatically generated file"> notice. */ for (final Node node : toArray(document.getDocumentElement().getParentNode().getChildNodes())) { if (node.getNodeType() == Node.COMMENT_NODE) { node.setNodeValue(LINE_SEPARATOR + LINE_SEPARATOR + " Licensed to the Apache Software Foundation (ASF)" + LINE_SEPARATOR + LINE_SEPARATOR + " http://www.apache.org/licenses/LICENSE-2.0" + LINE_SEPARATOR + LINE_SEPARATOR + " This is an automatically generated file. DO NOT EDIT." + LINE_SEPARATOR + " See the files in the `content/developer-guide` directory instead." + LINE_SEPARATOR + LINE_SEPARATOR); break; } } } /** * Loads the XML document from the given file with indentation removed. */ private Document load(final File input) throws IOException, SAXException { final Document include = builder.parse(input); builder.reset(); removeIndentation(include.getDocumentElement()); return include; } /** * Removes the indentation at the beginning of lines in the given node and all child nodes. * This can reduce the file length by as much as 20%. Note that the indentation was broken * anyway after the treatment of {@code }, because included file does not use * the right amount of spaces for the location where it is introduced. */ private void removeIndentation(final Node node) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: { if ("pre".equals(node.getNodeName())) { return; } break; } case Node.TEXT_NODE: { boolean newLine = false; StringBuilder buffer = null; CharSequence text = node.getTextContent(); for (int i=0; i} element. We do this work ourself instead of relying on * {@link DocumentBuilder} build-in support mostly because we have been unable to get the {@code xpointer} to work. * * @param input the source XML file. * @param toReplace the target XML node to be replaced by the content of the given file. */ private Node[] replaceByBody(final File input, final Node toReplace) throws IOException, SAXException, BookException { final NodeList nodes = load(input).getElementsByTagName("body"); if (nodes.getLength() != 1) { throw new BookException(input.getName() + ": expected exactly one element."); } final Node parent = toReplace.getParentNode(); parent.removeChild(toReplace); Node[] childNodes = toArray(nodes.item(0).getChildNodes()); for (int i=0; i} * or {@code } attribute value. */ private static void adjustURL(final Element element) { for (final String prefix : PATHS_TO_REPLACE) { if (adjustURL(element, prefix)) break; } } /** * Adjusts the relative path in {@code } * or {@code } attribute value. * * @param element the element to adjust. * @param prefix the path prefix to search and replace. * @return whether replacement has been done. */ private static boolean adjustURL(final Element element, final String prefix) { String attribute; String href = element.getAttribute(attribute = "href"); if (href == null || !href.startsWith(prefix)) { href = element.getAttribute(attribute = "src"); if (href == null || !href.startsWith(prefix)) { return false; } } element.setAttribute(attribute, "../" + href.substring(prefix.length())); return true; } /** * Automatically inserts a {@code title} attribute in the given {@code } element * if it meets the condition documented in the class javadoc. */ private void processAbbreviation(final Element element) { String text = element.getTextContent(); String title = element.getAttribute("title"); if (!title.isEmpty()) { abbreviations.put(text, title); } if (writtenAbbreviations.add(text) && title.isEmpty()) { title = abbreviations.get(text); if (title != null) { element.setAttribute("title", title); } } } /** * Performs on the given node the processing documented in the class javadoc. * This method invokes itself recursively. * * @param directory the directory of the file being processed. Used for resolving relative links. * @param index {@code true} for including the {@code

}, etc. texts in the Table Of Content (TOC). * This is set to {@code false} when parsing the content of {@code