View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2025 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:
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      @Override
31      public void validate(final MavenEnvironment env)
32          throws ValidationException {
33          PomXpathValidator.validate(PomXpathValidator.pom(env), env.asserts());
34      }
35  
36      /**
37       * Validate pom against xpath queries.
38       * @param pom POM
39       * @param xpaths Xpath queries
40       * @throws ValidationException validation exception
41       */
42      private static void validate(final XML pom, final Iterable<String> xpaths)
43          throws ValidationException {
44          for (final String xpath : xpaths) {
45              if (pom.xpath(xpath).isEmpty()) {
46                  throw new ValidationException(
47                      "pom.xml don't match the xpath query [%s]", xpath
48                  );
49              }
50          }
51      }
52  
53      /**
54       * Parse pom.xml.
55       *
56       * @param env Environment
57       * @return XML instance
58       */
59      private static XML pom(final Environment env) {
60          try {
61              return new XMLDocument(
62                  FileUtils.readFileToString(
63                      new File(
64                          String.format(
65                              "%s%s%s",
66                              env.basedir(),
67                              File.separator,
68                              "pom.xml"
69                          )
70                      ),
71                      StandardCharsets.UTF_8
72                  )
73              ).registerNs("pom", "http://maven.apache.org/POM/4.0.0");
74          } catch (final IOException exc) {
75              throw new IllegalArgumentException(exc);
76          }
77      }
78  }