Search in sources :

Example 16 with LocalizedMessage

use of org.eclipse.wst.validation.internal.operations.LocalizedMessage in project webtools.sourceediting by eclipse.

the class StreamingMarkupValidator method addAttributeError.

/**
 * Creates an error related to an attribute
 */
private void addAttributeError(String messageText, String attributeValueText, int start, int length, int line, int problemId, IReporter reporter, int messageSeverity) {
    LocalizedMessage message = new LocalizedMessage(messageSeverity, messageText);
    message.setOffset(start);
    message.setLength(length);
    message.setLineNo(line + 1);
    getAnnotationMsg(reporter, problemId, message, attributeValueText, length);
}
Also used : LocalizedMessage(org.eclipse.wst.validation.internal.operations.LocalizedMessage)

Example 17 with LocalizedMessage

use of org.eclipse.wst.validation.internal.operations.LocalizedMessage in project webtools.sourceediting by eclipse.

the class XMLValidator method validate.

/**
 * Validate the inputStream
 *
 * @param uri
 *    The URI of the file to validate.
 * @param inputstream
 *    The inputStream of the file to validate
 * @param configuration
 *    A configuration for this validation session.
 * @param result
 *    The validation result
 * @param context
 *    The validation context
 * @return
 *    Returns an XML validation report.
 */
