Search in sources :

Example 21 with SAXParseException

use of org.xml.sax.SAXParseException in project intellij-community by JetBrains.

the class ExternalDocumentValidator method runJaxpValidation.

private void runJaxpValidation(final XmlElement element, Validator.ValidationHost host) {
    final PsiFile file = element.getContainingFile();
    if (myFile == file && file != null && myModificationStamp == file.getModificationStamp() && !ValidateXmlActionHandler.isValidationDependentFilesOutOfDate((XmlFile) file) && // we have validated before
    SoftReference.dereference(myInfos) != null) {
        addAllInfos(host, myInfos.get());
        return;
    }
    if (myHandler == null)
        myHandler = new ValidateXmlActionHandler(false);
    final Project project = element.getProject();
    final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document == null)
        return;
    final List<ValidationInfo> results = new LinkedList<>();
    myHost = new Validator.ValidationHost() {

        @Override
        public void addMessage(PsiElement context, String message, int type) {
            addMessage(context, message, type == ERROR ? ErrorType.ERROR : type == WARNING ? ErrorType.WARNING : ErrorType.INFO);
        }

        @Override
        public void addMessage(final PsiElement context, final String message, @NotNull final ErrorType type) {
            final ValidationInfo o = new ValidationInfo(context, message, type);
            results.add(o);
        }
    };
    myHandler.setErrorReporter(new ErrorReporter(myHandler) {

        @Override
        public boolean isStopOnUndeclaredResource() {
            return true;
        }

        @Override
        public void processError(final SAXParseException e, final ValidateXmlActionHandler.ProblemType warning) {
            try {
                ApplicationManager.getApplication().runReadAction(() -> {
                    if (e.getPublicId() != null) {
                        return;
                    }
                    final VirtualFile errorFile = myHandler.getProblemFile(e);
                    if (!Comparing.equal(errorFile, file.getVirtualFile()) && errorFile != null) {
                        // error in attached schema
                        return;
                    }
                    if (document.getLineCount() < e.getLineNumber() || e.getLineNumber() <= 0) {
                        return;
                    }
                    Validator.ValidationHost.ErrorType problemType = getProblemType(warning);
                    int offset = Math.max(0, document.getLineStartOffset(e.getLineNumber() - 1) + e.getColumnNumber() - 2);
                    if (offset >= document.getTextLength())
                        return;
                    PsiElement currentElement = PsiDocumentManager.getInstance(project).getPsiFile(document).findElementAt(offset);
                    PsiElement originalElement = currentElement;
                    final String elementText = currentElement.getText();
                    if (elementText.equals("</")) {
                        currentElement = currentElement.getNextSibling();
                    } else if (elementText.equals(">") || elementText.equals("=")) {
                        currentElement = currentElement.getPrevSibling();
                    }
                    // Cannot find the declaration of element
                    String localizedMessage = e.getLocalizedMessage();
                    // Ideally would be to switch one messageIds
                    int endIndex = localizedMessage.indexOf(':');
                    if (endIndex < localizedMessage.length() - 1 && localizedMessage.charAt(endIndex + 1) == '/') {
                        // ignore : in http://
                        endIndex = -1;
                    }
                    String messageId = endIndex != -1 ? localizedMessage.substring(0, endIndex) : "";
                    localizedMessage = localizedMessage.substring(endIndex + 1).trim();
                    if (localizedMessage.startsWith(CANNOT_FIND_DECLARATION_ERROR_PREFIX) || localizedMessage.startsWith(ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(ROOT_ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(CONTENT_OF_ELEMENT_TYPE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    //return;
                    } else if (localizedMessage.startsWith(VALUE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    } else {
                        if (messageId.startsWith(ATTRIBUTE_MESSAGE_PREFIX)) {
                            @NonNls String prefix = "of attribute ";
                            final int i = localizedMessage.indexOf(prefix);
                            if (i != -1) {
                                int messagePrefixLength = prefix.length() + i;
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = ((XmlAttribute) currentElement).getValueElement();
                                }
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(ATTRIBUTE_ERROR_PREFIX)) {
                            final int messagePrefixLength = ATTRIBUTE_ERROR_PREFIX.length();
                            if (localizedMessage.charAt(messagePrefixLength) == '"' || localizedMessage.charAt(messagePrefixLength) == '\'') {
                                // extract the attribute name from message and get it from tag!
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = SourceTreeToPsiMap.treeElementToPsi(XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(SourceTreeToPsiMap.psiElementToTree(currentElement)));
                                }
                            } else {
                                currentElement = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class, false);
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(STRING_ERROR_PREFIX)) {
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, Validator.ValidationHost.ErrorType.WARNING);
                            }
                        } else {
                            currentElement = getNodeForMessage(currentElement != null ? currentElement : originalElement);
                            assertValidElement(currentElement, originalElement, localizedMessage);
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            }
                        }
                    }
                });
            } catch (Exception ex) {
                if (ex instanceof ProcessCanceledException)
                    throw (ProcessCanceledException) ex;
                if (ex instanceof XmlResourceResolver.IgnoredResourceException)
                    throw (XmlResourceResolver.IgnoredResourceException) ex;
                LOG.error(ex);
            }
        }
    });
    myHandler.doValidate((XmlFile) element.getContainingFile());
    myFile = file;
    myModificationStamp = myFile.getModificationStamp();
    myInfos = new WeakReference<>(results);
    addAllInfos(host, results);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) XmlResourceResolver(com.intellij.xml.util.XmlResourceResolver) ErrorReporter(com.intellij.xml.actions.validate.ErrorReporter) SAXParseException(org.xml.sax.SAXParseException) PsiFile(com.intellij.psi.PsiFile) ValidateXmlActionHandler(com.intellij.xml.actions.validate.ValidateXmlActionHandler) PsiElement(com.intellij.psi.PsiElement) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NonNls(org.jetbrains.annotations.NonNls) LinkedList(java.util.LinkedList) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) SAXParseException(org.xml.sax.SAXParseException) Project(com.intellij.openapi.project.Project) Validator(com.intellij.codeInsight.daemon.Validator)

