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.fosstrak.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Parses the input into a DOM. If a schema is given, the input is also
 * validated against this schema. The schema may be null.
 *//* www  . j  a v  a 2s.  c  o  m*/
private Document parseInput(InputStream in, Schema schema)
        throws InternalBusinessException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setSchema(schema);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
                LOG.warn("warning while parsing XML input: " + e.getMessage());
            }

            public void fatalError(SAXParseException e) throws SAXException {
                LOG.error("non-recovarable error while parsing XML input: " + e.getMessage());
                throw e;
            }

            public void error(SAXParseException e) throws SAXException {
                LOG.error("error while parsing XML input: " + e.getMessage());
                throw e;
            }
        });
        Document document = builder.parse(in);
        LOG.debug("payload successfully parsed as XML document");
        if (LOG.isDebugEnabled()) {
            logDocument(document);
        }
        return document;
    } catch (ParserConfigurationException e) {
        throw new InternalBusinessException("unable to configure document builder to parse XML input", e);
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * Given a dom and a schema, checks that the dom validates against the schema 
 * of the validation errors instead/*from   ww  w. j a  v a 2  s.c om*/
 * @param validationErrors
 * @throws IOException 
 * @throws SAXException 
 */
protected void checkValidationErrors(Document dom, Schema schema) throws SAXException, IOException {
    final Validator validator = schema.newValidator();
    final List<Exception> validationErrors = new ArrayList<Exception>();
    validator.setErrorHandler(new ErrorHandler() {

        public void warning(SAXParseException exception) throws SAXException {
            System.out.println(exception.getMessage());
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            validationErrors.add(exception);
        }

        public void error(SAXParseException exception) throws SAXException {
            validationErrors.add(exception);
        }

    });
    validator.validate(new DOMSource(dom));
    if (validationErrors != null && validationErrors.size() > 0) {
        StringBuilder sb = new StringBuilder();
        for (Exception ve : validationErrors) {
            sb.append(ve.getMessage()).append("\n");
        }
        fail(sb.toString());
    }
}

From source file:org.impalaframework.util.XMLDomUtils.java

/**
 * Validates document of given description using w3c.org schema validation
 * @param document the DOM document instance
 * @param description a description of the document, typically name or path
 * @param xsdResource the schema resource used for validation
 *//*w w w.jav a2s  .  co m*/
public static void validateDocument(Document document, String description, Resource xsdResource) {

    Assert.notNull(xsdResource, "xsdResource cannot be null");

    if (!xsdResource.exists()) {
        throw new ExecutionException(
                "Cannot validate document as xsdResource '" + xsdResource + "' does not exist");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Validating using schema resource " + xsdResource.getDescription());
        }
    }

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {
        InputStream inputStream = xsdResource.getInputStream();
        Source source = new StreamSource(inputStream);

        Schema schema = factory.newSchema(source);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (SAXParseException e) {
        throw new ExecutionException("Error on " + e.getLineNumber() + ", column " + e.getColumnNumber()
                + " in " + description + ": " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new ExecutionException("Error parsing " + description + ": " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.intermine.modelviewer.jaxb.ConfigParser.java

/**
 * This method is a legacy of trying to persuade JAXB to read Intermine
 * files of all types, using all sorts of tricks to get it to work with
 * documents without schema declarations, documents with schema declarations,
 * documents without proper namespace declarations etc.
 * <p>It is no longer used, but remains here for the lessons learned.</p>
 * // w ww  .  ja  v  a 2  s  .  c  o m
 * @param context The type of objects expected from the XML file.
 * @param file The file to load.
 * 
 * @return The Object created as a result of reading the file.
 * Its type will depend on <code>context</code>.
 * 
 * @throws JAXBException if there is a problem when unmarshalling.
 * @throws SAXException if there is a problem parsing with SAX.
 * @throws ParserConfigurationException if there is a configuration problem with
 * the SAX system.
 * @throws IOException if there is a low level I/O problem.
 */
protected Object twoPassUnmarshall(Context context, File file)
        throws JAXBException, SAXException, ParserConfigurationException, IOException {
    Unmarshaller unmarshall = jaxbContexts.get(context).createUnmarshaller();
    //unmarshall.setSchema(schemas.get(context));

    try {
        Source source = getSource(file, null);
        return unmarshall.unmarshal(source);
    } catch (UnmarshalException e) {
        if (e.getCause() == null) {
            logger.warn("Failed to unmarshall " + file + ": " + e.getMessage());
        } else {
            try {
                throw e.getCause();
            } catch (SAXParseException e2) {
                logger.warn("Failed to unmarshall " + file + ": " + e2.getMessage());
                logger.debug("", e2);
            } catch (Throwable e2) {
                logger.warn("Unexpected root exception while unmarshalling " + file + ": "
                        + e2.getClass().getName());
                throw e;
            }
        }

        /*
         * This one would try to replace namespaces for JAXB. Unfortunately this
         * too is too strict.
         * 
        String namespace = namespaces.get(context);
                
        // Try filtering the XML by adding the appropriate namespace.
        try {
        Source source = getSource(file, namespace);
        return unmarshall.unmarshal(source);
        } catch (UnmarshalException e2) {
        // Throw the original exception - it's really the one that nags
        // about the namespace.
        throw e;
        }
        */

        return saxParse(context, file);
    }
}

From source file:org.jajuk.base.Collection.java

/**
 * parsing warning./*from www  . ja va2s  .c  om*/
 *
 * @param spe 
 * @throws SAXException the SAX exception
 */
@Override
@SuppressWarnings("ucd")
//NOSONAR
public void warning(SAXParseException spe) throws SAXException {
    throw new SAXException(Messages.getErrorMessage(5) + " / " + spe.getSystemId() + "/" + spe.getLineNumber()
            + "/" + spe.getColumnNumber() + " : " + spe.getMessage());
}

From source file:org.jajuk.base.Collection.java

/**
 * parsing error./*w  w w .  j ava2  s.c  om*/
 *
 * @param spe 
 * @throws SAXException the SAX exception
 */
@Override
@SuppressWarnings("ucd")
public void error(SAXParseException spe) throws SAXException {
    throw new SAXException(Messages.getErrorMessage(5) + " / " + spe.getSystemId() + "/" + spe.getLineNumber()
            + "/" + spe.getColumnNumber() + " : " + spe.getMessage());
}

From source file:org.jajuk.base.Collection.java

/**
 * parsing fatal error./*  w  w  w . j a v  a2  s. c om*/
 *
 * @param spe 
 * @throws SAXException the SAX exception
 */
@Override
@SuppressWarnings("ucd")
public void fatalError(SAXParseException spe) throws SAXException {
    throw new SAXException(Messages.getErrorMessage(5) + " / " + spe.getSystemId() + "/" + spe.getLineNumber()
            + "/" + spe.getColumnNumber() + " : " + spe.getMessage());
}

From source file:org.jboss.elasticsearch.river.remote.sitemap.SiteMapParser.java

/**
 * Parse the given XML content.//from w  w w .  j  a  v a 2  s  .co  m
 * 
 * @param sitemapUrl
 * @param is
 * @throws UnknownFormatException
 */
private AbstractSiteMap processXml(URL sitemapUrl, InputSource is) throws UnknownFormatException {

    Document doc = null;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                logger.warn("Sitemap XML warning: " + exception.getMessage());
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                logger.warn("Sitemap XML fatalError: " + exception.getMessage());
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                logger.warn("Sitemap XML error: " + exception.getMessage());

            }
        });
        doc = db.parse(is);
    } catch (Exception e) {
        throw new UnknownFormatException("Error parsing XML for " + sitemapUrl);
    }

    // See if this is a sitemap index
    NodeList nodeList = doc.getElementsByTagName("sitemapindex");
    if (nodeList.getLength() > 0) {
        nodeList = doc.getElementsByTagName("sitemap");
        return parseSitemapIndex(sitemapUrl, nodeList);
    } else if (doc.getElementsByTagName("urlset").getLength() > 0) {
        // This is a regular Sitemap
        return parseXmlSitemap(sitemapUrl, doc);
    } else if (doc.getElementsByTagName("link").getLength() > 0) {
        // Could be RSS or Atom
        return parseSyndicationFormat(sitemapUrl, doc);
    }
    throw new UnknownFormatException("Unknown XML format for " + sitemapUrl);
}

From source file:org.kitodo.editor.XMLEditor.java

/**
 * Check and return whether the given String 'xmlCode' contains well formed XML
 * code or not./*  w w w .  j av a  2 s .  co m*/
 *
 * @param facesContext
 *            the current FacesContext
 * @param uiComponent
 *            the component containing the String that is being validated
 * @param xmlCode
 *            XML code that will be validated
 * @return whether 'xmlCode' is well formed or not
 */
public boolean validateXMLConfiguration(FacesContext facesContext, UIComponent uiComponent, String xmlCode) {
    if (!Objects.equals(documentBuilder, null)) {
        InputSource inputSource = new InputSource(new StringReader(xmlCode));
        try {
            documentBuilder.parse(inputSource);
            return true;
        } catch (SAXParseException e) {
            // parse method throwing an SAXParseException means given xml code is not well
            // formed!
            String errorString = "Error while parsing XML: line = " + e.getLineNumber() + ", column = "
                    + e.getColumnNumber() + ": " + e.getMessage();
            FacesMessage errorMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "XML parsing error",
                    errorString);
            facesContext.addMessage(uiComponent.getClientId(), errorMessage);
            logger.error(errorString);
            return false;
        } catch (SAXException e) {
            logger.error("SAXException: " + e.getMessage());
            return false;
        } catch (IOException e) {
            logger.error("IOException: " + e.getMessage());
            return false;
        }
    } else {
        logger.error("ERROR: document builder is null!");
        return false;
    }
}