public XMLValidationReport validate(String uri, InputStream inputStream, XMLValidationConfiguration configuration, ValidationResult result, NestedValidatorContext context) {
    // $NON-NLS-1$
    String grammarFile = "";
    // Used for the preparse.
    Reader reader1 = null;
    // Used for validation parse.
    Reader reader2 = null;
    if (inputStream != null) {
        String string = createStringForInputStream(inputStream);
        reader1 = new StringReader(string);
        reader2 = new StringReader(string);
    }
    XMLValidationInfo valinfo = new XMLValidationInfo(uri);
    MyEntityResolver entityResolver = new MyEntityResolver(uriResolver, context);
    ValidatorHelper helper = new ValidatorHelper();
    try {
        helper.computeValidationInformation(uri, reader1, uriResolver);
        valinfo.setDTDEncountered(helper.isDTDEncountered);
        valinfo.setElementDeclarationCount(helper.numDTDElements);
        valinfo.setNamespaceEncountered(helper.isNamespaceEncountered);
        valinfo.setGrammarEncountered(helper.isGrammarEncountered);
        XMLReader reader = createXMLReader(valinfo, entityResolver);
        // Set the configuration option
        if (configuration.getFeature(XMLValidationConfiguration.HONOUR_ALL_SCHEMA_LOCATIONS)) {
            // $NON-NLS-1$
            reader.setFeature("http://apache.org/xml/features/honour-all-schemaLocations", true);
        }
        if (configuration.getFeature(XMLValidationConfiguration.USE_XINCLUDE)) {
            // $NON-NLS-1$
            reader.setFeature("http://apache.org/xml/features/xinclude", true);
        }
        // Support external schema locations
        boolean isGrammarEncountered = helper.isGrammarEncountered;
        if (!isGrammarEncountered) {
            isGrammarEncountered = checkExternalSchemas(reader, valinfo.getFileURI());
        }
        // $NON-NLS-1$
        reader.setFeature("http://xml.org/sax/features/validation", isGrammarEncountered);
        // $NON-NLS-1$
        reader.setFeature("http://apache.org/xml/features/validation/schema", isGrammarEncountered);
        XMLErrorHandler errorhandler = new XMLErrorHandler(valinfo);
        reader.setErrorHandler(errorhandler);
        InputSource inputSource = new InputSource(uri);
        inputSource.setCharacterStream(reader2);
        ClassLoader originalClzLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        try {
            reader.parse(inputSource);
        } finally {
            Thread.currentThread().setContextClassLoader(originalClzLoader);
        }
        if (configuration.getIntFeature(XMLValidationConfiguration.INDICATE_NO_GRAMMAR) > 0 && valinfo.isValid() && !isGrammarEncountered) {
            if (configuration.getIntFeature(XMLValidationConfiguration.INDICATE_NO_GRAMMAR) == 1)
                valinfo.addWarning(XMLValidationMessages._WARN_NO_GRAMMAR, 1, 0, uri, NO_GRAMMAR_FOUND, null);
            else
                // 2
                valinfo.addError(XMLValidationMessages._WARN_NO_GRAMMAR, 1, 0, uri, NO_GRAMMAR_FOUND, null);
        }
        if (configuration.getIntFeature(XMLValidationConfiguration.INDICATE_NO_DOCUMENT_ELEMENT) > 0 && valinfo.isValid() && !helper.isDocumentElementEncountered) {
            if (configuration.getIntFeature(XMLValidationConfiguration.INDICATE_NO_DOCUMENT_ELEMENT) == 1)
                valinfo.addWarning(XMLValidationMessages._NO_DOCUMENT_ELEMENT, 1, 0, uri, NO_DOCUMENT_ELEMENT_FOUND, null);
            else
                // 2
                valinfo.addError(XMLValidationMessages._NO_DOCUMENT_ELEMENT, 1, 0, uri, NO_DOCUMENT_ELEMENT_FOUND, null);
        }
        if (helper.isDTDEncountered)
            grammarFile = entityResolver.getLocation();
        else
            grammarFile = helper.schemaLocationString;
    } catch (SAXParseException saxParseException) {
    // These errors are caught by the error handler.
    // addValidationMessage(valinfo, saxParseException);
    } catch (IOException ioException) {
        addValidationMessage(valinfo, ioException);
    } catch (Exception exception) {
        Logger.logException(exception.getLocalizedMessage(), exception);
    }
    // still proceed as before
    if (result != null) {
        try {
            IResource resource = getWorkspaceFileFromLocation(grammarFile);
            ArrayList resources = new ArrayList();
            if (resource != null)
                resources.add(resource);
            result.setDependsOn((IResource[]) resources.toArray(new IResource[0]));
        } catch (Exception e) {
            Logger.logException(e.getLocalizedMessage(), e);
        }
    }
    if (XMLCorePlugin.getDefault().getPluginPreferences().getBoolean(XMLCorePreferenceNames.MARKUP_VALIDATION)) {
        IReporter reporter = executeMarkupValidator(uri);
        if (reporter != null) {
            List msgList = reporter.getMessages();
            for (int i = 0; i < msgList.size(); i++) {
                LocalizedMessage msg = (LocalizedMessage) msgList.get(i);
                if (msg.getSeverity() == 2)
                    // $NON-NLS-1$
                    valinfo.addError(msg.getLocalizedMessage(), msg.getLineNumber(), msg.getOffset(), valinfo.getFileURI(), "null", getMsgArguments(msg));
                else if (msg.getSeverity() == 1)
                    // $NON-NLS-1$
                    valinfo.addWarning(msg.getLocalizedMessage(), msg.getLineNumber(), msg.getOffset(), valinfo.getFileURI(), "null", getMsgArguments(msg));
            }
        }
    }
    return valinfo;
}
Also used : XMLInputSource(org.apache.xerces.xni.parser.XMLInputSource) InputSource(org.xml.sax.InputSource) IReporter(org.eclipse.wst.validation.internal.provisional.core.IReporter) ArrayList(java.util.ArrayList) Reader(java.io.Reader) XMLReader(org.xml.sax.XMLReader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) XNIException(org.apache.xerces.xni.XNIException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SAXParseException(org.xml.sax.SAXParseException) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) List(java.util.List) ArrayList(java.util.ArrayList) XMLReader(org.xml.sax.XMLReader) IResource(org.eclipse.core.resources.IResource) LocalizedMessage(org.eclipse.wst.validation.internal.operations.LocalizedMessage)

Example 18 with LocalizedMessage

use of org.eclipse.wst.validation.internal.operations.LocalizedMessage in project webtools.sourceediting by eclipse.

the class MarkupValidator method checkStartEndTagPairs.

