Example usage for org.xml.sax SAXParseException toString

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Override toString to provide more detailed error message.

Usage

From source file:javasnack.snacks.xml.sax2.DebugPrinter.java

void saxerr(String level, SAXParseException e) {
    oops("%s : SAXParserException(line:%d, column:%d, publicId:%s, systemId:%s)", level, e.getLineNumber(),
            e.getColumnNumber(), e.getPublicId(), e.getSystemId());
    oops(e.toString());
    oops("...continue");
}

From source file:net.sourceforge.fullsync.fs.connection.SyncFileBufferedConnection.java

protected void loadFromBuffer() throws IOException {
    File fsRoot = fs.getRoot();//from w w  w. j  a  v a2 s . c  om
    File f = fsRoot.getChild(BUFFER_FILENAME);

    root = new AbstractBufferedFile(this, fsRoot, null, true, true);
    if ((null == f) || !f.exists() || f.isDirectory()) {
        if (isMonitoringFileSystem()) {
            updateFromFileSystem(root);
        }
        return;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream((int) f.getSize());
    try (InputStream in = new GZIPInputStream(f.getInputStream())) {
        int i;
        byte[] block = new byte[4096];
        while ((i = in.read(block)) > 0) {
            out.write(block, 0, i);
        }
    }
    try {
        SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
        sax.parse(new ByteArrayInputStream(out.toByteArray()), new SyncFileDefaultHandler(this));
    } catch (SAXParseException spe) {
        StringBuilder sb = new StringBuilder(spe.toString());
        sb.append("\n Line number: " + spe.getLineNumber()); //$NON-NLS-1$
        sb.append("\n Column number: " + spe.getColumnNumber()); //$NON-NLS-1$
        sb.append("\n Public ID: " + spe.getPublicId()); //$NON-NLS-1$
        sb.append("\n System ID: " + spe.getSystemId() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        System.err.println(sb.toString());
    } catch (IOException | SAXException | ParserConfigurationException | FactoryConfigurationError e) {
        ExceptionHandler.reportException(e);
    }

    if (isMonitoringFileSystem()) {
        updateFromFileSystem(root);
    }
}

From source file:ch.ddl.daia.DaiaRequest.java

public List<Bestand> get(final String openurl) {

    final List<Bestand> bestaende = new ArrayList<Bestand>();

    // TODO: use cached Threadpool with timeouts

    for (final String host : ReadSystemConfigurations.getDaiaHosts()) {

        final String url = host + "?" + openurl;

        try {/*from   w ww .  ja va  2  s .  co  m*/

            final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            final Document doc = docBuilder.parse(url);

            // normalize text representation
            doc.getDocumentElement().normalize();

            // contains the baseUrl of the server installation, needed
            // to order at the register beeing searched
            final NodeList listOfInstitution = doc.getElementsByTagName("institution");
            final Element institutionElement = (Element) listOfInstitution.item(0);
            final String baseUrl = extractBaseUrl(institutionElement.getAttribute("href"));
            //            System.out.println("BaseURL orderlink: " + baseUrl);

            // Get a list of all holdings
            final NodeList listOfHoldings = doc.getElementsByTagName("document");
            //                final int totalHoldings = listOfHoldings.getLength();
            //                System.out.println("Total no of holdings: " + totalHoldings);

            // process each holding
            for (int s = 0; s < listOfHoldings.getLength(); s++) {

                final Node firstHoldingNode = listOfHoldings.item(s);
                if (firstHoldingNode.getNodeType() == Node.ELEMENT_NODE) {

                    // URN and holding ID
                    final Element firstHoldingElement = (Element) firstHoldingNode;
                    final Long hoid = urnExtractID(firstHoldingElement.getAttribute("id"));
                    //                    System.out.println("Holding-URN: " + hoid);

                    // Title of journal
                    final NodeList titelList = firstHoldingElement.getElementsByTagName("message");
                    final Element titelElement = (Element) titelList.item(0);
                    final NodeList textTitelList = titelElement.getChildNodes();
                    String titel = "";
                    if (textTitelList.getLength() > 0) {
                        titel = StringEscapeUtils.unescapeXml(textTitelList.item(0).getNodeValue().trim());
                    }

                    // List of stock elements for one holding
                    final NodeList listOfItems = firstHoldingElement.getElementsByTagName("item");
                    //                        final int totalItems = listOfItems.getLength();
                    //                        System.out.println("Total no of items: " + totalItems);

                    // process each stock element
                    for (int n = 0; n < listOfItems.getLength(); n++) {

                        final Bestand bestand = new Bestand();
                        bestand.getHolding().setId(hoid);
                        bestand.getHolding().setTitel(titel);
                        bestand.getHolding().setBaseurl(baseUrl);

                        final Node firstItemNode = listOfItems.item(n);
                        if (firstItemNode.getNodeType() == Node.ELEMENT_NODE) {

                            String value = "";

                            // URN and stock ID
                            final Element firstItemElement = (Element) firstItemNode;
                            value = firstItemElement.getAttribute("id");
                            //                                System.out.println("Stock-URN: " + value);
                            bestand.setId(urnExtractID(value));

                            // Remarks
                            final NodeList bemerkungenList = firstItemElement.getElementsByTagName("message");
                            if (bemerkungenList.getLength() > 0) {
                                final Element bemerkungenElement = (Element) bemerkungenList.item(0);
                                final NodeList textBemerkungenList = bemerkungenElement.getChildNodes();
                                if (textBemerkungenList.getLength() > 0) {
                                    value = StringEscapeUtils
                                            .unescapeXml(textBemerkungenList.item(0).getNodeValue().trim());
                                } else {
                                    value = "";
                                }
                                bestand.setBemerkungen(value);
                            }

                            // shelfmark or callnumber
                            final NodeList shelfmarkList = firstItemElement.getElementsByTagName("label");
                            if (shelfmarkList.getLength() > 0) {
                                final Element shelfmarkElement = (Element) shelfmarkList.item(0);
                                final NodeList textShelfmarkList = shelfmarkElement.getChildNodes();
                                if (textShelfmarkList.getLength() > 0) {
                                    value = StringEscapeUtils
                                            .unescapeXml(textShelfmarkList.item(0).getNodeValue().trim());
                                } else {
                                    value = "";
                                }
                                bestand.setShelfmark(value);
                            }

                            // URN and account ID
                            final NodeList kontoList = firstItemElement.getElementsByTagName("department");
                            if (kontoList.getLength() > 0) {
                                final Element kontoElement = (Element) kontoList.item(0);
                                value = kontoElement.getAttribute("id");
                                final Long kid = urnExtractID(value);
                                //                                    System.out.println("Konto-URN: " + value);
                                bestand.getHolding().setKid(kid);
                                bestand.getHolding().getKonto().setId(kid);

                                final NodeList textKontoList = kontoElement.getChildNodes();
                                if (textKontoList.getLength() > 0) {
                                    value = StringEscapeUtils
                                            .unescapeXml(textKontoList.item(0).getNodeValue().trim());
                                } else {
                                    value = "";
                                }
                                bestand.getHolding().getKonto().setBibliotheksname(value);
                            }

                            // ----
                            final NodeList storageList = firstItemElement.getElementsByTagName("storage");
                            if (storageList.getLength() > 0) {
                                final Element storageElement = (Element) storageList.item(0);
                                final NodeList textStorageList = storageElement.getChildNodes();
                                if (textStorageList.getLength() > 0) {
                                    value = textStorageList.item(0).getNodeValue().trim();
                                    value = StringEscapeUtils
                                            .unescapeXml(textStorageList.item(0).getNodeValue().trim());
                                } else {
                                    value = "";
                                }
                                bestand.getStandort().setInhalt(value);
                            }

                            // Read available tag and limitations
                            final NodeList availableList = firstItemElement.getElementsByTagName("available");

                            if (availableList.getLength() > 0) {

                                // Limitations
                                final Element availableElement = (Element) availableList.item(0);
                                final NodeList availableLimitationList = availableElement
                                        .getElementsByTagName("limitation");
                                value = "";
                                // there may be other limitations than country...
                                for (int m = 0; m < availableLimitationList.getLength(); m++) {
                                    final Element countryElement = (Element) availableLimitationList.item(m);
                                    final NodeList textCountryList = countryElement.getChildNodes();
                                    if (textCountryList.getLength() > 0
                                            && textCountryList.item(0).getNodeValue().startsWith("Country: ")) {
                                        value = textCountryList.item(0).getNodeValue().substring(9).trim();
                                    }
                                }

                                bestand.getHolding().getKonto().setLand(value);

                                bestaende.add(bestand);
                            }
                        }
                    }
                }
            }

        } catch (final SAXParseException e) {
            LOG.error(e.toString());

        } catch (final SAXException e) {
            LOG.error(e.toString());

        } catch (final IOException e) {
            LOG.error(e.toString());
        } catch (final ParserConfigurationException e) {
            LOG.error(e.toString());
        }

    }

    return bestaende;

}

From source file:org.apache.uima.ruta.resource.TreeWordList.java

public void readXML(InputStream stream, String encoding) throws IOException {
    try {/*from w  w  w .  j  av a2  s  . c o m*/
        InputStream is = new BufferedInputStream(stream); // adds mark/reset support
        boolean isXml = MultiTreeWordListPersistence.isSniffedXmlContentType(is);
        if (!isXml) { // MTWL is encoded
            is = new ZipInputStream(is);
            ((ZipInputStream) is).getNextEntry(); // zip must contain a single entry
        }
        InputStreamReader streamReader = new InputStreamReader(is, encoding);
        this.root = new TextNode();
        XMLEventHandler handler = new XMLEventHandler(root);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        // XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.parse(new InputSource(streamReader));
    } catch (SAXParseException spe) {
        StringBuffer sb = new StringBuffer(spe.toString());
        sb.append("\n  Line number: " + spe.getLineNumber());
        sb.append("\n Column number: " + spe.getColumnNumber());
        sb.append("\n Public ID: " + spe.getPublicId());
        sb.append("\n System ID: " + spe.getSystemId() + "\n");
        System.out.println(sb.toString());
    } catch (SAXException se) {
        System.out.println("loadDOM threw " + se);
        se.printStackTrace(System.out);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:org.ajax4jsf.renderkit.compiler.HtmlCompiler.java

public PreparedTemplate compile(Reader input) {
    // By default - empty result. we not throw any exceptions in compile phase -
    // since it can be in static class initialization.
    PreparedTemplate result = null;//w w w.  jav  a  2 s . co m
    try {
        digestr.clear();
        digestr.push(new RootElement());
        result = (PreparedTemplate) digestr.parse(input);
    } catch (SAXParseException e) {
        //         TODO - locate compilation error. How get name ?
        String errorstr = Messages.getMessage(Messages.PARSING_TEMPLATE_ERROR,
                new Object[] { "" + e.getLineNumber(), "" + e.getColumnNumber(), e.toString() });
        //         errorstr.append(digestr.getDocumentLocator().getLineNumber()).append(" and position ").append(digestr.getDocumentLocator().getColumnNumber());
        log.error(errorstr, e);
        result = new CompiledError(errorstr.toString(), e);
    } catch (IOException e) {
        String errorstr = Messages.getMessage(Messages.TEMPLATE_IO_ERROR, e.toString());
        log.error(errorstr, e);
        result = new CompiledError(errorstr.toString(), e);
    } catch (SAXException e) {
        String errorstr = Messages.getMessage(Messages.PARSING_TEMPLATE_ERROR_2, e.toString());
        log.error(errorstr, e);
        result = new CompiledError(errorstr.toString(), e);
    }
    return result;
}

From source file:org.ajax4jsf.renderkit.compiler.HtmlCompiler.java

/**
 * Compile input {@link InputStream} to {@link PreparedTemplate} - set of Java classes to encode as JSF output.
 * @param input stream with template XML text.
 * @param sourcename ( optional ) name of resource, for debug purposes.
 * @return compiled template.//from  w w  w  .  j  av  a 2 s. co m
 */
public PreparedTemplate compile(InputStream input, String sourcename) {
    // By default - empty result. we not throw any exceptions in compile phase -
    // since it can be in static class initialization.
    PreparedTemplate result = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug(Messages.getMessage(Messages.START_COMPILE_TEMPLATE_INFO, sourcename));
        }
        digestr.clear();
        RootElement root = new RootElement();
        root.setTemplateName(sourcename);
        digestr.push(root);
        result = (PreparedTemplate) digestr.parse(input);
    } catch (SAXParseException e) {
        //         TODO - locate compilation error. How get name ?
        String errorstr = Messages.getMessage(Messages.PARSING_TEMPLATE_ERROR_a,
                new Object[] { sourcename, "" + e.getLineNumber(), "" + e.getColumnNumber(), e.toString() });
        //         errorstr.append(digestr.getDocumentLocator().getLineNumber()).append(" and position ").append(digestr.getDocumentLocator().getColumnNumber());
        log.error(errorstr, e);
        result = new CompiledError(errorstr.toString(), e);
    } catch (IOException e) {
        String errorstr = Messages.getMessage(Messages.TEMPLATE_IO_ERROR_a, sourcename, e.toString());
        log.error(errorstr, e);
        result = new CompiledError(errorstr.toString(), e);
    } catch (SAXException e) {
        String errorstr = Messages.getMessage(Messages.PARSING_TEMPLATE_ERROR_2a, sourcename, e.toString());
        log.error(errorstr, e);
        result = new CompiledError(errorstr.toString(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage(Messages.FINISH_COMPILE_TEMPLATE_INFO, sourcename));
    }
    return result;
}

From source file:org.apache.fop.fo.FOTreeBuilder.java

/** {@inheritDoc} */
public void error(SAXParseException e) {
    LOG.error(e.toString());
}

From source file:org.apache.fop.fo.FOTreeBuilder.java

/** {@inheritDoc} */
public void fatalError(SAXParseException e) throws SAXException {
    LOG.error(e.toString());
    throw e;/*from   ww  w. j a v a2  s .  com*/
}

From source file:org.apache.solr.core.TestCoreContainer.java

@Test
public void testCoreInitFailuresOnReload() throws Exception {

    // reused state
    Map<String, CoreContainer.CoreLoadFailure> failures = null;
    Collection<String> cores = null;
    Exception fail = null;// www. j  a va2s . c  o  m

    // -----
    // init the  CoreContainer with the mix of ok/bad cores
    MockCoresLocator cl = new MockCoresLocator();

    SolrResourceLoader resourceLoader = new SolrResourceLoader(createTempDir());

    System.setProperty("configsets", getFile("solr/configsets").getAbsolutePath());

    final CoreContainer cc = new CoreContainer(SolrXmlConfig.fromString(resourceLoader, CONFIGSETS_SOLR_XML),
            new Properties(), cl);
    cl.add(new CoreDescriptor(cc, "col_ok", resourceLoader.getInstancePath().resolve("col_ok"), "configSet",
            "minimal"));
    cl.add(new CoreDescriptor(cc, "col_bad", resourceLoader.getInstancePath().resolve("col_bad"), "configSet",
            "bad-mergepolicy"));
    cc.load();

    // check that we have the cores we expect
    cores = cc.getCoreNames();
    assertNotNull("core names is null", cores);
    assertEquals("wrong number of cores", 1, cores.size());
    assertTrue("col_ok not found", cores.contains("col_ok"));

    // check that we have the failures we expect
    failures = cc.getCoreInitFailures();
    assertNotNull("core failures is a null map", failures);
    assertEquals("wrong number of core failures", 1, failures.size());
    fail = failures.get("col_bad").exception;
    assertNotNull("null failure for test core", fail);
    assertTrue("init failure doesn't mention problem: " + fail.getMessage(),
            0 < fail.getMessage().indexOf("DummyMergePolicy"));

    // check that we get null accessing a non-existent core
    assertNull(cc.getCore("does_not_exist"));
    // check that we get a 500 accessing the core with an init failure
    try {
        SolrCore c = cc.getCore("col_bad");
        fail("Failed to get Exception on accessing core with init failure");
    } catch (SolrException ex) {
        assertEquals(500, ex.code());
        // double wrapped
        String cause = ex.getCause().getCause().getMessage();
        assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
                0 < cause.indexOf("DummyMergePolicy"));
    }

    // -----
    // "fix" the bad collection
    FileUtils.copyFile(getFile("solr/collection1/conf/solrconfig-defaults.xml"),
            FileUtils.getFile(cc.getSolrHome(), "col_bad", "conf", "solrconfig.xml"));
    FileUtils.copyFile(getFile("solr/collection1/conf/schema-minimal.xml"),
            FileUtils.getFile(cc.getSolrHome(), "col_bad", "conf", "schema.xml"));
    cc.create("col_bad", ImmutableMap.of());

    // check that we have the cores we expect
    cores = cc.getCoreNames();
    assertNotNull("core names is null", cores);
    assertEquals("wrong number of cores", 2, cores.size());
    assertTrue("col_ok not found", cores.contains("col_ok"));
    assertTrue("col_bad not found", cores.contains("col_bad"));

    // check that we have the failures we expect
    failures = cc.getCoreInitFailures();
    assertNotNull("core failures is a null map", failures);
    assertEquals("wrong number of core failures", 0, failures.size());

    // -----
    // try to add a collection with a path that doesn't exist
    try {
        ignoreException(Pattern.quote("bogus_path"));
        cc.create("bogus", ImmutableMap.of("configSet", "bogus_path"));
        fail("bogus inst dir failed to trigger exception from create");
    } catch (SolrException e) {
        assertTrue("init exception doesn't mention bogus dir: " + e.getCause().getCause().getMessage(),
                0 < e.getCause().getCause().getMessage().indexOf("bogus_path"));

    }

    // check that we have the cores we expect
    cores = cc.getCoreNames();
    assertNotNull("core names is null", cores);
    assertEquals("wrong number of cores", 2, cores.size());
    assertTrue("col_ok not found", cores.contains("col_ok"));
    assertTrue("col_bad not found", cores.contains("col_bad"));

    // check that we have the failures we expect
    failures = cc.getCoreInitFailures();
    assertNotNull("core failures is a null map", failures);
    assertEquals("wrong number of core failures", 1, failures.size());
    fail = failures.get("bogus").exception;
    assertNotNull("null failure for test core", fail);
    assertTrue("init failure doesn't mention problem: " + fail.getMessage(),
            0 < fail.getMessage().indexOf("bogus_path"));

    // check that we get null accessing a non-existent core
    assertNull(cc.getCore("does_not_exist"));
    // check that we get a 500 accessing the core with an init failure
    try {
        SolrCore c = cc.getCore("bogus");
        fail("Failed to get Exception on accessing core with init failure");
    } catch (SolrException ex) {
        assertEquals(500, ex.code());
        // double wrapped
        String cause = ex.getCause().getMessage();
        assertTrue("getCore() ex cause doesn't mention init fail: " + cause, 0 < cause.indexOf("bogus_path"));
    }

    // -----
    // break col_bad's config and try to RELOAD to add failure

    final long col_bad_old_start = getCoreStartTime(cc, "col_bad");

    FileUtils.write(FileUtils.getFile(cc.getSolrHome(), "col_bad", "conf", "solrconfig.xml"),
            "This is giberish, not valid XML <", IOUtils.UTF_8);

    try {
        ignoreException(Pattern.quote("SAX"));
        cc.reload("col_bad");
        fail("corrupt solrconfig.xml failed to trigger exception from reload");
    } catch (SolrException e) {
        Throwable rootException = getWrappedException(e);
        assertTrue("We're supposed to have a wrapped SAXParserException here, but we don't",
                rootException instanceof SAXParseException);
        SAXParseException se = (SAXParseException) rootException;
        assertTrue("reload exception doesn't refer to slrconfig.xml " + se.getSystemId(),
                0 < se.getSystemId().indexOf("solrconfig.xml"));

    }

    assertEquals("Failed core reload should not have changed start time", col_bad_old_start,
            getCoreStartTime(cc, "col_bad"));

    // check that we have the cores we expect
    cores = cc.getCoreNames();
    assertNotNull("core names is null", cores);
    assertEquals("wrong number of cores", 2, cores.size());
    assertTrue("col_ok not found", cores.contains("col_ok"));
    assertTrue("col_bad not found", cores.contains("col_bad"));

    // check that we have the failures we expect
    failures = cc.getCoreInitFailures();
    assertNotNull("core failures is a null map", failures);
    assertEquals("wrong number of core failures", 2, failures.size());
    Throwable ex = getWrappedException(failures.get("col_bad").exception);
    assertNotNull("null failure for test core", ex);
    assertTrue("init failure isn't SAXParseException", ex instanceof SAXParseException);
    SAXParseException saxEx = (SAXParseException) ex;
    assertTrue("init failure doesn't mention problem: " + saxEx.toString(),
            saxEx.getSystemId().contains("solrconfig.xml"));

    // ----
    // fix col_bad's config (again) and RELOAD to fix failure
    FileUtils.copyFile(getFile("solr/collection1/conf/solrconfig-defaults.xml"),
            FileUtils.getFile(cc.getSolrHome(), "col_bad", "conf", "solrconfig.xml"));
    cc.reload("col_bad");

    assertTrue("Core reload should have changed start time",
            col_bad_old_start < getCoreStartTime(cc, "col_bad"));

    // check that we have the cores we expect
    cores = cc.getCoreNames();
    assertNotNull("core names is null", cores);
    assertEquals("wrong number of cores", 2, cores.size());
    assertTrue("col_ok not found", cores.contains("col_ok"));
    assertTrue("col_bad not found", cores.contains("col_bad"));

    // check that we have the failures we expect
    failures = cc.getCoreInitFailures();
    assertNotNull("core failures is a null map", failures);
    assertEquals("wrong number of core failures", 1, failures.size());

    cc.shutdown();

}

From source file:org.castor.xmlctf.xmldiff.xml.XMLFileReader.java

/**
 * Reads an XML Document into an BaseNode from the provided file.
 *
 * @return the BaseNode/*  w  w w .j  a v  a2 s . c  o  m*/
 * @throws java.io.IOException if any exception occurs during parsing
 */
public XMLNode read() throws java.io.IOException {
    XMLNode node = null;

    try {
        InputSource source = new InputSource();
        source.setSystemId(_location);
        source.setCharacterStream(new FileReader(_file));

        XMLContentHandler builder = new XMLContentHandler();

        _parser.setContentHandler(builder);
        _parser.parse(source);

        node = builder.getRoot();
    } catch (SAXException sx) {
        Exception nested = sx.getException();

        SAXParseException sxp = null;
        if (sx instanceof SAXParseException) {
            sxp = (SAXParseException) sx;
        } else if (nested != null && (nested instanceof SAXParseException)) {
            sxp = (SAXParseException) nested;
        } else {
            throw new NestedIOException(sx);
        }

        String err = new StringBuilder(sxp.toString()).append("\n - ").append(sxp.getSystemId())
                .append("; line: ").append(sxp.getLineNumber()).append(", column: ")
                .append(sxp.getColumnNumber()).toString();
        throw new NestedIOException(err, sx);
    }

    Root root = (Root) node;
    return root;
}