Example 22 with SAXParseException

use of org.xml.sax.SAXParseException in project intellij-community by JetBrains.

the class RngSchemaValidator method collectInformation.

@Nullable
@Override
public MyValidationMessageConsumer collectInformation(@NotNull final PsiFile file) {
    final FileType type = file.getFileType();
    if (type != StdFileTypes.XML && type != RncFileType.getInstance()) {
        return null;
    }
    final XmlFile xmlfile = (XmlFile) file;
    final XmlDocument document = xmlfile.getDocument();
    if (document == null) {
        return null;
    }
    if (type == StdFileTypes.XML) {
        final XmlTag rootTag = document.getRootTag();
        if (rootTag == null) {
            return null;
        }
        if (!ApplicationLoader.RNG_NAMESPACE.equals(rootTag.getNamespace())) {
            return null;
        }
    } else {
        if (!ApplicationManager.getApplication().isUnitTestMode() && MyErrorFinder.hasError(xmlfile)) {
            return null;
        }
    }
    final Document doc = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
    final MyValidationMessageConsumer consumer = new MyValidationMessageConsumer();
    ErrorHandler eh = new DefaultHandler() {

        @Override
        public void warning(SAXParseException e) {
            handleError(e, file, doc, consumer.warning());
        }

        @Override
        public void error(SAXParseException e) {
            handleError(e, file, doc, consumer.error());
        }
    };
    RngParser.parsePattern(file, eh, true);
    return consumer;
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) RncFileType(org.intellij.plugins.relaxNG.compact.RncFileType) FileType(com.intellij.openapi.fileTypes.FileType) SAXParseException(org.xml.sax.SAXParseException) Document(com.intellij.openapi.editor.Document) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Nullable(org.jetbrains.annotations.Nullable)

Example 23 with SAXParseException

use of org.xml.sax.SAXParseException in project intellij-community by JetBrains.