private void checkStartEndTagPairs(IStructuredDocumentRegion sdRegion, IReporter reporter) {
    if (sdRegion.isDeleted()) {
        return;
    }
    // check start/end tag pairs
    IDOMNode xmlNode = getXMLNode(sdRegion);
    if (xmlNode == null) {
        return;
    }
    boolean selfClosed = false;
    String tagName = null;
    /**
     * For tags that aren't meant to be EMPTY, make sure it's empty or has an end tag
     */
    if (xmlNode.isContainer()) {
        IStructuredDocumentRegion endRegion = xmlNode.getEndStructuredDocumentRegion();
        if (endRegion == null) {
            IStructuredDocumentRegion startRegion = xmlNode.getStartStructuredDocumentRegion();
            if (startRegion != null && !startRegion.isDeleted() && DOMRegionContext.XML_TAG_OPEN.equals(startRegion.getFirstRegion().getType())) {
                // analyze the tag (check self closing)
                ITextRegionList regions = startRegion.getRegions();
                ITextRegion r = null;
                int start = sdRegion.getStart();
                int length = sdRegion.getTextLength();
                for (int i = 0; i < regions.size(); i++) {
                    r = regions.get(i);
                    if (r.getType() == DOMRegionContext.XML_TAG_NAME) {
                        tagName = sdRegion.getText(r);
                        start = sdRegion.getStartOffset(r);
                        length = r.getTextLength();
                    } else if (r.getType() == DOMRegionContext.XML_EMPTY_TAG_CLOSE) {
                        selfClosed = true;
                    }
                }
                if (!selfClosed && (tagName != null)) {
                    Object[] args = { tagName };
                    String messageText = NLS.bind(XMLCoreMessages.Missing_end_tag_, args);
                    int lineNumber = getLineNumber(start);
                    LocalizedMessage message = new LocalizedMessage(getPluginPreference().getInt(XMLCorePreferenceNames.MISSING_END_TAG), messageText);
                    message.setOffset(start);
                    message.setLength(length);
                    message.setLineNo(lineNumber);
                    Object[] additionalFixInfo = getStartEndFixInfo(xmlNode, tagName, r);
                    getAnnotationMsg(reporter, ProblemIDsXML.MissingEndTag, message, additionalFixInfo, length);
                }
            }
        } else {
            IStructuredDocumentRegion startRegion = xmlNode.getStartStructuredDocumentRegion();
            if (startRegion == null || startRegion.isDeleted()) {
                // analyze the tag (check self closing)
                ITextRegionList regions = endRegion.getRegions();
                ITextRegion r = null;
                int start = sdRegion.getStart();
                int length = sdRegion.getTextLength();
                for (int i = 0; i < regions.size(); i++) {
                    r = regions.get(i);
                    if (r.getType() == DOMRegionContext.XML_TAG_NAME) {
                        tagName = sdRegion.getText(r);
                        start = sdRegion.getStartOffset(r);
                        length = r.getTextLength();
                    }
                }
                if (tagName != null) {
                    Object[] args = { tagName };
                    String messageText = NLS.bind(XMLCoreMessages.Missing_start_tag_, args);
                    int lineNumber = getLineNumber(start);
                    LocalizedMessage message = new LocalizedMessage(getPluginPreference().getInt(XMLCorePreferenceNames.MISSING_START_TAG), messageText);
                    message.setOffset(start);
                    message.setLength(length);
                    message.setLineNo(lineNumber);
                    Object[] additionalFixInfo = getStartEndFixInfo(xmlNode, tagName, r);
                    getAnnotationMsg(reporter, ProblemIDsXML.MissingStartTag, message, additionalFixInfo, length);
                }
            }
        }
    } else /*
		 * Check for an end tag that has no start tag
		 */
    {
        IStructuredDocumentRegion startRegion = xmlNode.getStartStructuredDocumentRegion();
        if (startRegion == null) {
            IStructuredDocumentRegion endRegion = xmlNode.getEndStructuredDocumentRegion();
            if (!endRegion.isDeleted()) {
                // get name
                ITextRegionList regions = endRegion.getRegions();
                ITextRegion r = null;
                for (int i = 0; i < regions.size(); i++) {
                    r = regions.get(i);
                    if (r.getType() == DOMRegionContext.XML_TAG_NAME) {
                        tagName = sdRegion.getText(r);
                    }
                }
                if (!selfClosed && (tagName != null)) {
                    String messageText = XMLCoreMessages.Indicate_no_grammar_specified_severities_error;
                    int start = sdRegion.getStart();
                    int lineNumber = getLineNumber(start);
                    // SEVERITY_STRUCTURE == IMessage.HIGH_SEVERITY
                    IMessage message = new LocalizedMessage(IMessage.HIGH_SEVERITY, messageText);
                    message.setOffset(start);
                    message.setLength(sdRegion.getTextLength());
                    message.setLineNo(lineNumber);
                    reporter.addMessage(this, message);
                }
            }
        }
    }
}
Also used : ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) ITextRegion(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion) IMessage(org.eclipse.wst.validation.internal.provisional.core.IMessage) LocalizedMessage(org.eclipse.wst.validation.internal.operations.LocalizedMessage)

Example 19 with LocalizedMessage

