Example usage for org.xml.sax SAXParseException getMessage

List of usage examples for org.xml.sax SAXParseException getMessage

Introduction

In this page you can find the example usage for org.xml.sax SAXParseException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Return a detail message for this exception.

Usage

From source file:org.opencms.util.ant.CmsAntTaskReadXMLProperty.java

/**
 * Run the task.<p>// w w  w .j  a v a 2s .c  om
 * 
 * Sets the given property to <code>__ABORT__</code> if canceled, or to a list of selected
 * modules if not.<p>
 * 
 * @throws BuildException if something goes wrong
 * 
 * @see org.apache.tools.ant.Task#execute()
 */
public void execute() throws BuildException {

    boolean isAttr = ((m_attribute != null) && (m_attribute.trim().length() > 0));

    // instantiate Digester and enable XML validation
    Digester digester = new Digester();
    digester.setValidating(false);
    digester.setEntityResolver(null);
    digester.setRuleNamespaceURI(null);
    digester.setErrorHandler(new ErrorHandler() {

        /**
         * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
         */
        public void error(SAXParseException exception) {

            log(exception.getMessage(), exception.getLineNumber());
        }

        /**
         * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
         */
        public void fatalError(SAXParseException exception) {

            log(exception.getMessage(), exception.getLineNumber());
        }

        /**
         * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
         */
        public void warning(SAXParseException exception) {

            log(exception.getMessage(), exception.getLineNumber());
        }

    });

    // add this class to the Digester
    digester.push(this);
    if (!isAttr) {
        digester.addCallMethod(m_element, "setValue", 0);
    } else {
        digester.addCallMethod(m_element, "setValue", 1);
        digester.addCallParam(m_element, 0, m_attribute);
    }
    // start the parsing process
    try {
        digester.parse(new File(getXmlFile()));
    } catch (Exception e) {
        throw new BuildException(e);
    }

    getProject().setProperty(m_property, m_value.substring(1));
}

From source file:org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGeneratorTest.java

private void verifyXmlFiles(final Collection<File> xmlFiles) throws Exception {
    ErrorHandler errorHandler = new ErrorHandler() {

        @Override//from w  w  w  . j  ava  2  s  . c  om
        public void warning(final SAXParseException exception) throws SAXException {
            fail("Generated blueprint xml is not well formed " + exception.getMessage());
        }

        @Override
        public void fatalError(final SAXParseException exception) throws SAXException {
            fail("Generated blueprint xml is not well formed " + exception.getMessage());
        }

        @Override
        public void error(final SAXParseException exception) throws SAXException {
            fail("Generated blueprint xml is not well formed " + exception.getMessage());
        }
    };

    for (File file : xmlFiles) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(errorHandler);
        builder.parse(new InputSource(file.getPath()));
    }

}

From source file:org.openhab.tools.analysis.checkstyle.EshInfXmlValidationCheck.java

private void validateXmlAgainstSchema(File xmlFile, Schema schema) {
    if (schema != null) {
        try {//  w w w . jav  a 2 s. com
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(xmlFile));
        } catch (SAXParseException exception) {
            String message = exception.getMessage();
            // Removing the type of the logged message (For example - "cvc-complex-type.2.4.b: ...").
            message = message.substring(message.indexOf(":") + 2);
            int lineNumber = exception.getLineNumber();
            log(lineNumber, message, xmlFile.getPath());
        } catch (IOException | SAXException e) {
            logger.error("Problem occurred while parsing the file " + xmlFile.getName(), e);
        }
    } else {
        logger.warn("XML validation will be skipped as the schema file download failed.");
    }
}

From source file:org.openmrs.module.radiology.report.template.XsdMrrtReportTemplateValidator.java

/**
 * @see MrrtReportTemplateValidator#validate(String)
 *//*from  ww  w . j ava 2 s  . co  m*/
