Search in sources :

Example 1 with MessageEmitterAdapter

use of nu.validator.messages.MessageEmitterAdapter in project validator by validator.

the class SimpleCommandLineValidator method setErrorHandler.

private static void setErrorHandler() {
    SourceCode sourceCode = validator.getSourceCode();
    ImageCollector imageCollector = new ImageCollector(sourceCode);
    boolean showSource = false;
    if (outputFormat == OutputFormat.TEXT) {
        errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, imageCollector, lineOffset, true, new TextMessageEmitter(out, asciiQuotes));
    } else if (outputFormat == OutputFormat.GNU) {
        errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, imageCollector, lineOffset, true, new GnuMessageEmitter(out, asciiQuotes));
    } else if (outputFormat == OutputFormat.XML) {
        errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, imageCollector, lineOffset, true, new XmlMessageEmitter(new XmlSerializer(out)));
    } else if (outputFormat == OutputFormat.JSON) {
        String callback = null;
        errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, imageCollector, lineOffset, true, new JsonMessageEmitter(new nu.validator.json.Serializer(out), callback));
    } else {
        throw new RuntimeException("Bug. Should be unreachable.");
    }
    errorHandler.setErrorsOnly(errorsOnly);
}
Also used : SourceCode(nu.validator.source.SourceCode) MessageEmitterAdapter(nu.validator.messages.MessageEmitterAdapter) TextMessageEmitter(nu.validator.messages.TextMessageEmitter) GnuMessageEmitter(nu.validator.messages.GnuMessageEmitter) ImageCollector(nu.validator.servlet.imagereview.ImageCollector) XmlMessageEmitter(nu.validator.messages.XmlMessageEmitter) JsonMessageEmitter(nu.validator.messages.JsonMessageEmitter) XmlSerializer(nu.validator.htmlparser.sax.XmlSerializer) XmlSerializer(nu.validator.htmlparser.sax.XmlSerializer)

Example 2 with MessageEmitterAdapter

use of nu.validator.messages.MessageEmitterAdapter in project validator by validator.

the class Assertions method endElement.