use of org.eclipse.wst.validation.internal.operations.LocalizedMessage in project webtools.sourceediting by eclipse.

the class MarkupValidator method validateV1File.

/**
 * @param currentFile
 * @param reporter
 */
private void validateV1File(IFile currentFile, IReporter reporter) {
    Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, currentFile.getFullPath().toString().substring(1));
    reporter.displaySubtask(MarkupValidator.this, message);
    IStructuredModel model = null;
    try {
        model = StructuredModelManager.getModelManager().getModelForRead(currentFile);
        IStructuredDocument document = null;
        if (model != null) {
            document = model.getStructuredDocument();
            connect(document);
            IStructuredDocumentRegion validationRegion = document.getFirstStructuredDocumentRegion();
            while (validationRegion != null) {
                validate(validationRegion, reporter);
                validationRegion = validationRegion.getNext();
            }
            disconnect(document);
        }
    } catch (Exception e) {
        Logger.logException(e);
    } finally {
        if (model != null) {
            model.releaseFromRead();
        }
    }
}
Also used : IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) IMessage(org.eclipse.wst.validation.internal.provisional.core.IMessage) LocalizedMessage(org.eclipse.wst.validation.internal.operations.LocalizedMessage) Message(org.eclipse.wst.validation.internal.core.Message) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) ValidationException(org.eclipse.wst.validation.internal.core.ValidationException) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) LocalizedMessage(org.eclipse.wst.validation.internal.operations.LocalizedMessage)

Example 20 with LocalizedMessage

use of org.eclipse.wst.validation.internal.operations.LocalizedMessage in project webtools.sourceediting by eclipse.

the class MarkupValidator method checkForSpaceBeforeName.

private void checkForSpaceBeforeName(IStructuredDocumentRegion structuredDocumentRegion, IReporter reporter) {
    if (structuredDocumentRegion.isDeleted()) {
        return;
    }
    String sdRegionText = structuredDocumentRegion.getFullText();
    if (sdRegionText.startsWith(" ")) {
        // $NON-NLS-1$
        IStructuredDocumentRegion prev = structuredDocumentRegion.getPrevious();
        if (prev != null) {
            // this is possibly the case of "< tag"
            if ((prev.getRegions().size() == 1) && isStartTag(prev)) {
                // add the error for preceding space in tag name
                String messageText = XMLCoreMessages.ReconcileStepForMarkup_2;
                int start = structuredDocumentRegion.getStartOffset();
                // find length of whitespace
                // $NON-NLS-1$
                int length = sdRegionText.trim().equals("") ? sdRegionText.length() : sdRegionText.indexOf(sdRegionText.trim());
                LocalizedMessage message = new LocalizedMessage(getPluginPreference().getInt(XMLCorePreferenceNames.WHITESPACE_BEFORE_TAGNAME), messageText);
                message.setOffset(start);
                message.setLength(length);
                message.setLineNo(getLineNumber(start));
                getAnnotationMsg(reporter, ProblemIDsXML.SpacesBeforeTagName, message, null, length);
            }
        }
    }
}
Also used : IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) LocalizedMessage(org.eclipse.wst.validation.internal.operations.LocalizedMessage)

Aggregations

LocalizedMessage (org.eclipse.wst.validation.internal.operations.LocalizedMessage)41 ITextRegionList (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList)12 ITextRegion (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion)10 AnnotationInfo (org.eclipse.wst.sse.ui.internal.reconcile.validator.AnnotationInfo)9 IncrementalReporter (org.eclipse.wst.sse.ui.internal.reconcile.validator.IncrementalReporter)9 IStructuredDocumentRegion (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion)8 List (java.util.List)7 IMessage (org.eclipse.wst.validation.internal.provisional.core.IMessage)6 IReporter (org.eclipse.wst.validation.internal.provisional.core.IReporter)6 Test (org.junit.Test)5 CoreException (org.eclipse.core.runtime.CoreException)4 Message (org.eclipse.wst.validation.internal.core.Message)4 BufferedReader (java.io.BufferedReader)3 IOException (java.io.IOException)3 InputStreamReader (java.io.InputStreamReader)3 IStructuredModel (org.eclipse.wst.sse.core.internal.provisional.IStructuredModel)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Stack (java.util.Stack)2 BadLocationException (org.eclipse.jface.text.BadLocationException)2 DocumentReader (org.eclipse.wst.sse.core.internal.document.DocumentReader)2