View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.maven;
6   
7   import com.jcabi.xml.XML;
8   import com.jcabi.xml.XMLDocument;
9   import com.qulice.spi.Environment;
10  import com.qulice.spi.ValidationException;
11  import java.io.File;
12  import java.io.IOException;
13  import java.nio.charset.StandardCharsets;
14  import org.apache.commons.io.FileUtils;
15  
16  /**
17   * Check pom.xml with XPath validation queries.
18   *
19   * <p>Restrictions:</p>
20   *
21   * <ol>
22   * <li>Each xpath component should contains namespace prefix pom:</li>
23   * <li>Each xpath query should end with /text()</li>
24   * </ol>
25   *
26   * @since 0.6
27   */
28  public final class PomXpathValidator implements MavenValidator {
29  
30      /**
31       * Default constructor.
32       */
33      public PomXpathValidator() {
34          // nothing to initialize
35      }
36  
37      @Override
38      public void validate(final MavenEnvironment env)
39          throws ValidationException {
40          PomXpathValidator.validate(PomXpathValidator.pom(env), env.asserts());
41      }
42  
43      private static void validate(final XML pom, final Iterable<String> xpaths)
44          throws ValidationException {
45          for (final String xpath : xpaths) {
46              if (pom.xpath(xpath).isEmpty()) {
47                  throw new ValidationException(
48                      String.format(
49                          "pom.xml don't match the xpath query [%s]", xpath
50                      )
51                  );
52              }
53          }
54      }
55  
56      private static XML pom(final Environment env) {
57          try {
58              return new XMLDocument(
59                  FileUtils.readFileToString(
60                      new File(
61                          String.format(
62                              "%s%s%s",
63                              env.basedir(),
64                              File.separator,
65                              "pom.xml"
66                          )
67                      ),
68                      StandardCharsets.UTF_8
69                  )
70              ).registerNs("pom", "http://maven.apache.org/POM/4.0.0");
71          } catch (final IOException exc) {
72              throw new IllegalArgumentException(exc);
73          }
74      }
75  }