Example usage for org.xml.sax SAXParseException getLineNumber

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

Introduction

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

Prototype

public int getLineNumber() 

Source Link

Document

The line number of the end of the text where the exception occurred.

Usage

From source file:org.eclim.plugin.core.util.XmlUtils.java

/**
 * Validate the supplied xml file.//from w w w. ja va  2s .  c  o m
 *
 * @param project The project name.
 * @param filename The file path to the xml file.
 * @param schema True to use schema validation relying on the
 * xsi:schemaLocation attribute of the document.
 * @param handler The content handler to use while parsing the file.
 * @return A possibly empty list of errors.
 */
public static List<Error> validateXml(String project, String filename, boolean schema, DefaultHandler handler)
        throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    if (schema) {
        factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    }

    SAXParser parser = factory.newSAXParser();

    filename = ProjectUtils.getFilePath(project, filename);
    filename = filename.replace('\\', '/');

    ErrorAggregator errorHandler = new ErrorAggregator(filename);
    EntityResolver entityResolver = new EntityResolver(FileUtils.getFullPath(filename));
    try {
        parser.parse(new File(filename), getHandler(handler, errorHandler, entityResolver));
    } catch (SAXParseException spe) {
        ArrayList<Error> errors = new ArrayList<Error>();
        errors.add(new Error(spe.getMessage(), filename, spe.getLineNumber(), spe.getColumnNumber(), false));
        return errors;
    }

    return errorHandler.getErrors();
}

From source file:org.eclim.plugin.core.util.XmlUtils.java

/**
 * Validate the supplied xml file against the specified xsd.
 *
 * @param project The project name.//from w  w  w .j a v  a 2  s .  co  m
 * @param filename The file path to the xml file.
 * @param schema The file path to the xsd.
 * @return A possibly empty array of errors.
 */
public static List<Error> validateXml(String project, String filename, String schema) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setFeature("http://apache.org/xml/features/validation/schema", true);
    factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    SAXParser parser = factory.newSAXParser();
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    if (!schema.startsWith("file:")) {
        schema = "file://" + schema;
    }
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema);
    parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            schema.replace('\\', '/'));

    filename = ProjectUtils.getFilePath(project, filename);
    filename = filename.replace('\\', '/');

    ErrorAggregator errorHandler = new ErrorAggregator(filename);
    EntityResolver entityResolver = new EntityResolver(FileUtils.getFullPath(filename));
    try {
        parser.parse(new File(filename), getHandler(null, errorHandler, entityResolver));
    } catch (SAXParseException spe) {
        ArrayList<Error> errors = new ArrayList<Error>();
        errors.add(new Error(spe.getMessage(), filename, spe.getLineNumber(), spe.getColumnNumber(), false));
        return errors;
    }

    return errorHandler.getErrors();
}

From source file:org.eclipse.rdf4j.rio.trix.TriXParser.java

private void parse(InputSource inputStreamOrReader) throws IOException, RDFParseException, RDFHandlerException {
    clear();/*from  w  ww .j a  v  a2 s .  c o m*/

    try {
        if (rdfHandler != null) {
            rdfHandler.startRDF();
        }

        XMLReader xmlReader;

        if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) {
            xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER);
        } else {
            xmlReader = XMLReaderFactory.createXMLReader();
        }

        xmlReader.setErrorHandler(this);

        saxParser = new SimpleSAXParser(xmlReader);
        saxParser.setPreserveWhitespace(true);
        saxParser.setListener(new TriXSAXHandler());

        saxParser.parse(inputStreamOrReader);
    } catch (SAXParseException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e, e.getLineNumber(), e.getColumnNumber());
        } else {
            reportFatalError(wrappedExc, e.getLineNumber(), e.getColumnNumber());
        }
    } catch (SAXException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e);
        } else if (wrappedExc instanceof RDFParseException) {
            throw (RDFParseException) wrappedExc;
        } else if (wrappedExc instanceof RDFHandlerException) {
            throw (RDFHandlerException) wrappedExc;
        } else {
            reportFatalError(wrappedExc);
        }
    } finally {
        clear();
    }

    if (rdfHandler != null) {
        rdfHandler.endRDF();
    }
}

From source file:org.ecoinformatics.emltest.SaxValidateTest.java

/**
 * Test if XML documents are valid with respect to their schemas.
 *///  w w w .j  a va 2 s  .c  o m
public void testSchemaValid() {
    SAXValidate test = new SAXValidate(true);
    assertTrue(test != null);

    File testDir = new File(TEST_DIR);
    Vector fileList = getXmlFiles(testDir);

    for (int i = 0; i < fileList.size(); i++) {
        File testFile = (File) fileList.elementAt(i);
        try {
            System.err.println("Validating file: " + testFile.getName());
            FileReader reader = new FileReader(testFile);
            String namespace = EMLParserServlet.findNamespace(reader);
            reader.close();
            test.runTest(new FileReader(testFile), namespace);
        } catch (Exception e) {
            if (e instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException) e;
                System.err.println("Error on line: " + spe.getLineNumber());
            }
            e.printStackTrace(System.err);
            fail("Document NOT valid!\n\n" + e.getClass().getName() + "(" + e.getMessage() + ")");
        }
    }
}

