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.dita.dost.module.reader.AbstractReaderModule.java

/**
 * Read a file and process it for list information.
 *
 * @param ref system path of the file to process
 * @param parseFile file to parse, may be {@code null}
 * @throws DITAOTException if processing failed
 *//*from   w  ww .  ja  va2  s . co m*/
void readFile(final Reference ref, final URI parseFile) throws DITAOTException {
    currentFile = ref.filename;
    assert currentFile.isAbsolute();
    final URI src = parseFile != null ? parseFile : currentFile;
    assert src.isAbsolute();
    final URI rel = tempFileNameScheme.generateTempFileName(currentFile);
    outputFile = new File(job.tempDirURI.resolve(rel));
    final File outputDir = outputFile.getParentFile();
    if (!outputDir.exists() && !outputDir.mkdirs()) {
        logger.error("Failed to create output directory " + outputDir.getAbsolutePath());
        return;
    }
    validateMap = Collections.emptyMap();
    defaultValueMap = Collections.emptyMap();
    logger.info("Processing " + currentFile + " to " + outputFile.toURI());
    final String[] params = { currentFile.toString() };

    // Verify stub for current file is in Job
    final FileInfo fi = job.getFileInfo(currentFile);
    if (fi == null) {
        final FileInfo stub = new FileInfo.Builder().src(currentFile).uri(rel).result(currentFile)
                .isInput(currentFile.equals(rootFile)).build();
        job.add(stub);
    }

    //        InputSource in = null;
    Result out = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        final SAXTransformerFactory stf = (SAXTransformerFactory) tf;
        final TransformerHandler serializer = stf.newTransformerHandler();

        XMLReader parser = getXmlReader(ref.format);
        XMLReader xmlSource = parser;
        for (final XMLFilter f : getProcessingPipe(currentFile)) {
            f.setParent(xmlSource);
            f.setEntityResolver(CatalogUtils.getCatalogResolver());
            xmlSource = f;
        }

        try {
            final LexicalHandler lexicalHandler = new DTDForwardHandler(xmlSource);
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
            parser.setFeature("http://xml.org/sax/features/lexical-handler", true);
        } catch (final SAXNotRecognizedException e) {
        }

        //            in = new InputSource(src.toString());
        out = new StreamResult(new FileOutputStream(outputFile));
        serializer.setResult(out);
        xmlSource.setContentHandler(serializer);
        xmlSource.parse(src.toString());

        if (listFilter.isValidInput()) {
            processParseResult(currentFile);
            categorizeCurrentFile(ref);
        } else if (!currentFile.equals(rootFile)) {
            logger.warn(MessageUtils.getMessage("DOTJ021W", params).toString());
            failureList.add(currentFile);
        }
    } catch (final RuntimeException e) {
        throw e;
    } catch (final SAXParseException sax) {
        final Exception inner = sax.getException();
        if (inner != null && inner instanceof DITAOTException) {
            throw (DITAOTException) inner;
        }
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + sax.getMessage(), sax);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax);
        }
        failureList.add(currentFile);
    } catch (final FileNotFoundException e) {
        if (!exists(currentFile)) {
            if (currentFile.equals(rootFile)) {
                throw new DITAOTException(MessageUtils.getMessage("DOTA069F", params).toString(), e);
            } else if (processingMode == Mode.STRICT) {
                throw new DITAOTException(MessageUtils.getMessage("DOTX008E", params).toString(), e);
            } else {
                logger.error(MessageUtils.getMessage("DOTX008E", params).toString());
            }
        } else if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getMessage("DOTJ078F", params).toString()
                    + " Cannot load file: " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getMessage("DOTJ079E", params).toString()
                    + " Cannot load file: " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ079E", params).toString() + " Cannot load file: "
                    + e.getMessage());
        }
        failureList.add(currentFile);
    } catch (final Exception e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e);
        }
        failureList.add(currentFile);
    } finally {
        if (out != null) {
            try {
                close(out);
            } catch (final IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        if (failureList.contains(currentFile)) {
            FileUtils.deleteQuietly(outputFile);
        }
    }

    if (!listFilter.isValidInput() && currentFile.equals(rootFile)) {
        if (validate) {
            // stop the build if all content in the input file was filtered out.
            throw new DITAOTException(MessageUtils.getMessage("DOTJ022F", params).toString());
        } else {
            // stop the build if the content of the file is not valid.
            throw new DITAOTException(MessageUtils.getMessage("DOTJ034F", params).toString());
        }
    }

    doneList.add(currentFile);
    listFilter.reset();
    keydefFilter.reset();

}

From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java

public Map<String, Category> fromXMLToCategoriesMap(String xml) {
    try {// ww w .j  a v  a 2 s .  c o  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);

        final List<String> errors = new ArrayList<String>();
        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.WARNING,
                        "Warning parsing categories from Guvnor", exception);
            }

            public void error(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE,
                        "Error parsing categories from Guvnor", exception);
                errors.add(exception.getMessage());
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE,
                        "Error parsing categories from Guvnor", exception);
                errors.add(exception.getMessage());
            }
        });

        org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

        if (!errors.isEmpty()) {
            throw new IllegalStateException(
                    "Error parsing categories from guvnor. Check the log for errors' details.");
        }

        Map<String, Category> categories = new HashMap<String, Category>();

        //convert all catergories and add them to the list
        NodeList categoriesList = doc.getElementsByTagName("category");
        for (int i = 0; i < categoriesList.getLength(); i++) {
            Element element = (Element) categoriesList.item(i);
            Category category = new Category();

            NodeList pathNodes = element.getElementsByTagName("path");
            if (pathNodes.getLength() != 1) {
                throw new IllegalStateException(
                        "Malformed category. Expected 1 <path> tag, but found " + pathNodes.getLength());
            }
            Node pathNode = pathNodes.item(0);
            category.setPath(pathNode.getTextContent());

            NodeList refLinkNodes = element.getElementsByTagName("refLink");
            if (refLinkNodes.getLength() != 1) {
                throw new IllegalStateException(
                        "Malformed category. Expected 1 <refLink> tag, but found " + refLinkNodes.getLength());
            }
            Node refLinkNode = refLinkNodes.item(0);
            try {
                category.setRefLink(new URI(refLinkNode.getTextContent()));
            } catch (URISyntaxException e) {
                throw new RuntimeException("Error parsing categories xml", e);
            }

            categories.put(category.getPath(), category);
        }

        return categories;
    } catch (SAXException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    } catch (IOException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    }
}

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