/**
 * @see nu.validator.checker.Checker#endElement(java.lang.String,
 *      java.lang.String, java.lang.String)
 */
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
    if ("http://www.w3.org/1999/xhtml" == uri && "template".equals(localName)) {
        numberOfTemplatesDeep--;
        if (numberOfTemplatesDeep != 0) {
            return;
        }
    } else if (numberOfTemplatesDeep > 0) {
        return;
    }
    StackNode node = pop();
    String systemId = node.locator().getSystemId();
    String publicId = node.locator().getPublicId();
    Locator locator = null;
    openSingleSelects.remove(node);
    openLabels.remove(node);
    openMediaElements.remove(node);
    if ("http://www.w3.org/1999/xhtml" == uri) {
        if ("figure" == localName) {
            if ((node.needsFigcaption() && !node.hasFigcaptionContent()) || node.hasTextNode() || node.hasEmbeddedContent()) {
                for (Locator imgLocator : node.getImagesLackingAlt()) {
                    err("An \u201Cimg\u201D element must have an" + " \u201Calt\u201D attribute, except under" + " certain conditions. For details, consult" + " guidance on providing text alternatives" + " for images.", imgLocator);
                }
            }
        } else if ("picture" == localName) {
            siblingSources.clear();
        } else if ("select" == localName && node.isOptionNeeded()) {
            if (!node.hasOption()) {
                err("A \u201Cselect\u201D element with a" + " \u201Crequired\u201D attribute, and without a" + " \u201Cmultiple\u201D attribute, and without a" + " \u201Csize\u201D attribute whose value is" + " greater than" + " \u201C1\u201D, must have a child" + " \u201Coption\u201D element.");
            }
            if (node.nonEmptyOptionLocator() != null) {
                err("The first child \u201Coption\u201D element of a" + " \u201Cselect\u201D element with a" + " \u201Crequired\u201D attribute, and without a" + " \u201Cmultiple\u201D attribute, and without a" + " \u201Csize\u201D attribute whose value is" + " greater than" + " \u201C1\u201D, must have either an empty" + " \u201Cvalue\u201D attribute, or must have no" + " text content." + " Consider either adding a placeholder option" + " label, or adding a" + " \u201Csize\u201D attribute with a value equal" + " to the number of" + " \u201Coption\u201D elements.", node.nonEmptyOptionLocator());
            }
        } else if ("section" == localName && !node.hasHeading()) {
            warn("Section lacks heading. Consider using" + " \u201ch2\u201d-\u201ch6\u201d elements to add" + " identifying headings to all sections.", node.locator());
        } else if ("article" == localName && !node.hasHeading()) {
            warn("Article lacks heading. Consider using" + " \u201ch2\u201d-\u201ch6\u201d elements to add" + " identifying headings to all articles.", node.locator());
        } else if (("h1" == localName || "h2" == localName || "h3" == localName || "h4" == localName || "h5" == localName || "h6" == localName) && !node.hasTextNode() && !node.hasImg()) {
            warn("Empty heading.", node.locator());
        } else if ("option" == localName && !stack[currentPtr].hasOption()) {
            stack[currentPtr].setOptionFound();
        } else if ("style" == localName) {
            String styleContents = node.getTextContent().toString();
            int lineOffset = 0;
            if (styleContents.startsWith("\n")) {
                lineOffset = 1;
            }
            ApplContext ac = new ApplContext("en");
            ac.setCssVersionAndProfile("css3svg");
            ac.setMedium("all");
            ac.setTreatVendorExtensionsAsWarnings(true);
            ac.setTreatCssHacksAsWarnings(true);
            ac.setWarningLevel(-1);
            ac.setFakeURL("file://localhost/StyleElement");
            StyleSheetParser styleSheetParser = new StyleSheetParser();
            styleSheetParser.parseStyleSheet(ac, new StringReader(styleContents.substring(lineOffset)), null);
            styleSheetParser.getStyleSheet().findConflicts(ac);
            Errors errors = styleSheetParser.getStyleSheet().getErrors();
            if (errors.getErrorCount() > 0) {
                incrementUseCounter("style-element-errors-found");
            }
            for (int i = 0; i < errors.getErrorCount(); i++) {
                String message = "";
                String cssProperty = "";
                String cssMessage = "";
                CssError error = errors.getErrorAt(i);
                int beginLine = error.getBeginLine() + lineOffset;
                int beginColumn = error.getBeginColumn();
                int endLine = error.getEndLine() + lineOffset;
                int endColumn = error.getEndColumn();
                if (beginLine == 0) {
                    continue;
                }
                Throwable ex = error.getException();
                if (ex instanceof CssParseException) {
                    CssParseException cpe = (CssParseException) ex;
                    if (// 
                    "generator.unrecognize".equals(cpe.getErrorType())) {
                        cssMessage = "Parse Error";
                    }
                    if (cpe.getProperty() != null) {
                        cssProperty = String.format("\u201c%s\u201D: ", cpe.getProperty());
                    }
                    if (cpe.getMessage() != null) {
                        cssMessage = cpe.getMessage();
                    }
                    if (!"".equals(cssMessage)) {
                        message = cssProperty + cssMessage + ".";
                    }
                } else {
                    message = ex.getMessage();
                }
                if (!"".equals(message)) {
                    int lastLine = // 
                    node.locator.getLineNumber() + endLine - 1;
                    int lastColumn = endColumn;
                    int columnOffset = node.locator.getColumnNumber();
                    if (error.getBeginLine() == 1) {
                        if (lineOffset != 0) {
                            columnOffset = 0;
                        }
                    } else {
                        columnOffset = 0;
                    }
                    String prefix = sourceIsCss ? "" : "CSS: ";
                    SAXParseException spe = new // 
                    SAXParseException(// 
                    prefix + message, // 
                    publicId, // 
                    systemId, lastLine, lastColumn);
                    int[] start = { node.locator.getLineNumber() + beginLine - 1, beginColumn, columnOffset };
                    if ((getErrorHandler() instanceof MessageEmitterAdapter) && !(getErrorHandler() instanceof TestRunner)) {
                        // 
                        ((MessageEmitterAdapter) getErrorHandler()).errorWithStart(spe, start);
                    } else {
                        getErrorHandler().error(spe);
                    }
                }
            }
        }
        if ("article" == localName || "aside" == localName || "nav" == localName || "section" == localName) {
            currentSectioningElementPtr = currentPtr - 1;
            currentSectioningDepth--;
        }
    }
    if ((locator = openActiveDescendants.remove(node)) != null) {
        warn("Attribute \u201Caria-activedescendant\u201D value should " + "either refer to a descendant element, or should " + "be accompanied by attribute \u201Caria-owns\u201D.", locator);
    }
}
Also used : MessageEmitterAdapter(nu.validator.messages.MessageEmitterAdapter) TestRunner(nu.validator.client.TestRunner) CssParseException(org.w3c.css.parser.CssParseException) StyleSheetParser(org.w3c.css.css.StyleSheetParser) Errors(org.w3c.css.parser.Errors) Locator(org.xml.sax.Locator) ApplContext(org.w3c.css.util.ApplContext) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) CssError(org.w3c.css.parser.CssError)