From source file:org.exist.validation.ValidationReport.java

private ValidationReportItem createValidationReportItem(int type, SAXParseException exception) {

    final ValidationReportItem vri = new ValidationReportItem();
    vri.setType(type);/*w w w .  ja  va2 s .com*/
    vri.setLineNumber(exception.getLineNumber());
    vri.setColumnNumber(exception.getColumnNumber());
    vri.setMessage(exception.getMessage());
    vri.setPublicId(exception.getPublicId());
    vri.setSystemId(exception.getSystemId());
    return vri;
}

From source file:org.geoserver.csw.CSWTestSupport.java

/**
 * Validates a document against the/*from w ww  . j a v  a2  s .c o  m*/
 * 
 * @param dom
 * @param configuration
 */
protected void checkValidationErrors(Document dom, Configuration configuration) throws Exception {
    Parser p = new Parser(configuration);
    p.setValidating(true);
    p.parse(new DOMSource(dom));

    if (!p.getValidationErrors().isEmpty()) {
        for (Iterator e = p.getValidationErrors().iterator(); e.hasNext();) {
            SAXParseException ex = (SAXParseException) e.next();
            System.out.println(ex.getLineNumber() + "," + ex.getColumnNumber() + " -" + ex.toString());
        }
        fail("Document did not validate.");
    }
}

From source file:org.geoserver.wms.web.data.AbstractStylePage.java

private String sldErrorWithLineNo(Exception e) {
    if (e instanceof SAXParseException) {
        SAXParseException se = (SAXParseException) e;
        return "line " + se.getLineNumber() + ": " + e.getLocalizedMessage();
    }/*w  w w.ja  va 2 s  . c o m*/
    String message = e.getLocalizedMessage();
    if (message != null) {
        return message;
    } else {
        return new ParamResourceModel("genericError", this).getString();
    }
}

From source file:org.geotools.styling.css.AbstractIntegrationTest.java

@Test
public void translateTest() throws Exception {
    String css = FileUtils.readFileToString(file);
    if (!exclusiveRulesEnabled) {
        css = "@mode \"Simple\";\n" + css;
    }/*  w w w. ja v a2s.  c o  m*/

    File sldFile = new File(file.getParentFile(),
            FilenameUtils.getBaseName(file.getName()) + (exclusiveRulesEnabled ? "" : "-first") + ".sld");
    if (!sldFile.exists()) {
        Stylesheet ss = CssParser.parse(css);
        CssTranslator tx = new CssTranslator();
        Style style = tx.translate(ss);
        writeStyle(style, sldFile);
        // throw new IllegalStateException("Could not locate sample sld file " +
        // sldFile.getPath());
    }

    Style actual = cssToSld(css);
    File sldFile2 = new File("./target/css", FilenameUtils.getBaseName(file.getName()) + ".sld");
    writeStyle(actual, sldFile2);
    String actualSld = FileUtils.readFileToString(sldFile2);

    List validationErrors = validateSLD(actualSld);
    if (!validationErrors.isEmpty()) {
        System.err.println("Validation failed, errors are: ");
        for (Object e : validationErrors) {
            if (e instanceof SAXParseException) {
                SAXParseException se = (SAXParseException) e;
                System.out.println("line " + se.getLineNumber() + ": " + se.getLocalizedMessage());
            } else {
                System.out.println(e);
            }

        }
        System.err.println("Validation failed, the two files are: " + sldFile.getAbsolutePath() + " "
                + sldFile2.getAbsolutePath());
        fail("Validation failed");
    }

    String expectedSld = FileUtils.readFileToString(sldFile);
    StyledLayerDescriptor expectedSLD = parseToSld(expectedSld);
    StyledLayerDescriptor actualSLD = parseToSld(actualSld);
    //        Document expectedDom = XMLUnit.buildControlDocument(expectedSld);
    //        Document actualDom = XMLUnit.buildControlDocument(actualSld);
    //        Diff diff = new Diff(expectedDom, actualDom);
    //        if (!diff.identical()) {
    if (!expectedSLD.equals(actualSLD)) {
        String message = "Comparison failed, the two files are: " + sldFile.getAbsolutePath() + " "
                + sldFile2.getAbsolutePath();
        System.err.println(message);
        fail(message);
    }
    //        }
}

From source file:org.goobi.eadmgr.Cli.java

@Override
public void handleException(Exception ex) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);// ww  w.j a  v  a  2s. c  o  m

    String msg = sw.toString();

    if (logger != null) {
        if (ex instanceof SAXParseException) {
            SAXParseException sax = (SAXParseException) ex;
            logger.error(ex.getMessage() + " (at line " + sax.getLineNumber() + ")");
            return;
        } else {
            logger.error(msg);
        }
    } else {
        println(msg);
    }

    println(PROMPT_HINT);
}

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
 *//*from www .ja  v  a 2  s . c  o  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);
    }
}