Example usage for org.xml.sax SAXParseException SAXParseException

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

Introduction

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

Prototype

public SAXParseException(String message, Locator locator, Exception e) 

Source Link

Document

Wrap an existing exception in a SAXParseException.

Usage

From source file:org.jcurl.core.io.SetupSaxDeSer.java

@Override
public void endElement(final String uri, final String localName, final String qName) throws SAXException {
    final String elem = qName;
    elems.pop();/*w  w  w  .  j a v a  2 s .  co m*/
    final String txt = buf.toString().trim();
    switch (elems.size() + 1) {
    case 1:
        if ("jcurl".equals(elem))
            ;
        else
            break;
        return;
    case 2:
        if ("setup".equals(elem))
            setup.freeze();
        else
            break;
        return;
    case 3:
        if ("model".equals(elem))
            try {
                setup.addModel(modelClass, modelProps);
            } catch (final InstantiationException e) {
                log.warn("error in [" + elems + "]", e);
                error(new SAXParseException("error in [" + elems + "]", locator, e));
            } catch (final IllegalAccessException e) {
                log.warn("error in [" + elems + "]", e);
                error(new SAXParseException("error in [" + elems + "]", locator, e));
            }
        else
            break;
        return;
    case 4:
        if ("rock".equals(elem))
            currRock = null;
        else
            break;
        return;
    }
}

From source file:org.kalypso.gml.GMLSAXFactory.java

private void processValueType(final IValuePropertyType pt, final Object propertyValue,
        final QName prefixedQName) throws SAXException {
    final IMarshallingTypeHandler th = pt.getTypeHandler();

    if (th instanceof ISimpleMarshallingTypeHandler<?>) {
        final String xmlString = printSimpleValue(pt, (ISimpleMarshallingTypeHandler<Object>) th,
                propertyValue);/*from w w w .  j  a  va  2s.c om*/
        if (xmlString != null) {
            // FIXME: this is the right place to write CDATA stuff, but of course now it is a wild hack
            // to look for a specific value. This must of course be decided in a more general way.
            // Maybe we register extensions for specific qnames?
            // TODO: also, it should be only done for String, i.e. in the XsdBaseTypeHandlerString
            final boolean doCData = prefixedQName.equals(new QName(NS.OM, "result"));
            final LexicalHandler lexicalHandler = doCData
                    ? (LexicalHandler) m_reader.getProperty("http://xml.org/sax/properties/lexical-handler")
                    : null;
            if (doCData)
                lexicalHandler.startCDATA();

            m_reader.getContentHandler().characters(xmlString.toCharArray(), 0, xmlString.length());

            if (doCData)
                lexicalHandler.endCDATA();
        }

        return;
    }

    if (propertyValue != null) {
        try {
            th.marshal(propertyValue, m_reader, null, m_gmlVersion);
        } catch (final Exception e) {
            // Catch any exception here: we should always continue to write data in order to minimise data loss here

            // TODO: we need an error handler! Else the user does not get any information about errors

            // TODO Distinguish between normal exceptions and SaxParseException
            final ErrorHandler errorHandler = m_reader.getErrorHandler();
            if (errorHandler == null)
                KalypsoDeegreePlugin.getDefault().getLog().log(StatusUtilities.statusFromThrowable(e));
            else
                errorHandler
                        .error(new SAXParseException("Failed to write property: " + pt.getQName(), null, e));
        }
    }
}

From source file:org.kalypso.gmlschema.types.SimpleDOMTypeHandler.java

@Override
public void unmarshal(final XMLReader reader, final URL context, final UnmarshallResultEater marshalResultEater,
        final String gmlVersion) throws TypeRegistryException {
    try {//from w  w  w.  j  a  v  a2  s  .  com
        final UnmarshallResultEater eater = new UnmarshallResultEater() {
            @Override
            public void unmarshallSuccesful(final Object value) throws SAXParseException {
                final Node node = (Node) value;
                if (node == null)
                    marshalResultEater.unmarshallSuccesful(null);
                else {
                    try {
                        final Object object = internalUnmarshall(node);
                        marshalResultEater.unmarshallSuccesful(object);
                    } catch (final TypeRegistryException e) {
                        throw new SAXParseException(e.getLocalizedMessage(), null, e);
                    }
                }
            }
        };

        // FIXME: use transformer instead of self-made stuff

        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.newDocument();
        final DOMConstructor domBuilderContentHandler = new DOMConstructor(document, eater);

        // simulate property-tag for dombuilder
        reader.setContentHandler(domBuilderContentHandler);
    } catch (final Exception e) {
        throw new TypeRegistryException(e);
    }
}

From source file:org.yamj.core.tools.xml.DOMHelper.java

