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.apache.torque.generator.configuration.controller.ControlConfigurationXmlParser.java

/**
 * Reads the controller configuration out of a configurationProvider.
 *
 * @param configurationProvider the object for accessing the configuration,
 *        not null.// w w w.  j a  va 2 s .c  o m
 * @param projectPaths the paths inside the configuration, not null.
 * @param configurationHandlers the available configuration handlers,
 *        not null.
 *
 * @return the Controller configuration.
        
 * @throws ConfigurationException if an error in the configuration
 *         is encountered.
 * @throws NullPointerException if an argument is null.
 */
public ControlConfiguration readControllerConfiguration(ConfigurationProvider configurationProvider,
        ProjectPaths projectPaths, ConfigurationHandlers configurationHandlers) throws ConfigurationException {
    InputStream controlConfigurationInputStream = configurationProvider.getControlConfigurationInputStream();
    try {
        ControlConfiguration result = new ControlConfiguration();
        try {
            SAXParser parser = saxFactory.newSAXParser();
            InputSource is = new InputSource(controlConfigurationInputStream);
            parser.parse(is, new ControlConfigurationSaxHandler(result, configurationProvider, projectPaths,
                    configurationHandlers));
        } catch (SAXParseException e) {
            throw new ConfigurationException("Error parsing controller Configuration "
                    + configurationProvider.getControlConfigurationLocation() + " at line " + e.getLineNumber()
                    + " column " + e.getColumnNumber() + " : " + e.getMessage(), e);

        } catch (Exception e) {
            throw new ConfigurationException("Error parsing controller Configuration "
                    + configurationProvider.getControlConfigurationLocation() + e.getMessage(), e);
        }
        return result;
    } finally {
        try {
            controlConfigurationInputStream.close();
        } catch (IOException e) {
            log.warn("Could not close controlConfigurationInputStream", e);
        }
    }
}

From source file:org.apache.torque.generator.configuration.outlet.OutletConfigurationXmlParser.java

/**
 * Reads all outlet configuration files and creates the outlet
 * configuration from them./*from  ww  w  .  j a va2s  . c o m*/
 * All the outlet configuration files known to the provide are parsed.
 * These are typically all XML files in the outletDefintiton configuration
 * directory and its subdirectories.
 *
 * @param configurationProvider The access object for the configuration
 *        files, not null.
 * @param configurationHandlers the handlers for reading the configuration,
 *        not null.
 * @param unitDescriptor the unit descriptor, not null.
 *
 * @return the outlet configuration.
 *
 * @throws ConfigurationException if the Configuration cannot be read
 *         or errors exists in the outlet configuration files.
 */
public OutletConfiguration readOutletConfiguration(ConfigurationProvider configurationProvider,
        ConfigurationHandlers configurationHandlers, UnitDescriptor unitDescriptor)
        throws ConfigurationException {
    if (configurationHandlers == null) {
        log.error("OutletConfiguration: " + " configurationHandlers is null");
        throw new NullPointerException("configurationHandlers is null");
    }
    if (configurationProvider == null) {
        log.error("OutletConfiguration: " + " configurationProvider is null");
        throw new NullPointerException("configurationProvider is null");
    }

    List<Outlet> allOutlets = new ArrayList<Outlet>();
    List<MergepointMapping> allMergepointMappings = new ArrayList<MergepointMapping>();

    // Outlets from all files
    Collection<String> outletConfigNames = configurationProvider.getOutletConfigurationNames();

    for (String outletConfigName : outletConfigNames) {
        InputStream inputStream = null;
        try {
            inputStream = configurationProvider.getOutletConfigurationInputStream(outletConfigName);
            OutletConfigFileContent fileContent = readOutletConfig(inputStream, configurationProvider,
                    unitDescriptor.getProjectPaths(), configurationHandlers);
            allOutlets.addAll(fileContent.getOutlets());
            allMergepointMappings.addAll(fileContent.getMergepointMappings());
        } catch (SAXParseException e) {
            throw new ConfigurationException(
                    "Error parsing outlet configuration " + outletConfigName + " at line " + e.getLineNumber()
                            + " column " + e.getColumnNumber() + " : " + e.getMessage(),
                    e);

        } catch (Exception e) {
            throw new ConfigurationException("Error parsing outlet configuration " + outletConfigName, e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.warn("Could not close " + "outletConfigurationInputStream " + outletConfigName, e);
                }
            }
        }
    }
    return new OutletConfiguration(allOutlets, allMergepointMappings, unitDescriptor);
}

From source file:org.archive.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./*w w w.  j  av a 2s.c  om*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(toResourcePath(f));
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.bibsonomy.rest.renderer.impl.JAXBRenderer.java

/**
 * Unmarshalls the document from the reader to the generated java
 * model./*from  w ww.  j a  v  a  2 s.co m*/
 * 
 * @return A BibsonomyXML object that contains the unmarshalled content
 * @throws InternServerException
 *             if the content can't be unmarshalled
 */
