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:
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                      String.format(
48                          "pom.xml don't match the xpath query [%s]", xpath
49                      )
50                  );
51              }
52          }
53      }
54  
55      /**
56       * Parse pom.xml.
57       * @param env Environment
58       * @return XML instance
59       */
60      private static XML pom(final Environment env) {
61          try {
62              return new XMLDocument(
63                  FileUtils.readFileToString(
64                      new File(
65                          String.format(
66                              "%s%s%s",
67                              env.basedir(),
68                              File.separator,
69                              "pom.xml"
70                          )
71                      ),
72                      StandardCharsets.UTF_8
73                  )
74              ).registerNs("pom", "http://maven.apache.org/POM/4.0.0");
75          } catch (final IOException exc) {
76              throw new IllegalArgumentException(exc);
77          }
78      }
79  }