View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.site;
21  
22  import java.io.IOException;
23  import java.nio.file.Files;
24  import java.nio.file.Path;
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.List;
28  import java.util.Locale;
29  import java.util.regex.Pattern;
30  import java.util.stream.Collectors;
31  
32  import org.apache.maven.doxia.macro.AbstractMacro;
33  import org.apache.maven.doxia.macro.Macro;
34  import org.apache.maven.doxia.macro.MacroExecutionException;
35  import org.apache.maven.doxia.macro.MacroRequest;
36  import org.apache.maven.doxia.sink.Sink;
37  import org.codehaus.plexus.component.annotations.Component;
38  
39  /**
40   * A macro that inserts a snippet of code or configuration from a file.
41   */
42  @Component(role = Macro.class, hint = "example")
43  public class ExampleMacro extends AbstractMacro {
44  
45      /** Starting delimiter for config snippets. */
46      private static final String XML_CONFIG_START = "/*xml";
47  
48      /** Ending delimiter for config snippets. */
49      private static final String XML_CONFIG_END = "*/";
50  
51      /** Starting delimiter for code snippets. */
52      private static final String CODE_SNIPPET_START = "// xdoc section -- start";
53  
54      /** Ending delimiter for code snippets. */
55      private static final String CODE_SNIPPET_END = "// xdoc section -- end";
56  
57      /** The pattern of xml code blocks. */
58      private static final Pattern XML_PATTERN = Pattern.compile(
59              "^\\s*(<!DOCTYPE\\s+.*?>|<\\?xml\\s+.*?>|<module\\s+.*?>)\\s*",
60              Pattern.DOTALL
61      );
62  
63      /** The path of the last file. */
64      private String lastPath = "";
65  
66      /** The line contents of the last file. */
67      private List<String> lastLines = new ArrayList<>();
68  
69      @Override
70      public void execute(Sink sink, MacroRequest request) throws MacroExecutionException {
71          final String path = (String) request.getParameter("path");
72          final String type = (String) request.getParameter("type");
73  
74          List<String> lines = lastLines;
75          if (!path.equals(lastPath)) {
76              lines = readFile("src/xdocs-examples/" + path);
77              lastPath = path;
78              lastLines = lines;
79          }
80  
81          if ("config".equals(type)) {
82              final String config = getConfigSnippet(lines);
83  
84              if (config.isBlank()) {
85                  final String message = String.format(Locale.ROOT,
86                          "Empty config snippet from %s, check"
87                                  + " for xml config snippet delimiters in input file.", path
88                  );
89                  throw new MacroExecutionException(message);
90              }
91  
92              writeSnippet(sink, config);
93          }
94          else if ("code".equals(type)) {
95              String code = getCodeSnippet(lines);
96              // Replace tabs with spaces for FileTabCharacterCheck examples
97              if (path.contains("filetabcharacter")) {
98                  code = code.replace("\t", "  ");
99              }
100 
101             if (code.isBlank()) {
102                 final String message = String.format(Locale.ROOT,
103                         "Empty code snippet from %s, check"
104                                 + " for code snippet delimiters in input file.", path
105                 );
106                 throw new MacroExecutionException(message);
107             }
108 
109             writeSnippet(sink, code);
110         }
111         else if ("raw".equals(type)) {
112             final String content = String.join(ModuleJavadocParsingUtil.NEWLINE, lines);
113             writeSnippet(sink, content);
114         }
115         else {
116             final String message = String.format(Locale.ROOT, "Unknown example type: %s", type);
117             throw new MacroExecutionException(message);
118         }
119     }
120 
121     /**
122      * Read the file at the given path and returns its contents as a list of lines.
123      *
124      * @param path the path to the file to read.
125      * @return the contents of the file as a list of lines.
126      * @throws MacroExecutionException if the file could not be read.
127      */
128     private static List<String> readFile(String path) throws MacroExecutionException {
129         try {
130             final Path exampleFilePath = Path.of(path);
131             return Files.readAllLines(exampleFilePath);
132         }
133         catch (IOException ioException) {
134             final String message = String.format(Locale.ROOT, "Failed to read %s", path);
135             throw new MacroExecutionException(message, ioException);
136         }
137     }
138 
139     /**
140      * Extract a configuration snippet from the given lines. Config delimiters use the whole
141      * line for themselves and have no indentation. We use equals() instead of contains()
142      * to be more strict because some examples contain those delimiters. If the delimiters
143      * are not found, returns the entire file content.
144      *
145      * @param lines the lines to extract the snippet from.
146      * @return the configuration snippet.
147      */
148     private static String getConfigSnippet(Collection<String> lines) {
149         final String snippet = lines.stream()
150                 .dropWhile(line -> !XML_CONFIG_START.equals(line))
151                 .skip(1)
152                 .takeWhile(line -> !XML_CONFIG_END.equals(line))
153                 .collect(Collectors.joining(ModuleJavadocParsingUtil.NEWLINE));
154 
155         // If no snippet was found (markers not present), return the entire file content
156         final String result;
157         if (snippet.isBlank()) {
158             result = String.join(ModuleJavadocParsingUtil.NEWLINE, lines);
159         }
160         else {
161             result = snippet;
162         }
163 
164         return result;
165     }
166 
167     /**
168      * Extract a code snippet from the given lines. Code delimiters can be indented, so
169      * we use contains() instead of equals(). If the delimiters are not found, returns
170      * the file content excluding the XML config block (if present).
171      *
172      * @param lines the lines to extract the snippet from.
173      * @return the code snippet.
174      */
175     private static String getCodeSnippet(Collection<String> lines) {
176         final String snippet = lines.stream()
177                 .dropWhile(line -> !line.contains(CODE_SNIPPET_START))
178                 .skip(1)
179                 .takeWhile(line -> !line.contains(CODE_SNIPPET_END))
180                 .collect(Collectors.joining(ModuleJavadocParsingUtil.NEWLINE));
181 
182         // If no snippet was found (markers not present), return the file content
183         // excluding the XML config block (if present)
184         final String result;
185         if (snippet.isBlank()) {
186             final List<String> linesList = new ArrayList<>(lines);
187             final int configEndIndex = linesList.indexOf(XML_CONFIG_END);
188             if (configEndIndex >= 0) {
189                 // XML config block is present, return content after it
190                 result = String.join(ModuleJavadocParsingUtil.NEWLINE,
191                         linesList.stream()
192                                 .skip(configEndIndex + 1)
193                                 .toList());
194             }
195             else {
196                 // No XML config block, return entire file
197                 result = String.join(ModuleJavadocParsingUtil.NEWLINE, linesList);
198             }
199         }
200         else {
201             result = snippet;
202         }
203 
204         return result;
205     }
206 
207     /**
208      * Writes the given snippet inside a formatted source block.
209      *
210      * @param sink the sink to write to.
211      * @param snippet the snippet to write.
212      */
213     private static void writeSnippet(Sink sink, String snippet) {
214         sink.rawText("<div class=\"wrapper\">");
215         final boolean isXml = isXml(snippet);
216 
217         final String languageClass;
218         if (isXml) {
219             languageClass = "language-xml";
220         }
221         else {
222             languageClass = "language-java";
223         }
224         sink.rawText("<pre class=\"prettyprint\"><code class=\"" + languageClass + "\">"
225             + ModuleJavadocParsingUtil.NEWLINE);
226         sink.rawText(escapeHtml(snippet).trim() + ModuleJavadocParsingUtil.NEWLINE);
227         sink.rawText("</code></pre>");
228         sink.rawText("</div>");
229     }
230 
231     /**
232      * Escapes HTML special characters in the snippet.
233      *
234      * @param snippet the snippet to escape.
235      * @return the escaped snippet.
236      */
237     private static String escapeHtml(String snippet) {
238         return snippet.replace("&", "&amp;")
239                 .replace("<", "&lt;")
240                 .replace(">", "&gt;");
241     }
242 
243     /**
244      * Determines if the given snippet is likely an XML fragment.
245      *
246      * @param snippet the code snippet to analyze.
247      * @return {@code true} if the snippet appears to be XML, otherwise {@code false}.
248      */
249     private static boolean isXml(String snippet) {
250         return XML_PATTERN.matcher(snippet.trim()).matches();
251     }
252 }