private BibsonomyXML parse(final Reader reader) throws InternServerException {
    // first: check the reader 
    this.checkReader(reader);
    try {
        // initialize JAXB context. We provide the classloader here because we experienced that under
        // certain circumstances (e.g. when used within JabRef as a JPF-Plugin), the wrong classloader is
        // used which has the following exception as consequence:
        //
        //   javax.xml.bind.JAXBException: "org.bibsonomy.rest.renderer.xml" doesnt contain ObjectFactory.class or jaxb.index
        //
        // (see also http://ws.apache.org/jaxme/apidocs/javax/xml/bind/JAXBContext.html)
        final JAXBContext jc = this.getJAXBContext();

        // create an Unmarshaller
        final Unmarshaller u = jc.createUnmarshaller();

        // set schema to validate input documents
        if (this.validateXMLInput) {
            u.setSchema(schema);
        }

        /*
         * unmarshal a xml instance document into a tree of Java content
         * objects composed of classes from the restapi package.
         */
        final JAXBElement<BibsonomyXML> xmlDoc = unmarshal(u, reader);
        return xmlDoc.getValue();
    } catch (final JAXBException e) {
        if (e.getLinkedException() != null && e.getLinkedException().getClass() == SAXParseException.class) {
            final SAXParseException ex = (SAXParseException) e.getLinkedException();
            throw new BadRequestOrResponseException("Error while parsing XML (Line " + ex.getLineNumber()
                    + ", Column " + ex.getColumnNumber() + ": " + ex.getMessage());
        }
        throw new InternServerException(e.toString());
    }
}

From source file:org.bibsonomy.rest.renderer.impl.JAXBRenderer.java

/**
 * Initializes java xml bindings, builds the document and then marshalls
 * it to the writer./*from   w  w w .j ava 2s  . co m*/
 * 
 * @throws InternServerException
 *             if the document can't be marshalled
 */
private void serialize(final Writer writer, final BibsonomyXML xmlDoc) throws InternServerException {
    try {
        // initialize context for java xml bindings
        final JAXBContext jc = this.getJAXBContext();

        // buildup document model
        final JAXBElement<BibsonomyXML> webserviceElement = new ObjectFactory().createBibsonomy(xmlDoc);

        // create a marshaller
        final Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (this.validateXMLOutput) {
            // validate the XML produced by the marshaller
            marshaller.setSchema(schema);
        }

        // marshal to the writer
        this.marshal(marshaller, webserviceElement, writer);
        // TODO log
        // log.debug("");
    } catch (final JAXBException e) {
        final Throwable linkedException = e.getLinkedException();
        if (present(linkedException) && linkedException.getClass() == SAXParseException.class) {
            final SAXParseException ex = (SAXParseException) linkedException;
            throw new BadRequestOrResponseException("Error while parsing XML (Line " + ex.getLineNumber()
                    + ", Column " + ex.getColumnNumber() + ": " + ex.getMessage());
        }
        throw new InternServerException(e.toString());
    }
}

From source file:org.codehaus.enunciate.config.EnunciateConfiguration.java

/**
 * Handle a warning.//from   w  w w. j av  a 2s.c  o m
 *
 * @param warning The warning.
 */
public void warning(SAXParseException warning) throws SAXException {
    System.err.println(warning.getMessage());
}

From source file:org.codice.ddf.transformer.xml.streaming.lib.SaxEventHandlerDelegate.java

/**
 * A helper method to help parse relevant information from the exception
 *
 * @param exception An exception that was passed into the {@link InputTransformerErrorHandler} by the parser
 * @return a string of relevant information about the exception
 *//*  ww w. j  a v  a2s . c o m*/
private String getParseExceptionInfo(SAXParseException exception) {
    String systemId = exception.getSystemId();

    if (systemId == null) {
        systemId = "null";
    }

    return "URI=" + systemId + " Line=" + exception.getLineNumber() + ": " + exception.getMessage();
}

From source file:org.datacleaner.cli.MainTest.java

public void testWriteHtmlToFile() throws Throwable {
    String filename = "target/test_write_html_to_file.html";
    Main.main(/*from   ww  w  . ja va 2  s  .c om*/
            ("-conf src/test/resources/cli-examples/conf.xml -job src/test/resources/cli-examples/employees_job.xml -of "
                    + filename + " -ot HTML").split(" "));

    File file = new File(filename);
    assertTrue(file.exists());

    {
        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) {
                String message = error.getMessage();
                if (message.startsWith("No explicit character encoding declaration has been seen yet")
                        || message.startsWith("The character encoding of the document was not declared.")) {
                    // 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.deegree.tools.metadata.ISO19139Validator.java

private void write(FileWriter fw, String level, SAXParseException arg0) {
    try {//  w ww .  j av a  2  s.  co m
        fw.write("[" + level + "] ");
        fw.write(arg0.getMessage());
        fw.write("\n");
    } catch (IOException e) {
        System.err.println(e.getMessage());
        if (verbose)
            e.printStackTrace();
    }
}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

/**
 * Read a file and process it for list information.
 * //from w w  w  . j a va2s  .c om
 * @param ref system path of the file to process
 * @throws DITAOTException if processing failed
 */
private void processFile(final Reference ref) throws DITAOTException {
    currentFile = ref.filename;
    assert currentFile.isAbsolute();
    logger.info("Processing " + currentFile);
    final String[] params = { currentFile.toString() };

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

        xmlSource.parse(currentFile.toString());

        if (listFilter.isValidInput()) {
            processParseResult(currentFile);
            categorizeCurrentFile(ref);
        } else if (!currentFile.equals(rootFile)) {
            logger.warn(MessageUtils.getInstance().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.getInstance().getMessage("DOTJ012F", params).toString()
                    + ": " + sax.getMessage(), sax);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString()
                    + ": " + sax.getMessage(), sax);
        } else {
            logger.error(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": "
                    + sax.getMessage(), sax);
        }
        failureList.add(currentFile);
    } catch (final FileNotFoundException e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTA069F", params).toString(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTX008E", params).toString()
                    + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getInstance().getMessage("DOTX008E", params).toString());
        }
        failureList.add(currentFile);
    } catch (final Exception e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ012F", params).toString()
                    + ": " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString()
                    + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": "
                    + e.getMessage(), e);
        }
        failureList.add(currentFile);
    }

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

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

}