the class ValidateAction method doValidation.

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
private static void doValidation(VirtualFile instanceFile, VirtualFile schemaFile, org.xml.sax.ErrorHandler eh) {
    final SchemaReader sr = schemaFile.getFileType() == RncFileType.getInstance() ? CompactSchemaReader.getInstance() : new AutoSchemaReader();
    final PropertyMapBuilder properties = new PropertyMapBuilder();
    ValidateProperty.ERROR_HANDLER.put(properties, eh);
    // TODO: should some options dialog displayed before validating?
    RngProperty.CHECK_ID_IDREF.add(properties);
    try {
        final String schemaPath = VfsUtilCore.fixIDEAUrl(schemaFile.getUrl());
        try {
            final ValidationDriver driver = new ValidationDriver(properties.toPropertyMap(), sr);
            final InputSource in = ValidationDriver.uriOrFileInputSource(schemaPath);
            in.setEncoding(schemaFile.getCharset().name());
            if (driver.loadSchema(in)) {
                final String path = VfsUtilCore.fixIDEAUrl(instanceFile.getUrl());
                try {
                    driver.validate(ValidationDriver.uriOrFileInputSource(path));
                } catch (IOException e1) {
                    eh.fatalError(new SAXParseException(e1.getMessage(), null, UriOrFile.fileToUri(path), -1, -1, e1));
                }
            }
        } catch (SAXParseException e1) {
            eh.fatalError(e1);
        } catch (IOException e1) {
            eh.fatalError(new SAXParseException(e1.getMessage(), null, UriOrFile.fileToUri(schemaPath), -1, -1, e1));
        }
    } catch (SAXException | MalformedURLException e1) {
        // huh?
        Logger.getInstance(ValidateAction.class.getName()).error(e1);
    }
}
Also used : CompactSchemaReader(com.thaiopensource.validate.rng.CompactSchemaReader) AutoSchemaReader(com.thaiopensource.validate.auto.AutoSchemaReader) SchemaReader(com.thaiopensource.validate.SchemaReader) InputSource(org.xml.sax.InputSource) MalformedURLException(java.net.MalformedURLException) AutoSchemaReader(com.thaiopensource.validate.auto.AutoSchemaReader) SAXParseException(org.xml.sax.SAXParseException) ValidationDriver(com.thaiopensource.validate.ValidationDriver) PropertyMapBuilder(com.thaiopensource.util.PropertyMapBuilder) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException)

Example 24 with SAXParseException

use of org.xml.sax.SAXParseException in project ACS by ACS-Community.

the class DALImpl method loadRecords.

/**
	 * Returns a xml constructed of all records below given curl
	 * 
	 * @param curl
	 * @param toString
	 * @return
	 * @throws AcsJCDBRecordDoesNotExistEx
	 * @throws AcsJCDBXMLErrorEx
	 */
