Debian Codegraph @

jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java

raw
1 //
2 // ========================================================================
3 // Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.jspc.plugin;
20
21 import java.io.BufferedReader;
22 import java.io.File;
23 import java.io.FileFilter;
24 import java.io.FileReader;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.PrintWriter;
28 import java.net.MalformedURLException;
29 import java.net.URL;
30 import java.net.URLClassLoader;
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Set;
37
38 import org.apache.jasper.JspC;
39 import org.apache.jasper.servlet.JspCServletContext;
40 import org.apache.jasper.servlet.TldScanner;
41 import org.apache.maven.artifact.Artifact;
42 import org.apache.maven.plugin.AbstractMojo;
43 import org.apache.maven.plugin.MojoExecutionException;
44 import org.apache.maven.plugin.MojoFailureException;
45 import org.apache.maven.plugins.annotations.LifecyclePhase;
46 import org.apache.maven.plugins.annotations.Mojo;
47 import org.apache.maven.plugins.annotations.Parameter;
48 import org.apache.maven.plugins.annotations.ResolutionScope;
49 import org.apache.maven.project.MavenProject;
50 import org.apache.tomcat.JarScanner;
51 import org.apache.tomcat.util.scan.StandardJarScanner;
52 import org.codehaus.plexus.util.FileUtils;
53 import org.codehaus.plexus.util.StringUtils;
54 import org.eclipse.jetty.util.IO;
55 import org.eclipse.jetty.util.resource.Resource;
56
57 /**
58 * This goal will compile jsps for a webapp so that they can be included in a
59 * war.
60 * <p>
61 * At runtime, the plugin will use the jspc compiler to precompile jsps and tags.
62 * </p>
63 * <p>
64 * Note that the same java compiler will be used as for on-the-fly compiled
65 * jsps, which will be the Eclipse java compiler.
66 * <p>
67 * See <a
68 * href="https://jetty.org/docs/9/jetty-jspc-maven-plugin.html">Usage
69 * Guide</a> for instructions on using this plugin.
70 * </p>
71 * Runs jspc compiler to produce .java and .class files
72 */
73 @Mojo(name = "jspc", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
74 public class JspcMojo extends AbstractMojo
75 {
76 public static final String END_OF_WEBAPP = "</web-app>";
77 public static final String PRECOMPILED_FLAG = "org.eclipse.jetty.jsp.precompiled";
78
79 /**
80 * JettyJspC
81 *
82 * Add some extra setters to standard JspC class to help configure it
83 * for running in maven.
84 *
85 * TODO move all setters on the plugin onto this jspc class instead.
86 */
87 public static class JettyJspC extends JspC
88 {
89
90 private boolean scanAll;
91
92 public void setClassLoader(ClassLoader loader)
93 {
94 this.loader = loader;
95 }
96
97 public void setScanAllDirectories(boolean scanAll)
98 {
99 this.scanAll = scanAll;
100 }
101
102 public boolean getScanAllDirectories()
103 {
104 return this.scanAll;
105 }
106
107 @Override
108 protected TldScanner newTldScanner(JspCServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal)
109 {
110 if (context != null && context.getAttribute(JarScanner.class.getName()) == null)
111 {
112 StandardJarScanner jarScanner = new StandardJarScanner();
113 jarScanner.setScanAllDirectories(getScanAllDirectories());
114 context.setAttribute(JarScanner.class.getName(), jarScanner);
115 }
116
117 return super.newTldScanner(context, namespaceAware, validate, blockExternal);
118 }
119 }
120
121 /**
122 * Whether or not to include dependencies on the plugin's classpath with &lt;scope&gt;provided&lt;/scope&gt;
123 * Use WITH CAUTION as you may wind up with duplicate jars/classes.
124 *
125 * @since jetty-7.6.3
126 */
127 @Parameter(defaultValue = "false")
128 private boolean useProvidedScope;
129
130 /**
131 * The artifacts for the project.
132 *
133 * @since jetty-7.6.3
134 */
135 @Parameter(defaultValue = "${project.artifacts}", readonly = true)
136 private Set<Artifact> projectArtifacts;
137
138 /**
139 * The maven project.
140 */
141 @Parameter(defaultValue = "${project}", readonly = true, required = true)
142 private MavenProject project;
143
144 /**
145 * The artifacts for the plugin itself.
146 */
147 @Parameter(defaultValue = "${plugin.artifacts}", readonly = true)
148 private List<Artifact> pluginArtifacts;
149
150 /**
151 * File into which to generate the &lt;servlet&gt; and
152 * &lt;servlet-mapping&gt; tags for the compiled jsps
153 */
154 @Parameter(defaultValue = "${basedir}/target/webfrag.xml")
155 private String webXmlFragment;
156
157 /**
158 * Optional. A marker string in the src web.xml file which indicates where
159 * to merge in the generated web.xml fragment. Note that the marker string
160 * will NOT be preserved during the insertion. Can be left blank, in which
161 * case the generated fragment is inserted just before the &lt;/web-app&gt;
162 * line
163 */
164 @Parameter
165 private String insertionMarker;
166
167 /**
168 * Merge the generated fragment file with the web.xml from
169 * webAppSourceDirectory. The merged file will go into the same directory as
170 * the webXmlFragment.
171 */
172 @Parameter(defaultValue = "true")
173 private boolean mergeFragment;
174
175 /**
176 * The destination directory into which to put the compiled jsps.
177 */
178 @Parameter(defaultValue = "${project.build.outputDirectory}")
179 private String generatedClasses;
180
181 /**
182 * Controls whether or not .java files generated during compilation will be
183 * preserved.
184 */
185 @Parameter(defaultValue = "false")
186 private boolean keepSources;
187
188 /**
189 * Root directory for all html/jsp etc files
190 */
191 @Parameter(defaultValue = "${basedir}/src/main/webapp")
192 private String webAppSourceDirectory;
193
194 /**
195 * Location of web.xml. Defaults to src/main/webapp/web.xml.
196 */
197 @Parameter(defaultValue = "${basedir}/src/main/webapp/WEB-INF/web.xml")
198 private String webXml;
199
200 /**
201 * The comma separated list of patterns for file extensions to be processed. By default
202 * will include all .jsp and .jspx files.
203 */
204 @Parameter(defaultValue = "**\\/*.jsp, **\\/*.jspx")
205 private String includes;
206
207 /**
208 * The comma separated list of file name patters to exclude from compilation.
209 */
210 @Parameter(defaultValue = "**\\/.svn\\/**")
211 private String excludes;
212
213 /**
214 * The location of the compiled classes for the webapp
215 */
216 @Parameter(defaultValue = "${project.build.outputDirectory}")
217 private File classesDirectory;
218
219 /**
220 * Patterns of jars on the system path that contain tlds. Use | to separate each pattern.
221 */
222 @Parameter(defaultValue = ".*taglibs[^/]*\\.jar|.*jstl[^/]*\\.jar$")
223 private String tldJarNamePatterns;
224
225 /**
226 * Source version - if not set defaults to jsp default (currently 1.7)
227 */
228 @Parameter
229 private String sourceVersion;
230
231 /**
232 * Target version - if not set defaults to jsp default (currently 1.7)
233 */
234 @Parameter
235 private String targetVersion;
236
237 /**
238 * The JspC instance being used to compile the jsps.
239 */
240 @Parameter
241 private JettyJspC jspc;
242
243 /**
244 * Whether dirs on the classpath should be scanned as well as jars.
245 * True by default. This allows for scanning for tlds of dependent projects that
246 * are in the reactor as unassembled jars.
247 */
248 @Parameter(defaultValue = "true")
249 private boolean scanAllDirectories;
250
251 @Override
252 public void execute() throws MojoExecutionException, MojoFailureException
253 {
254 if (getLog().isDebugEnabled())
255 {
256
257 getLog().info("webAppSourceDirectory=" + webAppSourceDirectory);
258 getLog().info("generatedClasses=" + generatedClasses);
259 getLog().info("webXmlFragment=" + webXmlFragment);
260 getLog().info("webXml=" + webXml);
261 getLog().info("insertionMarker=" + (insertionMarker == null || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker));
262 getLog().info("keepSources=" + keepSources);
263 getLog().info("mergeFragment=" + mergeFragment);
264 if (sourceVersion != null)
265 getLog().info("sourceVersion=" + sourceVersion);
266 if (targetVersion != null)
267 getLog().info("targetVersion=" + targetVersion);
268 }
269 try
270 {
271 prepare();
272 compile();
273 cleanupSrcs();
274 mergeWebXml();
275 }
276 catch (Exception e)
277 {
278 throw new MojoExecutionException("Failure processing jsps", e);
279 }
280 }
281
282 public void compile() throws Exception
283 {
284 ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
285
286 //set up the classpath of the webapp
287 List<URL> webAppUrls = setUpWebAppClassPath();
288
289 //set up the classpath of the container (ie jetty and jsp jars)
290 Set<URL> pluginJars = getPluginJars();
291 Set<URL> providedJars = getProvidedScopeJars(pluginJars);
292
293 //Make a classloader so provided jars will be on the classpath
294 List<URL> sysUrls = new ArrayList<>();
295 sysUrls.addAll(providedJars);
296 URLClassLoader sysClassLoader = new URLClassLoader(sysUrls.toArray(new URL[0]), currentClassLoader);
297
298 //make a classloader with the webapp classpath
299 URLClassLoader webAppClassLoader = new URLClassLoader(webAppUrls.toArray(new URL[0]), sysClassLoader);
300 StringBuilder webAppClassPath = new StringBuilder();
301
302 for (int i = 0; i < webAppUrls.size(); i++)
303 {
304 if (getLog().isDebugEnabled())
305 getLog().debug("webappclassloader contains: " + webAppUrls.get(i));
306 webAppClassPath.append(new File(webAppUrls.get(i).toURI()).getCanonicalPath());
307 if (getLog().isDebugEnabled())
308 getLog().debug("added to classpath: " + (webAppUrls.get(i)).getFile());
309 if (i + 1 < webAppUrls.size())
310 webAppClassPath.append(System.getProperty("path.separator"));
311 }
312
313 //Interpose a fake classloader as the webapp class loader. This is because the Apache JspC class
314 //uses a TldScanner which ignores jars outside of the WEB-INF/lib path on the webapp classloader.
315 //It will, however, look at all jars on the parents of the webapp classloader.
316 URLClassLoader fakeWebAppClassLoader = new URLClassLoader(new URL[0], webAppClassLoader);
317 Thread.currentThread().setContextClassLoader(fakeWebAppClassLoader);
318
319 if (jspc == null)
320 jspc = new JettyJspC();
321
322 jspc.setWebXmlInclude(webXmlFragment);
323 jspc.setUriroot(webAppSourceDirectory);
324 jspc.setOutputDir(generatedClasses);
325 jspc.setClassLoader(fakeWebAppClassLoader);
326 jspc.setScanAllDirectories(scanAllDirectories);
327 jspc.setCompile(true);
328 if (sourceVersion != null)
329 jspc.setCompilerSourceVM(sourceVersion);
330 if (targetVersion != null)
331 jspc.setCompilerTargetVM(targetVersion);
332
333 // JspC#setExtensions() does not exist, so
334 // always set concrete list of files that will be processed.
335 String jspFiles = getJspFiles(webAppSourceDirectory);
336
337 try
338 {
339 if (jspFiles == null | jspFiles.equals(""))
340 {
341 getLog().info("No files selected to precompile");
342 }
343 else
344 {
345 getLog().info("Compiling " + jspFiles + " from includes=" + includes + " excludes=" + excludes);
346 jspc.setJspFiles(jspFiles);
347 jspc.execute();
348 }
349 }
350 finally
351 {
352 Thread.currentThread().setContextClassLoader(currentClassLoader);
353 }
354 }
355
356 private String getJspFiles(String webAppSourceDirectory)
357 throws Exception
358 {
359 List<String> fileNames = FileUtils.getFileNames(new File(webAppSourceDirectory), includes, excludes, false);
360 return StringUtils.join(fileNames.toArray(new String[0]), ",");
361 }
362
363 /**
364 * Until Jasper supports the option to generate the srcs in a different dir
365 * than the classes, this is the best we can do.
366 *
367 * @throws Exception if unable to clean srcs
368 */
369 public void cleanupSrcs() throws Exception
370 {
371 // delete the .java files - depending on keepGenerated setting
372 if (!keepSources)
373 {
374 File generatedClassesDir = new File(generatedClasses);
375
376 if (generatedClassesDir.exists() && generatedClassesDir.isDirectory())
377 {
378 delete(generatedClassesDir, pathname ->
379 {
380 return pathname.isDirectory() || pathname.getName().endsWith(".java");
381 });
382 }
383 }
384 }
385
386 static void delete(File dir, FileFilter filter)
387 {
388 File[] files = dir.listFiles(filter);
389 if (files != null)
390 {
391 for (File f : files)
392 {
393 if (f.isDirectory())
394 delete(f, filter);
395 else
396 f.delete();
397 }
398 }
399 }
400
401 /**
402 * Take the web fragment and put it inside a copy of the web.xml.
403 *
404 * You can specify the insertion point by specifying the string in the
405 * insertionMarker configuration entry.
406 *
407 * If you dont specify the insertionMarker, then the fragment will be
408 * inserted at the end of the file just before the &lt;/webapp&gt;
409 *
410 * @throws Exception if unable to merge the web xml
411 */
412 public void mergeWebXml() throws Exception
413 {
414 if (mergeFragment)
415 {
416 // open the src web.xml
417 File webXml = getWebXmlFile();
418
419 if (!webXml.exists())
420 {
421 getLog().info(webXml.toString() + " does not exist, cannot merge with generated fragment");
422 return;
423 }
424
425 File fragmentWebXml = new File(webXmlFragment);
426 File mergedWebXml = new File(fragmentWebXml.getParentFile(), "web.xml");
427
428 try (BufferedReader webXmlReader = new BufferedReader(new FileReader(webXml));
429 PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(mergedWebXml)))
430 {
431
432 if (!fragmentWebXml.exists())
433 {
434 getLog().info("No fragment web.xml file generated");
435 //just copy existing web.xml to expected position
436 IO.copy(webXmlReader, mergedWebXmlWriter);
437 }
438 else
439 {
440 // read up to the insertion marker or the </webapp> if there is no
441 // marker
442 boolean atInsertPoint = false;
443 boolean atEOF = false;
444 String marker = (insertionMarker == null || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker);
445 while (!atInsertPoint && !atEOF)
446 {
447 String line = webXmlReader.readLine();
448 if (line == null)
449 atEOF = true;
450 else if (line.indexOf(marker) >= 0)
451 {
452 atInsertPoint = true;
453 }
454 else
455 {
456 mergedWebXmlWriter.println(line);
457 }
458 }
459
460 if (atEOF && !atInsertPoint)
461 throw new IllegalStateException("web.xml does not contain insertionMarker " + insertionMarker);
462
463 //put in a context init-param to flag that the contents have been precompiled
464 mergedWebXmlWriter.println("<context-param><param-name>" + PRECOMPILED_FLAG + "</param-name><param-value>true</param-value></context-param>");
465
466 // put in the generated fragment
467 try (BufferedReader fragmentWebXmlReader =
468 new BufferedReader(new FileReader(fragmentWebXml)))
469 {
470 IO.copy(fragmentWebXmlReader, mergedWebXmlWriter);
471
472 // if we inserted just before the </web-app>, put it back in
473 if (marker.equals(END_OF_WEBAPP))
474 mergedWebXmlWriter.println(END_OF_WEBAPP);
475
476 // copy in the rest of the original web.xml file
477 IO.copy(webXmlReader, mergedWebXmlWriter);
478 }
479 }
480 }
481 }
482 }
483
484 private void prepare() throws Exception
485 {
486 // For some reason JspC doesn't like it if the dir doesn't
487 // already exist and refuses to create the web.xml fragment
488 File generatedSourceDirectoryFile = new File(generatedClasses);
489 if (!generatedSourceDirectoryFile.exists())
490 generatedSourceDirectoryFile.mkdirs();
491 }
492
493 /**
494 * Set up the execution classpath for Jasper.
495 *
496 * Put everything in the classesDirectory and all of the dependencies on the
497 * classpath.
498 *
499 * @returns a list of the urls of the dependencies
500 */
501 private List<URL> setUpWebAppClassPath() throws Exception
502 {
503 //add any classes from the webapp
504 List<URL> urls = new ArrayList<URL>();
505 String classesDir = classesDirectory.getCanonicalPath();
506 classesDir = classesDir + (classesDir.endsWith(File.pathSeparator) ? "" : File.separator);
507 urls.add(Resource.toURL(new File(classesDir)));
508
509 if (getLog().isDebugEnabled())
510 getLog().debug("Adding to classpath classes dir: " + classesDir);
511
512 //add the dependencies of the webapp (which will form WEB-INF/lib)
513 for (Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); )
514 {
515 Artifact artifact = iter.next();
516
517 // Include runtime and compile time libraries
518 if (!Artifact.SCOPE_TEST.equals(artifact.getScope()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope()))
519 {
520 String filePath = artifact.getFile().getCanonicalPath();
521 if (getLog().isDebugEnabled())
522 getLog().debug("Adding to classpath dependency file: " + filePath);
523
524 urls.add(Resource.toURL(artifact.getFile()));
525 }
526 }
527 return urls;
528 }
529
530 /**
531 *
532 */
533 private Set<URL> getPluginJars() throws MalformedURLException
534 {
535 HashSet<URL> pluginJars = new HashSet<>();
536 for (Iterator<Artifact> iter = pluginArtifacts.iterator(); iter.hasNext(); )
537 {
538 Artifact pluginArtifact = iter.next();
539 if ("jar".equalsIgnoreCase(pluginArtifact.getType()))
540 {
541 if (getLog().isDebugEnabled())
542 {
543 getLog().debug("Adding plugin artifact " + pluginArtifact);
544 }
545 pluginJars.add(pluginArtifact.getFile().toURI().toURL());
546 }
547 }
548
549 return pluginJars;
550 }
551
552 /**
553 *
554 */
555 private Set<URL> getProvidedScopeJars(Set<URL> pluginJars) throws MalformedURLException
556 {
557 if (!useProvidedScope)
558 return Collections.emptySet();
559
560 HashSet<URL> providedJars = new HashSet<>();
561
562 for (Iterator<Artifact> iter = projectArtifacts.iterator(); iter.hasNext(); )
563 {
564 Artifact artifact = iter.next();
565 if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()))
566 {
567 //test to see if the provided artifact was amongst the plugin artifacts
568 URL jar = artifact.getFile().toURI().toURL();
569 if (!pluginJars.contains(jar))
570 {
571 providedJars.add(jar);
572 if (getLog().isDebugEnabled())
573 {
574 getLog().debug("Adding provided artifact: " + artifact);
575 }
576 }
577 else
578 {
579 if (getLog().isDebugEnabled())
580 {
581 getLog().debug("Skipping provided artifact: " + artifact);
582 }
583 }
584 }
585 }
586 return providedJars;
587 }
588
589 private File getWebXmlFile()
590 throws IOException
591 {
592 File file = null;
593 File baseDir = project.getBasedir().getCanonicalFile();
594 File defaultWebAppSrcDir = new File(baseDir, "src/main/webapp").getCanonicalFile();
595 File webAppSrcDir = new File(webAppSourceDirectory).getCanonicalFile();
596 File defaultWebXml = new File(defaultWebAppSrcDir, "web.xml").getCanonicalFile();
597
598 //If the web.xml has been changed from the default, try that
599 File webXmlFile = new File(webXml).getCanonicalFile();
600 if (webXmlFile.compareTo(defaultWebXml) != 0)
601 {
602 file = new File(webXml);
603 return file;
604 }
605
606 //If the web app src directory has not been changed from the default, use whatever
607 //is set for the web.xml location
608 file = new File(webAppSrcDir, "web.xml");
609 return file;
610 }
611 }