Search in sources :

Example 51 with XmlException

use of org.apache.xmlbeans.XmlException in project knime-core by knime.

the class PMMLUtils method getUpdatedVersionAndNamespace.

/**
 * Update the namespace and version of the document to PMML 4.2. This method forces an update of the header so
 * the caller should make sure it's compatible with 4.2 (in the sense that there haven't been changes to the
 * any of the fields in the models that KNIME can read).
 *
 * @param xmlDoc the {@link XmlObject} to update the namespace
 * @return the updated PMML
 * @throws XmlException when the PMML element could not be updated to 4.2
 */
public static String getUpdatedVersionAndNamespace(final XmlObject xmlDoc) throws XmlException {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        String encoding = xmlDoc.documentProperties().getEncoding();
        if (encoding == null) {
            // use utf-8 as default encoding if none is set
            encoding = "UTF-8";
        }
        // see bug 6306 - XML 1.1 features not parsed 'correctly'
        ByteArrayInputStream inputStream = new ByteArrayInputStream(PMMLFormatter.xmlText(xmlDoc).getBytes(encoding));
        Document doc = builder.parse(inputStream);
        inputStream.close();
        updatePmmlNamespaceAndVersion(doc);
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        writer.flush();
        return writer.toString();
    } catch (IOException | ParserConfigurationException | SAXException | TransformerException e) {
        throw new XmlException("Could not update PMML document.", e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) IOException(java.io.IOException) PMMLDocument(org.dmg.pmml.PMMLDocument) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XmlException(org.apache.xmlbeans.XmlException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 52 with XmlException

use of org.apache.xmlbeans.XmlException in project knime-core by knime.

the class PMMLUtils method updatePmmlNamespaceAndVersion.

/**
 * Sets the namespace and version of the document to PMML 4.2. Caller needs to make sure that this is a
 * safe operation.
 *
 * @param document the document to update the namespace
 * @throws XmlException when the PMML element could not be updated to 4.2
 */
public static void updatePmmlNamespaceAndVersion(final Document document) throws XmlException {
    Element root = document.getDocumentElement();
    String rootPrefix = root.getPrefix();
    fixNamespace(document, root, rootPrefix);
    NodeList nodeList = document.getElementsByTagName("PMML");
    Node pmmlNode = nodeList.item(0);
    if (pmmlNode == null) {
        throw new XmlException("Invalid PMML document without a PMML element encountered.");
    }
    Node version = pmmlNode.getAttributes().getNamedItem("version");
    version.setNodeValue(PMML_V42);
}
Also used : XmlException(org.apache.xmlbeans.XmlException) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node)

Example 53 with XmlException

use of org.apache.xmlbeans.XmlException in project knime-core by knime.

the class SubNodeContainer method getXMLDescriptionForPorts.

/**
 * @return a DOM which describes only the port connections.
 */
public Element getXMLDescriptionForPorts() {
    try {
        // Document
        final Document doc = NodeDescription.getDocumentBuilderFactory().newDocumentBuilder().getDOMImplementation().createDocument("http://knime.org/node2012", "knimeNode", null);
        addPortDescriptionToElement(doc, getMetadata(), getNrInPorts(), getNrOutPorts());
        // we avoid validating the document since we don't include certain elements like 'name'
        return (new NodeDescription27Proxy(doc, false)).getXMLDescription();
    } catch (ParserConfigurationException | DOMException | XmlException e) {
        LOGGER.warn("Could not generate ports description", e);
    }
    return null;
}
Also used : DOMException(org.w3c.dom.DOMException) NodeDescription27Proxy(org.knime.core.node.NodeDescription27Proxy) XmlException(org.apache.xmlbeans.XmlException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Document(org.w3c.dom.Document)

Example 54 with XmlException

use of org.apache.xmlbeans.XmlException in project hackpad by dropbox.

the class XML method createFromJS.

static XML createFromJS(XMLLibImpl lib, Object inputObject) {
    XmlObject xo;
    boolean isText = false;
    String frag;
    if (inputObject == null || inputObject == Undefined.instance) {
        frag = "";
    } else if (inputObject instanceof XMLObjectImpl) {
        // todo: faster way for XMLObjects?
        frag = ((XMLObjectImpl) inputObject).toXMLString(0);
    } else {
        if (inputObject instanceof Wrapper) {
            Object wrapped = ((Wrapper) inputObject).unwrap();
            if (wrapped instanceof XmlObject) {
                return createFromXmlObject(lib, (XmlObject) wrapped);
            }
        }
        frag = ScriptRuntime.toString(inputObject);
    }
    if (frag.trim().startsWith("<>")) {
        throw ScriptRuntime.typeError("Invalid use of XML object anonymous tags <></>.");
    }
    if (frag.indexOf("<") == -1) {
        // Must be solo text node, wrap in XML fragment
        isText = true;
        frag = "<textFragment>" + frag + "</textFragment>";
    }
    XmlOptions options = new XmlOptions();
    if (lib.ignoreComments) {
        options.put(XmlOptions.LOAD_STRIP_COMMENTS);
    }
    if (lib.ignoreProcessingInstructions) {
        options.put(XmlOptions.LOAD_STRIP_PROCINSTS);
    }
    if (lib.ignoreWhitespace) {
        options.put(XmlOptions.LOAD_STRIP_WHITESPACE);
    }
    try {
        xo = XmlObject.Factory.parse(frag, options);
        // Apply the default namespace
        Context cx = Context.getCurrentContext();
        String defaultURI = lib.getDefaultNamespaceURI(cx);
        if (defaultURI.length() > 0) {
            XmlCursor cursor = xo.newCursor();
            boolean isRoot = true;
            while (!cursor.toNextToken().isEnddoc()) {
                if (!cursor.isStart())
                    continue;
                // Check if this element explicitly sets the
                // default namespace
                boolean defaultNSDeclared = false;
                cursor.push();
                while (cursor.toNextToken().isAnyAttr()) {
                    if (cursor.isNamespace()) {
                        if (cursor.getName().getLocalPart().length() == 0) {
                            defaultNSDeclared = true;
                            break;
                        }
                    }
                }
                cursor.pop();
                if (defaultNSDeclared) {
                    cursor.toEndToken();
                    continue;
                }
                // Check if this element's name is in no namespace
                javax.xml.namespace.QName qname = cursor.getName();
                if (qname.getNamespaceURI().length() == 0) {
                    // Change the namespace
                    qname = new javax.xml.namespace.QName(defaultURI, qname.getLocalPart());
                    cursor.setName(qname);
                }
                if (isRoot) {
                    // Declare the default namespace
                    cursor.push();
                    cursor.toNextToken();
                    cursor.insertNamespace("", defaultURI);
                    cursor.pop();
                    isRoot = false;
                }
            }
            cursor.dispose();
        }
    } catch (XmlException xe) {
        /*
todo need to handle namespace prefix not found in XML look for namespace type in the scope change.

            String errorMsg = "Use of undefined namespace prefix: ";
            String msg = xe.getError().getMessage();
            if (msg.startsWith(errorMsg))
            {
                String prefix = msg.substring(errorMsg.length());
            }
*/
        String errMsg = xe.getMessage();
        if (errMsg.equals("error: Unexpected end of file after null")) {
            // Create an empty document.
            xo = XmlObject.Factory.newInstance();
        } else {
            throw ScriptRuntime.typeError(xe.getMessage());
        }
    } catch (Throwable e) {
        // todo: TLL Catch specific exceptions during parse.
        throw ScriptRuntime.typeError("Not Parsable as XML");
    }
    XmlCursor curs = xo.newCursor();
    if (curs.currentTokenType().isStartdoc()) {
        curs.toFirstContentToken();
    }
    if (isText) {
        // Move it to point to the text node
        curs.toFirstContentToken();
    }
    XScriptAnnotation anno;
    try {
        anno = new XScriptAnnotation(curs);
        curs.setBookmark(anno);
    } finally {
        curs.dispose();
    }
    return new XML(lib, anno);
}
Also used : XmlOptions(org.apache.xmlbeans.XmlOptions) XmlCursor(org.apache.xmlbeans.XmlCursor) XmlException(org.apache.xmlbeans.XmlException) XmlObject(org.apache.xmlbeans.XmlObject) XmlObject(org.apache.xmlbeans.XmlObject)

Example 55 with XmlException

use of org.apache.xmlbeans.XmlException in project poi by apache.

the class XWPFFootnotes method onDocumentRead.

/**
     * Read document
     */
@Override
protected void onDocumentRead() throws IOException {
    FootnotesDocument notesDoc;
    InputStream is = null;
    try {
        is = getPackagePart().getInputStream();
        notesDoc = FootnotesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
        ctFootnotes = notesDoc.getFootnotes();
    } catch (XmlException e) {
        throw new POIXMLException();
    } finally {
        if (is != null) {
            is.close();
        }
    }
    // Find our footnotes
    for (CTFtnEdn note : ctFootnotes.getFootnoteArray()) {
        listFootnote.add(new XWPFFootnote(note, this));
    }
}
Also used : CTFtnEdn(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn) InputStream(java.io.InputStream) XmlException(org.apache.xmlbeans.XmlException) FootnotesDocument(org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument) POIXMLException(org.apache.poi.POIXMLException)

Aggregations

XmlException (org.apache.xmlbeans.XmlException)112 XmlObject (org.apache.xmlbeans.XmlObject)45 IOException (java.io.IOException)35 DecodingException (org.n52.svalbard.decode.exception.DecodingException)19 EncodingException (org.n52.svalbard.encode.exception.EncodingException)17 POIXMLException (org.apache.poi.POIXMLException)15 InputStream (java.io.InputStream)11 ArrayList (java.util.ArrayList)10 XmlCursor (org.apache.xmlbeans.XmlCursor)10 XmlOptions (org.apache.xmlbeans.XmlOptions)10 OpenXML4JException (org.apache.poi.openxml4j.exceptions.OpenXML4JException)8 POIXMLDocumentPart (org.apache.poi.POIXMLDocumentPart)7 AbstractFeature (org.n52.shetland.ogc.gml.AbstractFeature)7 Geometry (org.locationtech.jts.geom.Geometry)6 Document (org.w3c.dom.Document)6 Node (org.w3c.dom.Node)6 DataAccessException (com.centurylink.mdw.common.exception.DataAccessException)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 File (java.io.File)5