@Override protected Node toNode(AbstractWmlConversionContext context, R.Sym sym, Document doc) throws TransformerException { String value = sym.getChar(); // Pre-process according to ECMA-376 2.3.3.29 if (value.startsWith("F0") || value.startsWith("f0")) { value = value.substring(2); } Text theChar = doc.createTextNode(new String(hexStringToByteArray(value))); DocumentFragment docfrag = doc.createDocumentFragment(); String fontName = sym.getFont(); PhysicalFont pf = context.getWmlPackage().getFontMapper().getFontMappings().get(fontName); if (pf == null) { log.warn("No physical font present for:" + fontName); docfrag.appendChild(theChar); } else { Element span = doc.createElement("span"); docfrag.appendChild(span); span.setAttribute("style", "font-family:" + pf.getName()); span.appendChild(theChar); } return docfrag; }
/** * Create some content in the context of a given document * * @return * <ul> * <li>A {@link DocumentFragment} if <code>text</code> is well-formed. * <li><code>null</code>, if <code>text</code> is plain text or not well formed * </ul> */ static final DocumentFragment createContent(Document doc, String text) { // Text might hold XML content if (text != null && text.contains("<")) { DocumentBuilder builder = builder(); try { // [#128] Trimming will get rid of leading and trailing whitespace, which would // otherwise cause a HIERARCHY_REQUEST_ERR raised by the parser text = text.trim(); // There is a processing instruction. We can safely assume // valid XML and parse it as such if (text.startsWith("<?xml")) { Document parsed = builder.parse(new InputSource(new StringReader(text))); DocumentFragment fragment = parsed.createDocumentFragment(); fragment.appendChild(parsed.getDocumentElement()); return (DocumentFragment) doc.importNode(fragment, true); } // Any XML document fragment. To be on the safe side, fragments // are wrapped in a dummy root node else { String wrapped = "<dummy>" + text + "</dummy>"; Document parsed = builder.parse(new InputSource(new StringReader(wrapped))); DocumentFragment fragment = parsed.createDocumentFragment(); NodeList children = parsed.getDocumentElement().getChildNodes(); // appendChild removes children also from NodeList! while (children.getLength() > 0) { fragment.appendChild(children.item(0)); } return (DocumentFragment) doc.importNode(fragment, true); } } // This does not occur catch (IOException ignore) { } // The XML content is invalid catch (SAXException ignore) { } } // Plain text or invalid XML return null; }
public static DocumentFragment shapeToSVG(SvgConversionContext context, NodeIterator shapeIt) { DocumentFragment docfrag = null; Document d = null; try { Object shape = null; if (shapeIt != null) { Node n = shapeIt.nextNode(); if (n == null) { d = makeErr("[null node?!]"); } else { log.debug("Handling " + n.getNodeName()); if (n.getNodeName().equals("p:cxnSp")) { shape = nodeToObjectModel(n, CxnSp.class); d = CxnSpToSVG((CxnSp) shape); } else { log.info("** TODO " + n.getNodeName()); d = makeErr("[" + n.getNodeName() + "]"); } } } } catch (Exception e) { log.error(e.getMessage(), e); d = makeErr(e.getMessage()); } // Machinery docfrag = d.createDocumentFragment(); docfrag.appendChild(d.getDocumentElement()); return docfrag; }
/** * This method is an extension that implements as a Xalan extension the node-set function also * found in xt and saxon. If the argument is a Result Tree Fragment, then <code>nodeset</code> * returns a node-set consisting of a single root node as described in section 11.1 of the XSLT * 1.0 Recommendation. If the argument is a node-set, <code>nodeset</code> returns a node-set. If * the argument is a string, number, or boolean, then <code>nodeset</code> returns a node-set * consisting of a single root node with a single text node child that is the result of calling * the XPath string() function on the passed parameter. If the argument is anything else, then a * node-set is returned consisting of a single root node with a single text node child that is the * result of calling the java <code>toString()</code> method on the passed argument. Most of the * actual work here is done in <code>MethodResolver</code> and <code>XRTreeFrag</code>. * * @param myProcessor Context passed by the extension processor * @param rtf Argument in the stylesheet to the nodeset extension function * <p>NEEDSDOC ($objectName$) @return */ public static NodeSet nodeset(ExpressionContext myProcessor, Object rtf) { String textNodeValue; if (rtf instanceof NodeIterator) { return new NodeSet((NodeIterator) rtf); } else { if (rtf instanceof String) { textNodeValue = (String) rtf; } else if (rtf instanceof Boolean) { textNodeValue = new XBoolean(((Boolean) rtf).booleanValue()).str(); } else if (rtf instanceof Double) { textNodeValue = new XNumber(((Double) rtf).doubleValue()).str(); } else { textNodeValue = rtf.toString(); } // This no longer will work right since the DTM. // Document myDoc = myProcessor.getContextNode().getOwnerDocument(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document myDoc = db.newDocument(); Text textNode = myDoc.createTextNode(textNodeValue); DocumentFragment docFrag = myDoc.createDocumentFragment(); docFrag.appendChild(textNode); return new NodeSet(docFrag); } catch (ParserConfigurationException pce) { throw new org.apache.xml.utils.WrappedRuntimeException(pce); } } }
@Method("GET") @Path("?fragment") @requires("urn:test:grant") @Type("application/xml") public DocumentFragment fragment() throws ParserConfigurationException { Document doc = builder.newDocumentBuilder().newDocument(); DocumentFragment frag = doc.createDocumentFragment(); Element element = doc.createElement("fragment"); frag.appendChild(element); return frag; }
private DocumentFragment appendPushContent( final DocumentFragment pushcontent, final DocumentFragment target) { DocumentFragment df = target; if (df == null) { df = pushDocument.createDocumentFragment(); } final NodeList children = pushcontent.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { df.appendChild(pushDocument.importNode(children.item(i), true)); } return df; }
public static DocumentFragment createBlockForR( SvgConversionContext context, NodeIterator rPrNodeIt, NodeIterator childResults) { DocumentFragment docfrag = null; Document d = null; Element span = null; try { // Create a DOM builder and parse the fragment d = XmlUtils.getNewDocumentBuilder().newDocument(); span = d.createElement("span"); d.appendChild(span); CTTextCharacterProperties textCharProps = (CTTextCharacterProperties) nodeToObjectModel(rPrNodeIt.nextNode(), CTTextCharacterProperties.class); RPr rPr = TextStyles.getWmlRPr(textCharProps); // Does our rPr contain anything else? StringBuilder inlineStyle = new StringBuilder(); HtmlCssHelper.createCss(context.getPmlPackage(), rPr, inlineStyle); if (!inlineStyle.toString().equals("")) { span.setAttribute("style", inlineStyle.toString()); } Node n = childResults.nextNode(); XmlUtils.treeCopy(n, span); } catch (Exception e) { log.error(e.getMessage(), e); // If something went wrong with the formatting, // still try to display the text! Node n = childResults.nextNode(); XmlUtils.treeCopy(n, span); } // Machinery docfrag = d.createDocumentFragment(); docfrag.appendChild(d.getDocumentElement()); return docfrag; }
public static Node coerceToNode(ELContext ctx, Object value) { if (value == null) { return null; } else if (value instanceof XmlNode) { return ((XmlNode) value).toDOM(); } else if (value instanceof Node) { return (Node) value; } else if (value instanceof ClosureObject) { Object obj = ((ClosureObject) value).invoke(ctx, "toXML", ELUtils.NO_PARAMS); return coerceToNode(ctx, obj); } else if (value instanceof Iterable) { DocumentFragment frag = getContextDocument(ctx).createDocumentFragment(); for (Iterator i = ((Iterable) value).iterator(); i.hasNext(); ) frag.appendChild(coerceToNode(ctx, i.next())); return frag; } else { String text = TypeCoercion.coerceToString(value); return getContextDocument(ctx).createTextNode(text); } }
/** * Append a node to the current container. * * @param newNode New node to append */ protected void append(Node newNode) throws org.xml.sax.SAXException { Node currentNode = m_currentNode; if (null != currentNode) { currentNode.appendChild(newNode); // System.out.println(newNode.getNodeName()); } else if (null != m_docFrag) { m_docFrag.appendChild(newNode); } else { boolean ok = true; short type = newNode.getNodeType(); if (type == Node.TEXT_NODE) { String data = newNode.getNodeValue(); if ((null != data) && (data.trim().length() > 0)) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_CANT_OUTPUT_TEXT_BEFORE_DOC, null)); // "Warning: can't output text before document element! Ignoring..."); } ok = false; } else if (type == Node.ELEMENT_NODE) { if (m_doc.getDocumentElement() != null) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_CANT_HAVE_MORE_THAN_ONE_ROOT, null)); // "Can't have more than one root on a DOM!"); } } if (ok) m_doc.appendChild(newNode); } }
/** * @param ctx * @param inputSource * @return the Node resulting from the parse of the source * @throws XMLEncryptionException */ private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException { try { if (dbf == null) { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); dbf.setValidating(false); } DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(inputSource); Document contextDocument = null; if (Node.DOCUMENT_NODE == ctx.getNodeType()) { contextDocument = (Document) ctx; } else { contextDocument = ctx.getOwnerDocument(); } Element fragElt = (Element) contextDocument.importNode(d.getDocumentElement(), true); DocumentFragment result = contextDocument.createDocumentFragment(); Node child = fragElt.getFirstChild(); while (child != null) { fragElt.removeChild(child); result.appendChild(child); child = fragElt.getFirstChild(); } return result; } catch (SAXException se) { throw new XMLEncryptionException("empty", se); } catch (ParserConfigurationException pce) { throw new XMLEncryptionException("empty", pce); } catch (IOException ioe) { throw new XMLEncryptionException("empty", ioe); } }
public Node toNode(Model tableModel, TransformState transformState, Document doc) throws TransformerException { TableModel table = (TableModel) tableModel; getLog().debug("Table asXML:\n" + table.debugStr()); DocumentFragment docfrag = doc.createDocumentFragment(); Element tableRoot = createNode(doc, null, NODE_TABLE); List<Property> rowProperties = new ArrayList<Property>(); int rowPropertiesTableSize = -1; List<Property> cellProperties = new ArrayList<Property>(); int cellPropertiesTableSize = -1; int cellPropertiesRowSize = -1; boolean inHeader = (table.getHeaderMaxRow() > -1); TableModelRow rowModel = null; Element rowContainer = null; Element row = null; Element cellNode = null; createRowProperties(rowProperties, table.getEffectiveTableStyle().getTrPr(), true); rowPropertiesTableSize = rowProperties.size(); createCellProperties(cellProperties, table.getEffectiveTableStyle().getTrPr()); createCellProperties(cellProperties, table.getEffectiveTableStyle().getTcPr()); // will apply these as a default on each td, and then override createCellProperties(cellProperties, table.getEffectiveTableStyle().getTblPr()); cellPropertiesTableSize = cellProperties.size(); docfrag.appendChild(tableRoot); applyTableStyles(table, transformState, tableRoot); // setup column widths createColumns(table, transformState, doc, tableRoot); rowContainer = createNode(doc, tableRoot, (inHeader ? NODE_TABLE_HEADER : NODE_TABLE_BODY)); tableRoot.appendChild(rowContainer); applyTableRowContainerCustomAttributes(table, transformState, rowContainer, inHeader); for (int rowIndex = 0; rowIndex < table.getCells().size(); rowIndex++) { rowModel = table.getCells().get(rowIndex); if ((inHeader) && (rowIndex > table.getHeaderMaxRow())) { rowContainer = createNode(doc, tableRoot, NODE_TABLE_BODY); tableRoot.appendChild(rowContainer); inHeader = false; applyTableRowContainerCustomAttributes(table, transformState, rowContainer, inHeader); } row = createNode(doc, rowContainer, (inHeader ? NODE_TABLE_HEADER_ROW : NODE_TABLE_BODY_ROW)); TrPr trPr = rowModel.getRowProperties(); CTTblPrEx tblPrEx = rowModel.getRowPropertiesExceptions(); createRowProperties(rowProperties, trPr, false); processAttributes(rowProperties, row); applyTableRowCustomAttributes(table, transformState, row, rowIndex, inHeader); createCellProperties(cellProperties, trPr); createCellProperties(cellProperties, tblPrEx); cellPropertiesRowSize = cellProperties.size(); for (Cell cell : rowModel.getRowContents()) { // process cell if (cell.isDummy()) { if (!cell.isVMerged()) { // Dummy-Cells resulting from vertical merged cells shouldn't be included cellNode = createNode(doc, row, (inHeader ? NODE_TABLE_HEADER_CELL : NODE_TABLE_BODY_CELL)); row.appendChild(cellNode); applyTableCellCustomAttributes(table, transformState, cell, cellNode, inHeader, true); } } else { cellNode = createNode(doc, row, (inHeader ? NODE_TABLE_HEADER_CELL : NODE_TABLE_BODY_CELL)); row.appendChild(cellNode); // Apply cell style createCellProperties(cellProperties, cell.getTcPr()); processAttributes(cellProperties, cellNode); applyTableCellCustomAttributes(table, transformState, cell, cellNode, inHeader, false); // remove properties defined on cell level resetProperties(cellProperties, cellPropertiesRowSize); // insert content into cell // skipping w:tc node itself, insert only its children if (cell.getContent() == null) { getLog().warn("model cell had no contents!"); } else { getLog().debug("copying cell contents.."); XmlUtils.treeCopy(cell.getContent().getChildNodes(), cellNode); } } } // remove properties defined on row level resetProperties(cellProperties, cellPropertiesTableSize); resetProperties(rowProperties, rowPropertiesTableSize); } return docfrag; }
/** * Get references for a given article * * @param doc article xml * @return references */ public ArrayList<CitationReference> getReferences(Document doc) { ArrayList<CitationReference> list = new ArrayList<CitationReference>(); if (doc == null) { return list; } try { NodeList refList = getReferenceNodes(doc); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation | //element-citation"); XPathExpression titleExpr = xpath.compile("//article-title"); XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name"); XPathExpression journalExpr = xpath.compile("//source"); XPathExpression volumeExpr = xpath.compile("//volume"); XPathExpression numberExpr = xpath.compile("//label"); XPathExpression fPageExpr = xpath.compile("//fpage"); XPathExpression lPageExpr = xpath.compile("//lpage"); XPathExpression yearExpr = xpath.compile("//year"); XPathExpression publisherExpr = xpath.compile("//publisher-name"); for (int i = 0; i < refList.getLength(); i++) { Node refNode = refList.item(i); CitationReference citation = new CitationReference(); DocumentFragment df = doc.createDocumentFragment(); df.appendChild(refNode); // citation type Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE); Node resultNode = (Node) resultObj; if (resultNode != null) { String citationType = getCitationType(resultNode); if (citationType != null) { citation.setCitationType(citationType); } } // title resultObj = titleExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setTitle(resultNode.getTextContent()); } // authors resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET); NodeList resultNodeList = (NodeList) resultObj; ArrayList<String> authors = new ArrayList<String>(); for (int j = 0; j < resultNodeList.getLength(); j++) { Node nameNode = resultNodeList.item(j); NodeList namePartList = nameNode.getChildNodes(); String surName = ""; String givenName = ""; for (int k = 0; k < namePartList.getLength(); k++) { Node namePartNode = namePartList.item(k); if (namePartNode.getNodeName().equals("surname")) { surName = namePartNode.getTextContent(); } else if (namePartNode.getNodeName().equals("given-names")) { givenName = namePartNode.getTextContent(); } } authors.add(givenName + " " + surName); } citation.setAuthors(authors); // journal title resultObj = journalExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setJournalTitle(resultNode.getTextContent()); } // volume resultObj = volumeExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setVolume(resultNode.getTextContent()); } // citation number resultObj = numberExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setNumber(resultNode.getTextContent()); } // citation pages String firstPage = null; String lastPage = null; resultObj = fPageExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { firstPage = resultNode.getTextContent(); } resultObj = lPageExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { lastPage = resultNode.getTextContent(); } if (firstPage != null) { if (lastPage != null) { citation.setPages(firstPage + "-" + lastPage); } else { citation.setPages(firstPage); } } // citation year resultObj = yearExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setYear(resultNode.getTextContent()); } // citation publisher resultObj = publisherExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setPublisher(resultNode.getTextContent()); } list.add(citation); } } catch (Exception e) { log.error("Error occurred while gathering the citation references.", e); } return list; }
public static DocumentFragment createBlockForP( SvgConversionContext context, String lvl, String cNvPrName, String phType, NodeIterator childResults, NodeIterator lvlNpPr) { StyleTree styleTree = null; try { styleTree = context.getPmlPackage().getStyleTree(); } catch (InvalidFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } log.debug("lvl:" + lvl); int level; if (lvl.equals("NaN")) { level = 1; } else { level = Integer.parseInt(lvl); } String pStyleVal; System.out.println("cNvPrName: " + cNvPrName + "; " + "phType: " + phType); if (cNvPrName.toLowerCase().indexOf("subtitle") > -1 || phType.toLowerCase().indexOf("subtitle") > -1) { // Subtitle on first page in default layout is styled as a Body. pStyleVal = "Lvl" + level + "Master" + context.getResolvedLayout().getMasterNumber() + "Body"; } else if (cNvPrName.toLowerCase().indexOf("title") > -1 || phType.toLowerCase().indexOf("title") > -1) { pStyleVal = "Lvl" + level + "Master" + context.getResolvedLayout().getMasterNumber() + "Title"; } else { // eg cNvPrName: TextBox 2; phType: pStyleVal = "Lvl" + level + "Master" + context.getResolvedLayout().getMasterNumber() + "Other"; } System.out.println("--> " + pStyleVal); try { // Create a DOM builder and parse the fragment Document document = XmlUtils.getNewDocumentBuilder().newDocument(); // log.info("Document: " + document.getClass().getName() ); Node xhtmlP = document.createElement("p"); document.appendChild(xhtmlP); // Set @class log.debug(pStyleVal); Tree<AugmentedStyle> pTree = styleTree.getParagraphStylesTree(); org.docx4j.model.styles.Node<AugmentedStyle> asn = pTree.get(pStyleVal); ((Element) xhtmlP).setAttribute("class", StyleTree.getHtmlClassAttributeValue(pTree, asn)); StringBuilder inlineStyle = new StringBuilder(); // Do we have CTTextParagraphProperties // <a:lvl?pPr> // Convert it to a WordML pPr CTTextParagraphProperties lvlPPr = unmarshalFormatting(lvlNpPr); if (lvlPPr != null) { log.debug("We have lvlPPr"); log.debug( XmlUtils.marshaltoString( lvlPPr, true, true, Context.jcPML, "FIXME", "lvl1pPr", CTTextParagraphProperties.class)); PPr pPr = TextStyles.getWmlPPr(lvlPPr); if (pPr != null) { HtmlCssHelper.createCss(context.getPmlPackage(), pPr, inlineStyle, false, false); } // TODO RPR } // Without this, top-margin is too large in Webkit (Midor). // Not tested elsewhere... inlineStyle.append("margin-left:3px; margin-top:3px;"); if (!inlineStyle.toString().equals("")) { ((Element) xhtmlP).setAttribute("style", inlineStyle.toString()); } // Our fo:block wraps whatever result tree fragment // our style sheet produced when it applied-templates // to the child nodes // init Node n = childResults.nextNode(); do { // getNumberXmlNode creates a span node, which is empty // if there is no numbering. // Let's get rid of any such <span/>. // What we actually get is a document node if (n.getNodeType() == Node.DOCUMENT_NODE) { log.debug("handling DOCUMENT_NODE"); // Do just enough of the handling here NodeList nodes = n.getChildNodes(); if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { if (((Node) nodes.item(i)).getLocalName().equals("span") && !((Node) nodes.item(i)).hasChildNodes()) { // ignore log.debug(".. ignoring <span/> "); } else { XmlUtils.treeCopy((Node) nodes.item(i), xhtmlP); } } } } else { // log.info("Node we are importing: " + n.getClass().getName() ); // foBlockElement.appendChild( // document.importNode(n, true) ); /* * Node we'd like to import is of type org.apache.xml.dtm.ref.DTMNodeProxy * which causes * org.w3c.dom.DOMException: NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation. * * See http://osdir.com/ml/text.xml.xerces-j.devel/2004-04/msg00066.html * * So instead of importNode, use */ XmlUtils.treeCopy(n, xhtmlP); } // next n = childResults.nextNode(); } while (n != null); DocumentFragment docfrag = document.createDocumentFragment(); docfrag.appendChild(document.getDocumentElement()); return docfrag; } catch (Exception e) { log.error(e.getMessage(), e); } return null; }