public XMLHandler loadRecords(String curl, boolean toString) throws AcsJCDBRecordDoesNotExistEx, AcsJCDBXMLErrorEx {
    StopWatch sw = new StopWatch(m_logger);
    try {
        // create hierarchy of all nodes if it is not created yet 
        synchronized (this) {
            if (rootNode == null) {
                //no Error thrown
                rootNode = DALNode.getRoot(m_root);
            }
        }
        //no Error thrown
        String strFileCurl = curl;
        String strNodeCurl = "";
        DALNode curlNode = null;
        boolean isEmbeddedNode = false;
        while (strFileCurl != null) {
            curlNode = rootNode.findNode(strFileCurl);
            if (curlNode == null) {
                // Therefore we must move up toward the root node to find a valid parent xml node.
                if (strFileCurl.lastIndexOf('/') > 0) {
                    strNodeCurl = strFileCurl.substring(strFileCurl.lastIndexOf('/') + 1) + "/" + strNodeCurl;
                    strFileCurl = strFileCurl.substring(0, strFileCurl.lastIndexOf('/'));
                    isEmbeddedNode = true;
                } else {
                    strFileCurl = null;
                }
            } else {
                // curlNode and strFileCurl point to the node that has the relevant XML file 
                break;
            }
        }
        m_logger.log(AcsLogLevel.DEBUG, "loadRecords(curl=" + curl + "), strFileCurl=" + strFileCurl + ", strNodeCurl=" + strNodeCurl);
        // because the "embedded" node data will not be found in other XML files.
        if (strFileCurl == null || (isEmbeddedNode && !curlNode.hasXmlChild())) {
            AcsJCDBRecordDoesNotExistEx recordDoesNotExist = new AcsJCDBRecordDoesNotExistEx();
            recordDoesNotExist.setCurl(curl);
            throw recordDoesNotExist;
        }
        if (curlNode.isSimple()) {
            m_logger.log(AcsLogLevel.DEBUG, "loadRecords(curl=" + curl + "); curlNode '" + curlNode.name + "' is simple.");
            if (curl.equals(strFileCurl)) {
                return loadRecord(strFileCurl, toString);
            } else {
                XMLHandler xmlSolver = loadRecord(strFileCurl, false);
                try {
                    return xmlSolver.getChild(strNodeCurl);
                } catch (AcsJCDBRecordDoesNotExistEx e) {
                    e.setCurl(strFileCurl + e.getCurl());
                    throw e;
                }
            }
        }
        m_logger.log(AcsLogLevel.DEBUG, "loadRecords(curl=" + curl + "), curlNode is Complex");
        XMLHandler xmlSolver;
        try {
            //xmlSolver.startElement(null,null,"curl",new org.xml.sax.helpers.AttributesImpl);
            if (curl.equals(strFileCurl)) {
                xmlSolver = new XMLHandler(toString, m_logger);
                xmlSolver.setAutoCloseStartingElement(false);
                parseNode(curlNode, xmlSolver, "");
                //xmlSolver.closeElement();
                return xmlSolver;
            } else {
                //here we must return the node inside the xmlSolver with curl= strNodeCurl		
                xmlSolver = new XMLHandler(false, m_logger);
                xmlSolver.setMarkArrays(1);
                xmlSolver.setAutoCloseStartingElement(false);
                parseNode(curlNode, xmlSolver, "");
                return xmlSolver.getChild(strNodeCurl);
            }
        } catch (AcsJCDBRecordDoesNotExistEx e) {
            e.setCurl(strFileCurl + e.getCurl());
            throw e;
        } catch (SAXParseException e) {
            AcsJCDBXMLErrorEx cdbxmlErr = new AcsJCDBXMLErrorEx();
            cdbxmlErr.setErrorString("SAXParseException: " + e.getMessage());
            cdbxmlErr.setCurl(curl);
            cdbxmlErr.setFilename(e.getSystemId() + ", line=" + e.getLineNumber());
            throw cdbxmlErr;
        } catch (Throwable thr) {
            AcsJCDBXMLErrorEx cdbxmlErr = new AcsJCDBXMLErrorEx(thr);
            cdbxmlErr.setCurl(curl);
            throw cdbxmlErr;
        }
    } finally {
        long lt = sw.getLapTimeMillis();
        m_logger.finest("Time spent in loadRecords(" + curl + "): " + lt);
    }
}
Also used : SAXParseException(org.xml.sax.SAXParseException) AcsJCDBRecordDoesNotExistEx(alma.cdbErrType.wrappers.AcsJCDBRecordDoesNotExistEx) AcsJCDBXMLErrorEx(alma.cdbErrType.wrappers.AcsJCDBXMLErrorEx) StopWatch(alma.acs.util.StopWatch)

Example 25 with SAXParseException

use of org.xml.sax.SAXParseException in project Activiti by Activiti.

the class BpmnDeploymentListener method parse.

protected Document parse(File artifact) throws Exception {
    if (dbf == null) {
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
    }
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(new ErrorHandler() {

        public void warning(SAXParseException exception) throws SAXException {
        }

        public void error(SAXParseException exception) throws SAXException {
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    return db.parse(artifact);
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException)

Aggregations

SAXParseException (org.xml.sax.SAXParseException)365 SAXException (org.xml.sax.SAXException)170 IOException (java.io.IOException)131 DocumentBuilder (javax.xml.parsers.DocumentBuilder)73 InputSource (org.xml.sax.InputSource)69 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)68 Document (org.w3c.dom.Document)64 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)56 ErrorHandler (org.xml.sax.ErrorHandler)52 InputStream (java.io.InputStream)36 File (java.io.File)34 ArrayList (java.util.ArrayList)33 FileInputStream (java.io.FileInputStream)31 FileNotFoundException (java.io.FileNotFoundException)31 Element (org.w3c.dom.Element)30 StringReader (java.io.StringReader)21 NodeList (org.w3c.dom.NodeList)21 URL (java.net.URL)20 Test (org.junit.jupiter.api.Test)19 Node (org.w3c.dom.Node)19