From source file:org.kuali.core.db.torque.KualiXmlToAppData.java

/**
 * Parses a XML input file and returns a newly created and
 * populated Database structure.//from w w  w  . jav  a2 s .  c o  m
 *
 * @param xmlFile The input file to parse.
 * @return Database populated by <code>xmlFile</code>.
 */
public KualiDatabase parseFile(String xmlFile) throws EngineException {
    try {
        // in case I am missing something, make it obvious
        if (!firstPass) {
            throw new Error("No more double pass");
        }
        // check to see if we alread have parsed the file
        if ((alreadyReadFiles != null) && alreadyReadFiles.contains(xmlFile)) {
            return database;
        } else if (alreadyReadFiles == null) {
            alreadyReadFiles = new Vector(3, 1);
        }

        // remember the file to avoid looping
        alreadyReadFiles.add(xmlFile);

        currentXmlFile = xmlFile;

        saxFactory.setValidating(false);
        SAXParser parser = saxFactory.newSAXParser();

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(xmlFile);
        } catch (FileNotFoundException fnfe) {
            throw new FileNotFoundException(new File(xmlFile).getAbsolutePath());
        }
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        try {
            log.info("Parsing file: '" + (new File(xmlFile)).getName() + "'");
            InputSource is = new InputSource(bufferedInputStream);
            is.setSystemId(xmlFile);
            parser.parse(is, this);
        } finally {
            bufferedInputStream.close();
        }
    } catch (SAXParseException e) {
        throw new EngineException("Sax error on line " + e.getLineNumber() + " column " + e.getColumnNumber()
                + " : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new EngineException(e);
    }
    if (!isExternalSchema) {
        firstPass = false;
    }
    database.doFinalInitialization();
    return database;
}