/**
 * Validate the supplied xml file./*from ww  w.j  av a 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.//  w w  w .  ja 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.http.server.repository.statements.StatementsController.java

/**
 * Process several actions as a transaction.
 *///from   w  ww  .  j av  a2s.c om
private ModelAndView getTransactionResultResult(Repository repository, HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ClientHTTPException, ServerHTTPException, HTTPException {
    InputStream in = request.getInputStream();
    try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) {
        logger.debug("Processing transaction...");

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

        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.eclipse.rdf4j.rio.rdfxml.RDFXMLParser.java

/**
 * Implementation of SAX ErrorHandler.warning
 *///from   w w  w. ja  v  a2 s. c o m
@Override
public void warning(SAXParseException exception) throws SAXException {
    this.reportWarning(exception.getMessage());
}

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

/**
 * Implementation of SAX ErrorHandler.error
 *//*from   w ww .j  a v a  2 s  .c om*/
@Override
public void error(SAXParseException exception) throws SAXException {
    try {
        this.reportError(exception.getMessage(), XMLParserSettings.FAIL_ON_SAX_NON_FATAL_ERRORS);
    } catch (RDFParseException rdfpe) {
        throw new SAXException(rdfpe);
    }
}

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

/**
 * Implementation of SAX ErrorHandler.fatalError
 *//*from   w w  w . java 2 s  .c om*/
@Override
public void fatalError(SAXParseException exception) throws SAXException {
    try {
        this.reportFatalError(exception.getMessage());
    } catch (RDFParseException rdfpe) {
        throw new SAXException(rdfpe);
    }
}

From source file:org.eobjects.analyzer.cli.MainTest.java

public void testWriteHtmlToFile() throws Throwable {
    String filename = "target/test_write_html_to_file.html";
    Main.main(("-conf examples/conf.xml -job examples/employees_job.xml -of " + filename + " -ot HTML")
            .split(" "));

    File file = new File(filename);
    assertTrue(file.exists());/*from w  ww  . j  a  v a 2  s .com*/

    {
        String result = FileHelper.readFileAsString(file);
        String[] lines = result.split("\n");

        assertEquals("<html>", lines[1]);
    }

    InputStream in = FileHelper.getInputStream(file);
    try {
        // parse it with validator.nu for HTML correctness
        final HtmlParser htmlParser = new HtmlParser(XmlViolationPolicy.FATAL);
        final AtomicInteger elementCounter = new AtomicInteger();
        htmlParser.setContentHandler(new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                elementCounter.incrementAndGet();
            }
        });
        final List<Exception> warningsAndErrors = new ArrayList<Exception>();
        htmlParser.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                System.err.println("Warning: " + exception.getMessage());
                warningsAndErrors.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                System.out.println("Fatal error: " + exception.getMessage());
                throw exception;
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                System.err.println("Error: " + exception.getMessage());
                warningsAndErrors.add(exception);
            }
        });

        htmlParser.parse(new InputSource(in));

        // the output has approx 3600 XML elements
        int elementCount = elementCounter.get();
        assertTrue("Element count: " + elementCount, elementCount > 3000);
        assertTrue("Element count: " + elementCount, elementCount < 5000);

        if (!warningsAndErrors.isEmpty()) {
            for (Exception error : warningsAndErrors) {
                if (error.getMessage()
                        .startsWith("No explicit character encoding declaration has been seen yet")) {
                    // ignore/accept this one
                    continue;
                }
                error.printStackTrace();
                fail("Got " + warningsAndErrors.size() + " warnings and errors, see log for details");
            }
        }
    } finally {
        in.close();
    }
}

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

private ValidationReportItem createValidationReportItem(int type, SAXParseException exception) {

    final ValidationReportItem vri = new ValidationReportItem();
    vri.setType(type);/* www  . j a v a 2  s .  c  o m*/
    vri.setLineNumber(exception.getLineNumber());
    vri.setColumnNumber(exception.getColumnNumber());
    vri.setMessage(exception.getMessage());
    vri.setPublicId(exception.getPublicId());
    vri.setSystemId(exception.getSystemId());
    return vri;
}