Example 3 with MessageEmitterAdapter

use of nu.validator.messages.MessageEmitterAdapter in project validator by validator.

the class VerifierServletTransaction method service.

void service() throws ServletException, IOException {
    this.methodIsGet = "GET".equals(request.getMethod()) || "HEAD".equals(request.getMethod());
    this.out = response.getOutputStream();
    try {
        request.setCharacterEncoding("utf-8");
    } catch (NoSuchMethodError e) {
        log4j.debug("Vintage Servlet API doesn't support setCharacterEncoding().", e);
    }
    if (!methodIsGet) {
        postContentType = request.getContentType();
        if (postContentType == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Type missing");
            return;
        } else if (postContentType.trim().toLowerCase().startsWith("application/x-www-form-urlencoded")) {
            response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "application/x-www-form-urlencoded not supported. Please use multipart/form-data.");
            return;
        }
    }
    String outFormat = request.getParameter("out");
    if (outFormat == null) {
        outputFormat = OutputFormat.HTML;
    } else {
        if ("html".equals(outFormat)) {
            outputFormat = OutputFormat.HTML;
        } else if ("xhtml".equals(outFormat)) {
            outputFormat = OutputFormat.XHTML;
        } else if ("text".equals(outFormat)) {
            outputFormat = OutputFormat.TEXT;
        } else if ("gnu".equals(outFormat)) {
            outputFormat = OutputFormat.GNU;
        } else if ("xml".equals(outFormat)) {
            outputFormat = OutputFormat.XML;
        } else if ("json".equals(outFormat)) {
            outputFormat = OutputFormat.JSON;
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported output format");
            return;
        }
    }
    if (!methodIsGet) {
        document = request.getHeader("Content-Location");
    }
    if (document == null) {
        document = request.getParameter("doc");
    }
    if (document == null) {
        document = request.getParameter("file");
    }
    document = ("".equals(document)) ? null : document;
    if (document != null) {
        for (String domain : DENY_LIST) {
            if (!"".equals(domain) && document.contains(domain)) {
                response.sendError(429, "Too many requests");
                return;
            }
        }
    }
    String callback = null;
    if (outputFormat == OutputFormat.JSON) {
        callback = request.getParameter("callback");
        if (callback != null) {
            Matcher m = JS_IDENTIFIER.matcher(callback);
            if (m.matches()) {
                if (Arrays.binarySearch(JS_RESERVED_WORDS, callback) >= 0) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Callback is a reserved word.");
                    return;
                }
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Callback is not a valid ECMA 262 IdentifierName.");
                return;
            }
        }
    }
    if (willValidate()) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
    } else if (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML) {
        response.setDateHeader("Last-Modified", lastModified);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No input document");
        return;
    }
    setup();
    String filterString = systemFilterString;
    String filterPatternParam = request.getParameter("filterpattern");
    if (filterPatternParam != null && !"".equals(filterPatternParam)) {
        if ("".equals(filterString)) {
            filterString = scrub(filterPatternParam);
        } else {
            filterString += "|" + scrub(filterPatternParam);
        }
    }
    String filterUrl = request.getParameter("filterurl");
    if (filterUrl != null && !"".equals(filterUrl)) {
        try {
            // 
            InputSource filterFile = // 
            (new PrudentHttpEntityResolver(-1, true, null)).resolveEntity(null, filterUrl);
            StringBuilder sb = new StringBuilder();
            // 
            BufferedReader reader = new BufferedReader(new InputStreamReader(filterFile.getByteStream()));
            String line;
            String pipe = "";
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#")) {
                    continue;
                }
                sb.append(pipe);
                sb.append(line);
                pipe = "|";
            }
            if (sb.length() != 0) {
                if (!"".equals(filterString)) {
                    filterString = scrub(sb.toString());
                } else {
                    filterString += "|" + scrub(sb.toString());
                }
            }
        } catch (Exception e) {
            response.sendError(500, e.getMessage());
        }
    }
    Pattern filterPattern = null;
    if (!"".equals(filterString)) {
        filterPattern = Pattern.compile(filterString);
    }
    if (request.getParameter("useragent") != null) {
        userAgent = scrub(request.getParameter("useragent"));
    } else {
        userAgent = USER_AGENT;
    }
    if (request.getParameter("acceptlanguage") != null) {
        request.setAttribute("http://validator.nu/properties/accept-language", scrub(request.getParameter("acceptlanguage")));
    }
    Object inputType = request.getAttribute("nu.validator.servlet.MultipartFormDataFilter.type");
    showSource = (request.getParameter("showsource") != null);
    showSource = (showSource || "textarea".equals(inputType));
    showOutline = (request.getParameter("showoutline") != null);
    if (request.getParameter("checkerrorpages") != null) {
        request.setAttribute("http://validator.nu/properties/ignore-response-status", true);
    }
    if (request.getParameter("showimagereport") != null) {
        imageCollector = new ImageCollector(sourceCode);
    }
    String charset = request.getParameter("charset");
    if (charset != null) {
        charset = scrub(charset.trim());
        if (!"".equals(charset)) {
            charsetOverride = charset;
        }
    }
    String nsfilter = request.getParameter("nsfilter");
    if (nsfilter != null) {
        for (String ns : SPACE.split(nsfilter)) {
            if (ns.length() > 0) {
                filteredNamespaces.add(ns);
            }
        }
    }
    boolean errorsOnly = ("error".equals(request.getParameter("level")));
    boolean asciiQuotes = (request.getParameter("asciiquotes") != null);
    int lineOffset = 0;
    String lineOffsetStr = request.getParameter("lineoffset");
    if (lineOffsetStr != null) {
        try {
            lineOffset = Integer.parseInt(lineOffsetStr);
        } catch (NumberFormatException e) {
        }
    }
    try {
        if (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML) {
            if (outputFormat == OutputFormat.HTML) {
                response.setContentType("text/html; charset=utf-8");
                contentHandler = new HtmlSerializer(out);
            } else {
                response.setContentType("application/xhtml+xml");
                contentHandler = new XmlSerializer(out);
            }
            emitter = new XhtmlSaxEmitter(contentHandler);
            errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, imageCollector, lineOffset, false, new XhtmlMessageEmitter(contentHandler));
            PageEmitter.emit(contentHandler, this);
        } else {
            if (outputFormat == OutputFormat.TEXT) {
                response.setContentType("text/plain; charset=utf-8");
                errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new TextMessageEmitter(out, asciiQuotes));
            } else if (outputFormat == OutputFormat.GNU) {
                response.setContentType("text/plain; charset=utf-8");
                errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new GnuMessageEmitter(out, asciiQuotes));
            } else if (outputFormat == OutputFormat.XML) {
                response.setContentType("application/xml");
                errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new XmlMessageEmitter(new XmlSerializer(out)));
            } else if (outputFormat == OutputFormat.JSON) {
                if (callback == null) {
                    response.setContentType("application/json; charset=utf-8");
                } else {
                    response.setContentType("application/javascript; charset=utf-8");
                }
                errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new JsonMessageEmitter(new nu.validator.json.Serializer(out), callback));
            } else {
                throw new RuntimeException("Unreachable.");
            }
            errorHandler.setErrorsOnly(errorsOnly);
            validate();
        }
    } catch (SAXException e) {
        log4j.debug("SAXException: " + e.getMessage());
    }
}
Also used : Matcher(java.util.regex.Matcher) MessageEmitterAdapter(nu.validator.messages.MessageEmitterAdapter) PrudentHttpEntityResolver(nu.validator.xml.PrudentHttpEntityResolver) TextMessageEmitter(nu.validator.messages.TextMessageEmitter) FatalSAXException(nu.validator.gnu.xml.aelfred2.FatalSAXException) SAXException(org.xml.sax.SAXException) GnuMessageEmitter(nu.validator.messages.GnuMessageEmitter) ImageCollector(nu.validator.servlet.imagereview.ImageCollector) XhtmlSaxEmitter(nu.validator.xml.XhtmlSaxEmitter) XmlSerializer(nu.validator.htmlparser.sax.XmlSerializer) HtmlSerializer(nu.validator.htmlparser.sax.HtmlSerializer) XhtmlMessageEmitter(nu.validator.messages.XhtmlMessageEmitter) Pattern(java.util.regex.Pattern) InputStreamReader(java.io.InputStreamReader) StreamBoundException(nu.validator.io.StreamBoundException) TooManyErrorsException(nu.validator.messages.TooManyErrorsException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) NonXmlContentTypeException(nu.validator.xml.ContentTypeParser.NonXmlContentTypeException) IOException(java.io.IOException) FatalSAXException(nu.validator.gnu.xml.aelfred2.FatalSAXException) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) ServletException(javax.servlet.ServletException) SAXException(org.xml.sax.SAXException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) IncorrectSchemaException(com.thaiopensource.validate.IncorrectSchemaException) ResourceNotRetrievableException(nu.validator.xml.PrudentHttpEntityResolver.ResourceNotRetrievableException) SAXParseException(org.xml.sax.SAXParseException) HtmlSerializer(nu.validator.htmlparser.sax.HtmlSerializer) BufferedReader(java.io.BufferedReader) XmlMessageEmitter(nu.validator.messages.XmlMessageEmitter) JsonMessageEmitter(nu.validator.messages.JsonMessageEmitter) XmlSerializer(nu.validator.htmlparser.sax.XmlSerializer)

Aggregations

MessageEmitterAdapter (nu.validator.messages.MessageEmitterAdapter)3 XmlSerializer (nu.validator.htmlparser.sax.XmlSerializer)2 GnuMessageEmitter (nu.validator.messages.GnuMessageEmitter)2 JsonMessageEmitter (nu.validator.messages.JsonMessageEmitter)2 TextMessageEmitter (nu.validator.messages.TextMessageEmitter)2 XmlMessageEmitter (nu.validator.messages.XmlMessageEmitter)2 ImageCollector (nu.validator.servlet.imagereview.ImageCollector)2 SAXParseException (org.xml.sax.SAXParseException)2 IncorrectSchemaException (com.thaiopensource.validate.IncorrectSchemaException)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 StringReader (java.io.StringReader)1 SocketTimeoutException (java.net.SocketTimeoutException)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 ServletException (javax.servlet.ServletException)1 TestRunner (nu.validator.client.TestRunner)1 FatalSAXException (nu.validator.gnu.xml.aelfred2.FatalSAXException)1 HtmlSerializer (nu.validator.htmlparser.sax.HtmlSerializer)1