View Javadoc
1   /*
2    * Copyright (c) 2011-2022, jcabi.com
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met: 1) Redistributions of source code must retain the above
8    * copyright notice, this list of conditions and the following
9    * disclaimer. 2) Redistributions in binary form must reproduce the above
10   * copyright notice, this list of conditions and the following
11   * disclaimer in the documentation and/or other materials provided
12   * with the distribution. 3) Neither the name of the jcabi.com nor
13   * the names of its contributors may be used to endorse or promote
14   * products derived from this software without specific prior written
15   * permission.
16   *
17   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19   * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20   * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21   * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22   * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28   * OF THE POSSIBILITY OF SUCH DAMAGE.
29   */
30  package com.jcabi.w3c;
31  
32  import com.jcabi.aspects.Immutable;
33  import com.jcabi.http.Request;
34  import com.jcabi.http.Response;
35  import com.jcabi.http.request.JdkRequest;
36  import com.jcabi.http.response.XmlResponse;
37  import com.jcabi.log.Logger;
38  import com.jcabi.xml.XML;
39  import java.io.IOException;
40  import java.net.HttpURLConnection;
41  import java.net.URI;
42  import java.nio.charset.StandardCharsets;
43  import java.util.List;
44  import javax.ws.rs.core.HttpHeaders;
45  import javax.ws.rs.core.MediaType;
46  import lombok.EqualsAndHashCode;
47  import lombok.ToString;
48  
49  /**
50   * Implementation of (X)HTML validator.
51   *
52   * @see <a href="http://validator.w3.org/docs/api.html">W3C API</a>
53   * @since 0.1
54   */
55  @Immutable
56  @ToString
57  @EqualsAndHashCode(callSuper = false, of = "uri")
58  final class DefaultHtmlValidator
59      extends AbstractBaseValidator implements Validator {
60  
61      /**
62       * The URI to use in W3C.
63       */
64      private final transient String uri;
65  
66      /**
67       * Public ctor.
68       * @param entry Entry point to use
69       */
70      DefaultHtmlValidator(final URI entry) {
71          super();
72          this.uri = entry.toString();
73      }
74  
75      @Override
76      public ValidationResponse validate(final String html)
77          throws IOException {
78          final Request req = this.request(html);
79          final Response response = req.fetch();
80          if (response.status() != HttpURLConnection.HTTP_OK) {
81              throw new IOException(
82                  response.reason()
83              );
84          }
85          return this.build(
86              response.as(XmlResponse.class)
87                  .registerNs("nu", "http://n.validator.nu/messages/")
88                  .assertXPath("//nu:messages")
89                  .assertXPath("//nu:source")
90                  .xml()
91          );
92      }
93  
94      /**
95       * Send request and return response.
96       * @param entity The entity to POST
97       * @return The response
98       */
99      private Request request(final String entity) {
100         return new JdkRequest(this.uri)
101             .method(Request.POST)
102             .body().set(entity).back()
103             .header(HttpHeaders.USER_AGENT, AbstractBaseValidator.USER_AGENT)
104             .header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML)
105             .header(
106                 HttpHeaders.CONTENT_TYPE,
107                 Logger.format(
108                     "%s; charset=%s",
109                     MediaType.TEXT_HTML,
110                     StandardCharsets.UTF_8
111                 )
112             );
113     }
114 
115     /**
116      * Build response from XML.
117      * @param xml The response
118      * @return The validation response just built
119      */
120     private ValidationResponse build(final XML xml) {
121         final List<XML> errors = xml.nodes("//nu:error");
122         final List<XML> warnings = xml.nodes("//nu:info");
123         final DefaultValidationResponse resp = new DefaultValidationResponse(
124             errors.isEmpty() && warnings.isEmpty(),
125             URI.create(this.uri),
126             AbstractBaseValidator.textOf(xml.xpath("//nu:source/@type")),
127             AbstractBaseValidator.charset(
128                 AbstractBaseValidator.textOf(xml.xpath("//nu:source/@encoding"))
129             )
130         );
131         for (final XML node : errors) {
132             resp.addError(DefaultHtmlValidator.defect(node));
133         }
134         for (final XML node : warnings) {
135             resp.addWarning(DefaultHtmlValidator.defect(node));
136         }
137         return resp;
138     }
139 
140     /**
141      * Convert XML node to defect.
142      * @param node The node
143      * @return The defect
144      */
145     private static Defect defect(final XML node) {
146         return new Defect(
147             AbstractBaseValidator.intOf(node.xpath("nu:error/@last-line")),
148             AbstractBaseValidator.intOf(node.xpath("nu:error/@last-column")),
149             AbstractBaseValidator.textOf(node.xpath("nu:extract/text()")),
150             AbstractBaseValidator.textOf(node.xpath("nu:elaboration/text()")),
151             "",
152             AbstractBaseValidator.textOf(node.xpath("nu:message/text()"))
153         );
154     }
155 }