@Override
public void validate(String mrrtTemplate) throws IOException {

    final Document document = Jsoup.parse(mrrtTemplate, "");
    final Elements metatags = document.getElementsByTag("meta");
    ValidationResult validationResult = metaTagsValidationEngine.run(metatags);

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    final Validator validator;
    try (InputStream in = IOUtils.toInputStream(mrrtTemplate)) {
        schema = factory.newSchema(getSchemaFile());
        validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }
        });
        validator.validate(new StreamSource(in));
        validationResult.assertOk();
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
        throw new APIException("radiology.report.template.validation.error", null, e);
    }
}

From source file:org.openrdf.http.server.repository.statements.StatementsController.java

/**
 * Process several actions as a transaction.
 *//*  w w  w  . j a  v a  2  s.  c o m*/
private ModelAndView getTransactionResultResult(Repository repository, HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ClientHTTPException, ServerHTTPException, HTTPException {
    InputStream in = request.getInputStream();
    try {
        logger.debug("Processing transaction...");

        TransactionReader reader = new TransactionReader();
        Iterable<? extends TransactionOperation> txn = reader.parse(in);

        RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
        synchronized (repositoryCon) {
            repositoryCon.begin();

            for (TransactionOperation op : txn) {
                op.execute(repositoryCon);
            }

            repositoryCon.commit();
        }
        logger.debug("Transaction processed ");

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (SAXParseException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    } catch (SAXException e) {
        throw new ServerHTTPException("Failed to parse transaction data: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ServerHTTPException("Failed to read data: " + e.getMessage(), e);
    } catch (RepositoryException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    }
}

From source file:org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogHelper.java

public void importSchema(File mondrianFile, String databaseConnection, String parameters) {

    try {/*from   ww w  .jav  a  2 s  . c  o m*/
        String datasourceInfo = "Provider=mondrian;DataSource=" + databaseConnection; //$NON-NLS-1$
        if (!StringUtils.isEmpty(parameters)) {
            datasourceInfo = parameters;
        }

        // Note: Mondrian parameters could be validated here and throw subsequent exception if they do not conform to
        // spec.

        FileInputStream parsingInputStream = new FileInputStream(mondrianFile);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(parsingInputStream);
        NodeList schemas = document.getElementsByTagName("Schema"); //$NON-NLS-1$
        Node schema = schemas.item(0);
        if (schema == null) {
            throw new SAXParseException("", null); // Generic schema error message will be provided at catch statement.
        }
        Node name = schema.getAttributes().getNamedItem("name"); //$NON-NLS-1$
        String catalogName = name.getTextContent();
        parsingInputStream.close();

        FileInputStream schemaInputStream = new FileInputStream(mondrianFile);
        org.pentaho.platform.plugin.services.importexport.legacy.MondrianCatalogRepositoryHelper helper = new org.pentaho.platform.plugin.services.importexport.legacy.MondrianCatalogRepositoryHelper(
                PentahoSystem.get(IUnifiedRepository.class));
        helper.addSchema(schemaInputStream, catalogName, datasourceInfo);

        reInit(PentahoSessionHolder.getSession());

        flushCacheForCatalog(catalogName, PentahoSessionHolder.getSession());
    } catch (SAXParseException e) {
        throw new MondrianCatalogServiceException(
                Messages.getInstance().getString("MondrianCatalogHelper.ERROR_0018_IMPORT_SCHEMA_ERROR")); //$NON-NLS-1$
    } catch (Exception e) {
        throw new MondrianCatalogServiceException(
                Messages.getInstance().getString("MondrianCatalogHelper.ERROR_0008_ERROR_OCCURRED"), //$NON-NLS-1$
                Reason.valueOf(e.getMessage()));
    }
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.LoggingErrorHandler.java

/**
 * Receive notification of a warning. <p/> <p>SAX parsers will use this method to report conditions that are not
 * errors or fatal errors as defined by the XML recommendation.  The default behaviour is to take no action.</p> <p/>
 * <p>The SAX parser must continue to provide normal parsing events after invoking this method: it should still be
 * possible for the application to process the document through to the end.</p> <p/> <p>Filters may use this method to
 * report other, non-XML warnings as well.</p>
 *
 * @param exception The warning information encapsulated in a SAX parse exception.
 * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
 * @see org.xml.sax.SAXParseException/*from   w  w  w .ja v a2s.c  o  m*/
 */
public void warning(final SAXParseException exception) throws SAXException {
    if (logContext.isDebugEnabled()) {
        if (exception.getMessage().startsWith("URI was not reported to parser for entity")) {
            // ignore that one. It is stupid! We do not use DTDs but old parsers like
            // the GNU thing complain about it ..
            return;
        }
        logContext.debug("Parser-Warning", exception);
    }
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.LoggingErrorHandler.java

/**
 * Receive notification of a recoverable error. <p/> <p>This corresponds to the definition of "error" in section 1.2
 * of the W3C XML 1.0 Recommendation.  For example, a validating parser would use this callback to report the
 * violation of a validity constraint.  The default behaviour is to take no action.</p> <p/> <p>The SAX parser must
 * continue to provide normal parsing events after invoking this method: it should still be possible for the
 * application to process the document through to the end. If the application cannot do so, then the parser should
 * report a fatal error even if the XML recommendation does not require it to do so.</p> <p/> <p>Filters may use this
 * method to report other, non-XML errors as well.</p>
 *
 * @param exception The error information encapsulated in a SAX parse exception.
 * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
 * @see org.xml.sax.SAXParseException/*  w  ww  . j a  v  a 2 s.c o  m*/
 */
public void error(final SAXParseException exception) throws SAXException {
    if (logContext.isWarnEnabled()) {
        if (logContext.isDebugEnabled()) {
            logContext.warn("Recoverable Parser-Error", exception);
        } else {
            logContext.warn("Recoverable Parser-Error:" + exception.getMessage());
        }
    }
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.LoggingErrorHandler.java

/**
 * Receive notification of a non-recoverable error. <p/> <p><strong>There is an apparent contradiction between the
 * documentation for this method and the documentation for {@link org.xml.sax.ContentHandler#endDocument}. Until this
 * ambiguity is resolved in a future major release, clients should make no assumptions about whether endDocument()
 * will or will not be invoked when the parser has reported a fatalError() or thrown an exception.</strong></p> <p/>
 * <p>This corresponds to the definition of "fatal error" in section 1.2 of the W3C XML 1.0 Recommendation.  For
 * example, a parser would use this callback to report the violation of a well-formedness constraint.</p> <p/> <p>The
 * application must assume that the document is unusable after the parser has invoked this method, and should continue
 * (if at all) only for the sake of collecting additional error messages: in fact, SAX parsers are free to stop
 * reporting any other events once this method has been invoked.</p>
 *
 * @param exception The error information encapsulated in a SAX parse exception.
 * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
 * @see org.xml.sax.SAXParseException/*w  ww.ja  va  2s .  c om*/
 */
public void fatalError(final SAXParseException exception) throws SAXException {
    if (logContext.isErrorEnabled()) {
        if (logContext.isDebugEnabled()) {
            logContext.error("Fatal Parser-Error", exception);
        } else {
            logContext.error("Fatal Parser-Error:" + exception.getMessage());
        }
    }
}

From source file:org.plasma.sdo.xml.DefaultErrorHandler.java

public void error(SAXParseException e) throws SAXException {
    String msg = "line:column[" + e.getLineNumber() + ":" + e.getColumnNumber() + "]";
    msg += " - " + e.getMessage();
    if (options.isFailOnValidationError()) {
        throw new SAXParseException(msg, new ErrorLocator(e));
    } else {//from  ww  w .ja  v  a  2s  .  c om
        if (options.getValidationLog() != null) {
            options.getValidationLog().error(msg);
        } else
            log.error(msg);
    }
}