/**
 * Get a DOM document from the supplied file
 *
 * @param xmlFile/*from  ww  w . j a  v  a 2  s. c o  m*/
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public static Document getDocFromFile(File xmlFile)
        throws ParserConfigurationException, SAXException, IOException {
    URL url = xmlFile.toURI().toURL();
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    // Custom error handler
    db.setErrorHandler(new SaxErrorHandler());
    Document doc;
    try (InputStream in = url.openStream()) {
        doc = db.parse(in);
    } catch (SAXParseException ex) {
        if (FilenameUtils.isExtension(xmlFile.getName().toLowerCase(), "xml")) {
            throw new SAXParseException("Failed to process file as XML", null, ex);
        }
        // Try processing the file a different way
        doc = null;
    }

    if (doc == null) {
        // try wrapping the file in a root
        try (StringReader sr = new StringReader(wrapInXml(FileTools.readFileToString(xmlFile)))) {
            doc = db.parse(new InputSource(sr));
        }
    }

    if (doc != null) {
        doc.getDocumentElement().normalize();
    }
    return doc;
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Transforms the given <code>xml</code> section from KFS3 format to KFS6
 * format./*  w w  w.j  a va  2  s.co m*/
 * 
 * @param xml
 *            {@link String} of the XML to transform
 * @return {@link String} of the transformed XML
 * @throws Exception
 *             Any {@link Exception}s encountered will be rethrown.
 */
private String transformSection(String xml, String docid) throws Exception {
    String rawXml = xml;
    String maintenanceAction = StringUtils.substringBetween(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">",
            "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">");
    xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">");

    xml = upgradeBONotes(xml, docid);

    if (classNameRuleMap == null) {
        setRuleMaps();
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document;
    try {
        document = db.parse(new InputSource(new StringReader(xml)));
    } catch (SAXParseException ex) {
        String eol = System.getProperty("line.separator");
        String exMsg = "Failed in db.parse(new InputSource(new StringReader(xml))) where xml=" + xml + eol
                + "of maintenanceAction = " + maintenanceAction + eol + "contained in rawXml = " + rawXml;
        throw new SAXParseException(exMsg, null, ex);
    }

    for (Node childNode = document.getFirstChild(); childNode != null;) {
        Node nextChild = childNode.getNextSibling();
        transformClassNode(document, childNode);
        // Also Transform first level Children which have class attribute
        NodeList children = childNode.getChildNodes();
        for (int n = 0; n < children.getLength(); n++) {
            Node child = children.item(n);
            if ((child != null) && (child.getNodeType() == Node.ELEMENT_NODE) && (child.hasAttributes())) {
                NamedNodeMap childAttributes = child.getAttributes();
                if (childAttributes.item(0).getNodeName() == "class") {
                    String childClassName = childAttributes.item(0).getNodeValue();
                    if (classPropertyRuleMap.containsKey(childClassName)) {
                        Map<String, String> propertyMappings = classPropertyRuleMap.get(childClassName);
                        NodeList nestedChildren = child.getChildNodes();
                        for (int i = 0; i < nestedChildren.getLength() - 1; i++) {
                            Node property = nestedChildren.item(i);
                            String propertyName = property.getNodeName();
                            if ((property.getNodeType() == Node.ELEMENT_NODE) && (propertyMappings != null)
                                    && (propertyMappings.containsKey(propertyName))) {
                                String newPropertyName = propertyMappings.get(propertyName);
                                if (StringUtils.isNotBlank(newPropertyName)) {
                                    document.renameNode(property, null, newPropertyName);
                                    propertyName = newPropertyName;
                                } else {
                                    // If there is no replacement name then the element needs to be removed
                                    child.removeChild(property);
                                }
                            }
                        }
                    }
                }
            }
        }
        childNode = nextChild;
    }

    /*
     * the default logic that traverses over the document tree doesn't
     * handle classes that are in an @class attribute, so we deal with those
     * individually.
     */
    migratePersonObjects(document);
    migrateKualiCodeBaseObjects(document);
    migrateAccountExtensionObjects(document);
    migrateClassAsAttribute(document);
    removeAutoIncrementSetElements(document);
    removeReconcilerGroup(document);
    catchMissedTypedArrayListElements(document);

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer trans = transFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");

    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(document);
    trans.transform(source, result);
    /*
     * (?m) puts the regex into multiline mode:
     * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.
     * html#MULTILINE So the effect of this statement is
     * "remove any empty lines"
     */
    xml = writer.toString().replaceAll("(?m)^\\s+\\n", "");
    xml = xml + "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">" + maintenanceAction + "</"
            + MAINTENANCE_ACTION_ELEMENT_NAME + ">";

    // replace classnames not updated so far that were captured by smoke test below
    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("active defined-in=\"" + className + "\"")) {
            LOGGER.info("Replacing active defined-in= attribute: " + className + " with: "
                    + classNameRuleMap.get(className) + " at docid= " + docid);
            xml = xml.replace("active defined-in=\"" + className + "\"",
                    "active defined-in=\"" + classNameRuleMap.get(className) + "\"");
        }
    }

    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("<" + className + ">")) {
            LOGGER.info("Replacing open tag: <" + className + "> with: <" + classNameRuleMap.get(className)
                    + ">" + " at docid= " + docid);
            xml = xml.replace("<" + className + ">", "<" + classNameRuleMap.get(className) + ">");
        }
    }

    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("</" + className + ">")) {
            LOGGER.info("Replacing close tag: </" + className + "> with: </" + classNameRuleMap.get(className)
                    + ">" + " at docid= " + docid);
            xml = xml.replace("</" + className + ">", "</" + classNameRuleMap.get(className) + ">");
        }
    }

    // replace classnames not updated so far that were captured by smoke test below
    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("maintainableImplClass=\"" + className + "\"")) {
            LOGGER.info("Replacing maintainableImplClass= attribute: " + className + " with: "
                    + classNameRuleMap.get(className) + " at docid= " + docid);
            xml = xml.replace("maintainableImplClass=\"" + className + "\"",
                    "maintainableImplClass=\"" + classNameRuleMap.get(className) + "\"");
        }
    }

    // investigative logging, still useful as a smoke test
    for (String oldClassName : classNameRuleMap.keySet()) {
        if (xml.contains(oldClassName)) {
            LOGGER.warn("Document has classname in contents that should have been mapped: " + oldClassName);
            LOGGER.warn("at docid= " + docid + " for xml= " + xml);
        }
    }
    checkForElementsWithClassAttribute(document);
    return xml;
}