/** * 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; }
void doApply( Stylesheet stylesheet, QName mode, Node context, int pos, int len, Node parent, Node nextSibling) throws TransformerException { Document doc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); DocumentFragment fragment = doc.createDocumentFragment(); format.apply(stylesheet, mode, context, pos, len, fragment, null); String f = Expr._string(context, Collections.singleton(fragment)); String value = format(f, compute(stylesheet, context, pos, len)); Text text = doc.createTextNode(value); if (nextSibling != null) { parent.insertBefore(text, nextSibling); } else { parent.appendChild(text); } // xsl:number doesn't process children if (next != null) { next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); } }
/** * 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); } } }
/** * Parses a string containing XML and returns a DocumentFragment containing the nodes of the * parsed XML. */ public static void loadFragment(Element el, String fragment) { // Wrap the fragment in an arbitrary element fragment = "<fragment>" + fragment + "</fragment>"; try { // Create a DOM builder and parse the fragment DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment))); Document doc = el.getOwnerDocument(); // Import the nodes of the new document into doc so that they // will be compatible with doc Node node = doc.importNode(d.getDocumentElement(), true); // Create the document fragment node to hold the new nodes DocumentFragment docfrag = doc.createDocumentFragment(); // Move the nodes into the fragment while (node.hasChildNodes()) { el.appendChild(node.removeChild(node.getFirstChild())); } } catch (Exception e) { log.error(e, e); } }
@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; }
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; }
private XMLStreamWriter getXMLStreamWriter() { pushcontentDocumentFragment = pushDocument.createDocumentFragment(); try { return XMLOutputFactory.newInstance() .createXMLStreamWriter(new DOMResult(pushcontentDocumentFragment)); } catch (final XMLStreamException | FactoryConfigurationError e) { throw new RuntimeException(e); } }
protected void convertToNode( CC conversionContext, Object unmarshalledNode, String modelId, Document document, Node parentNode) throws DOMException { // To use our existing model, first we need childResults. // We get these using a new Generator object. log.debug(modelId); DocumentFragment childResults = null; if (unmarshalledNode instanceof ContentAccessor) { childResults = document.createDocumentFragment(); AbstractVisitorExporterGenerator<CC> generator = getFactory().createInstance(conversionContext, document, childResults); new TraversalUtil(((ContentAccessor) unmarshalledNode).getContent(), generator); } else if (unmarshalledNode instanceof org.docx4j.wml.Pict) { // if it contains a textbox.. // repeating this... org.docx4j.vml.CTTextbox textBox = getTextBox((org.docx4j.wml.Pict) unmarshalledNode); if (textBox != null) { childResults = document.createDocumentFragment(); AbstractVisitorExporterGenerator<CC> generator = getFactory().createInstance(conversionContext, document, childResults); new TraversalUtil(textBox.getTxbxContent().getContent(), generator); } } Node resultNode = conversionContext .getWriterRegistry() .toNode(conversionContext, unmarshalledNode, modelId, childResults, document); if (resultNode != null) { log.debug("Appending " + XmlUtils.w3CDomNodeToString(resultNode)); parentNode.appendChild(resultNode); } }
@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; }
@NotNull @Override public SimpleAdapter marshal(@NotNull final XmlSerializable v) throws Exception { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final Document document = dbf.newDocumentBuilder().newDocument(); final DocumentFragment content = document.createDocumentFragment(); final XMLOutputFactory xof = XMLOutputFactory.newFactory(); final XMLStreamWriter out = xof.createXMLStreamWriter(new DOMResult(content)); v.serialize(XmlStreaming.newWriter(new DOMResult(content))); final int childCount = content.getChildNodes().getLength(); if (childCount == 0) { return new SimpleAdapter(); } else if (childCount == 1) { final SimpleAdapter result = new SimpleAdapter(); final Node child = content.getFirstChild(); if (child instanceof Element) { result.setAttributes(child.getAttributes()); for (Node child2 = child.getFirstChild(); child2 != null; child2 = child2.getNextSibling()) { result.children.add(child2); } } else { result.children.add(child); } return result; } else { // More than one child final SimpleAdapter result = new SimpleAdapter(); for (Node child = content.getFirstChild(); child != null; child = child.getNextSibling()) { result.children.add(child); } return result; } }
/** * @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; }
/** * Adjust column widths in an HTML table. * * <p>The specification of column widths in CALS (a relative width plus an optional absolute * width) are incompatible with HTML column widths. This method adjusts CALS column width * specifiers in an attempt to produce equivalent HTML specifiers. * * <p>In order for this method to work, the CALS width specifications should be placed in the * "width" attribute of the <col>s within a <colgroup>. Then the colgroup result tree * fragment is passed to this method. * * <p>This method makes use of two parameters from the XSL stylesheet that calls it: <code> * nominal.table.width</code> and <code>table.width</code>. The value of <code>nominal.table.width * </code> must be an absolute distance. The value of <code>table.width</code> can be either * absolute or relative. * * <p>Presented with a mixture of relative and absolute lengths, the table width is used to * calculate appropriate values. If the <code>table.width</code> is relative, the nominal width is * used for this calculation. * * <p>There are three possible combinations of values: * * <ol> * <li>There are no relative widths; in this case the absolute widths are used in the HTML * table. * <li>There are no absolute widths; in this case the relative widths are used in the HTML * table. * <li>There are a mixture of absolute and relative widths: * <ol> * <li>If the table width is absolute, all widths become absolute. * <li>If the table width is relative, make all the widths absolute relative to the * nominal table width then turn them all back into relative widths. * </ol> * </ol> * * @param context The stylesheet context; supplied automatically by Xalan * @param xalanNI * @return The result tree fragment containing the adjusted colgroup. */ public DocumentFragment adjustColumnWidths(ExpressionContext context, NodeIterator xalanNI) { int nominalWidth = convertLength(Params.getString(context, "nominal.table.width")); String tableWidth = Params.getString(context, "table.width"); String styleType = Params.getString(context, "stylesheet.result.type"); boolean foStylesheet = styleType.equals("fo"); DocumentFragment xalanRTF = (DocumentFragment) xalanNI.nextNode(); Element colgroup = (Element) xalanRTF.getFirstChild(); // N.B. ...stree.ElementImpl doesn't implement getElementsByTagName() Node firstCol = null; // If this is an FO tree, there might be no colgroup... if (colgroup.getLocalName().equals("colgroup")) { firstCol = colgroup.getFirstChild(); } else { firstCol = colgroup; } // Count the number of columns... Node child = firstCol; int numColumns = 0; while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE && (child.getNodeName().equals("col") || (child.getNamespaceURI().equals(foURI) && child.getLocalName().equals("table-column")))) { numColumns++; } child = child.getNextSibling(); } String widths[] = new String[numColumns]; Element columns[] = new Element[numColumns]; int colnum = 0; child = firstCol; while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE && (child.getNodeName().equals("col") || (child.getNamespaceURI().equals(foURI) && child.getLocalName().equals("table-column")))) { Element col = (Element) child; columns[colnum] = col; if (foStylesheet) { if ("".equals(col.getAttribute("column-width"))) { widths[colnum] = "1*"; } else { widths[colnum] = col.getAttribute("column-width"); } } else { if ("".equals(col.getAttribute("width"))) { widths[colnum] = "1*"; } else { widths[colnum] = col.getAttribute("width"); } } colnum++; } child = child.getNextSibling(); } float relTotal = 0; float relParts[] = new float[numColumns]; float absTotal = 0; float absParts[] = new float[numColumns]; for (int count = 0; count < numColumns; count++) { String width = widths[count]; int pos = width.indexOf("*"); if (pos >= 0) { String relPart = width.substring(0, pos); String absPart = width.substring(pos + 1); try { float rel = Float.parseFloat(relPart); relTotal += rel; relParts[count] = rel; } catch (NumberFormatException e) { System.out.println(relPart + " is not a valid relative unit."); } int pixels = 0; if (absPart != null && !absPart.equals("")) { pixels = convertLength(absPart); } absTotal += pixels; absParts[count] = pixels; } else { relParts[count] = 0; int pixels = 0; if (width != null && !width.equals("")) { pixels = convertLength(width); } absTotal += pixels; absParts[count] = pixels; } } // Ok, now we have the relative widths and absolute widths in // two parallel arrays. // // - If there are no relative widths, output the absolute widths // - If there are no absolute widths, output the relative widths // - If there are a mixture of relative and absolute widths, // - If the table width is absolute, turn these all into absolute // widths. // - If the table width is relative, turn these all into absolute // widths in the nominalWidth and then turn them back into // percentages. if (relTotal == 0) { for (int count = 0; count < numColumns; count++) { Float f = new Float(absParts[count]); if (foStylesheet) { int pixels = f.intValue(); float inches = (float) pixels / pixelsPerInch; widths[count] = inches + "in"; } else { widths[count] = Integer.toString(f.intValue()); } } } else if (absTotal == 0) { for (int count = 0; count < numColumns; count++) { float rel = relParts[count] / relTotal * 100; Float f = new Float(rel); widths[count] = Integer.toString(f.intValue()); } widths = correctRoundingError(widths); } else { int pixelWidth = nominalWidth; if (tableWidth.indexOf("%") <= 0) { pixelWidth = convertLength(tableWidth); } if (pixelWidth <= absTotal) { System.out.println("Table is wider than table width."); } else { pixelWidth -= absTotal; } absTotal = 0; for (int count = 0; count < numColumns; count++) { float rel = relParts[count] / relTotal * pixelWidth; relParts[count] = rel + absParts[count]; absTotal += rel + absParts[count]; } if (tableWidth.indexOf("%") <= 0) { for (int count = 0; count < numColumns; count++) { Float f = new Float(relParts[count]); if (foStylesheet) { int pixels = f.intValue(); float inches = (float) pixels / pixelsPerInch; widths[count] = inches + "in"; } else { widths[count] = Integer.toString(f.intValue()); } } } else { for (int count = 0; count < numColumns; count++) { float rel = relParts[count] / absTotal * 100; Float f = new Float(rel); widths[count] = Integer.toString(f.intValue()); } widths = correctRoundingError(widths); } } // Now rebuild the colgroup with the right widths DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { System.out.println("PCE!"); return xalanRTF; } Document doc = docBuilder.newDocument(); DocumentFragment df = doc.createDocumentFragment(); DOMBuilder rtf = new DOMBuilder(doc, df); try { String ns = colgroup.getNamespaceURI(); String localName = colgroup.getLocalName(); String name = colgroup.getTagName(); if (colgroup.getLocalName().equals("colgroup")) { rtf.startElement(ns, localName, name, copyAttributes(colgroup)); } for (colnum = 0; colnum < numColumns; colnum++) { Element col = columns[colnum]; NamedNodeMap domAttr = col.getAttributes(); AttributesImpl attr = new AttributesImpl(); for (int acount = 0; acount < domAttr.getLength(); acount++) { Node a = domAttr.item(acount); String a_ns = a.getNamespaceURI(); String a_localName = a.getLocalName(); if ((foStylesheet && !a_localName.equals("column-width")) || !a_localName.equalsIgnoreCase("width")) { attr.addAttribute( a.getNamespaceURI(), a.getLocalName(), a.getNodeName(), "CDATA", a.getNodeValue()); } } if (foStylesheet) { attr.addAttribute("", "column-width", "column-width", "CDATA", widths[colnum]); } else { attr.addAttribute("", "width", "width", "CDATA", widths[colnum]); } rtf.startElement(col.getNamespaceURI(), col.getLocalName(), col.getTagName(), attr); rtf.endElement(col.getNamespaceURI(), col.getLocalName(), col.getTagName()); } if (colgroup.getLocalName().equals("colgroup")) { rtf.endElement(ns, localName, name); } } catch (SAXException se) { System.out.println("SE!"); return xalanRTF; } return df; }
/** * 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; }
@Override public DocumentFragment createDocumentFragment() { return doc.createDocumentFragment(); }
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; }
// J2SE does not support Xalan interpretive // main -> _main public static void _main(String argv[]) { // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off boolean doStackDumpOnError = false; boolean setQuietMode = false; boolean doDiag = false; String msg = null; boolean isSecureProcessing = false; // Runtime.getRuntime().traceMethodCalls(false); // Runtime.getRuntime().traceInstructions(false); /** The default diagnostic writer... */ java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true); java.io.PrintWriter dumpWriter = diagnosticsWriter; ResourceBundle resbundle = (SecuritySupport.getResourceBundle( com.sun.org.apache.xml.internal.utils.res.XResourceBundle.ERROR_RESOURCES)); String flavor = "s2s"; if (argv.length < 1) { printArgOptions(resbundle); } else { // J2SE does not support Xalan interpretive // false -> true boolean useXSLTC = true; for (int i = 0; i < argv.length; i++) { if ("-XSLTC".equalsIgnoreCase(argv[i])) { useXSLTC = true; } } TransformerFactory tfactory; if (useXSLTC) { String key = "javax.xml.transform.TransformerFactory"; String value = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; Properties props = System.getProperties(); props.put(key, value); System.setProperties(props); } try { tfactory = TransformerFactory.newInstance(); tfactory.setErrorListener(new DefaultErrorHandler()); } catch (TransformerFactoryConfigurationError pfe) { pfe.printStackTrace(dumpWriter); // "XSL Process was not successful."); msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null); diagnosticsWriter.println(msg); tfactory = null; // shut up compiler doExit(msg); } boolean formatOutput = false; boolean useSourceLocation = false; String inFileName = null; String outFileName = null; String dumpFileName = null; String xslFileName = null; String treedumpFileName = null; // J2SE does not support Xalan interpretive /* PrintTraceListener tracer = null; */ String outputType = null; String media = null; Vector params = new Vector(); boolean quietConflictWarnings = false; URIResolver uriResolver = null; EntityResolver entityResolver = null; ContentHandler contentHandler = null; int recursionLimit = -1; for (int i = 0; i < argv.length; i++) { if ("-XSLTC".equalsIgnoreCase(argv[i])) { // The -XSLTC option has been processed. } // J2SE does not support Xalan interpretive /* else if ("-TT".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceTemplates = true; } else printInvalidXSLTCOption("-TT"); // tfactory.setTraceTemplates(true); } else if ("-TG".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceGeneration = true; } else printInvalidXSLTCOption("-TG"); // tfactory.setTraceSelect(true); } else if ("-TS".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceSelection = true; } else printInvalidXSLTCOption("-TS"); // tfactory.setTraceTemplates(true); } else if ("-TTC".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceElements = true; } else printInvalidXSLTCOption("-TTC"); // tfactory.setTraceTemplateChildren(true); } */ else if ("-INDENT".equalsIgnoreCase(argv[i])) { int indentAmount; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { indentAmount = Integer.parseInt(argv[++i]); } else { indentAmount = 0; } // TBD: // xmlProcessorLiaison.setIndent(indentAmount); } else if ("-IN".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') inFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-IN"})); // "Missing argument for); } else if ("-MEDIA".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) media = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-MEDIA"})); // "Missing argument for); } else if ("-OUT".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') outFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-OUT"})); // "Missing argument for); } else if ("-XSL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') xslFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XSL"})); // "Missing argument for); } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { flavor = argv[++i]; } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-FLAVOR"})); // "Missing argument for); } else if ("-PARAM".equalsIgnoreCase(argv[i])) { if (i + 2 < argv.length) { String name = argv[++i]; params.addElement(name); String expression = argv[++i]; params.addElement(expression); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-PARAM"})); // "Missing argument for); } else if ("-E".equalsIgnoreCase(argv[i])) { // TBD: // xmlProcessorLiaison.setShouldExpandEntityRefs(false); } else if ("-V".equalsIgnoreCase(argv[i])) { diagnosticsWriter.println( resbundle.getString("version") // ">>>>>>> Xalan Version " + Version.getVersion() + ", " + /* xmlProcessorLiaison.getParserDescription()+ */ resbundle.getString("version2")); // "<<<<<<<"); } // J2SE does not support Xalan interpretive /* else if ("-QC".equalsIgnoreCase(argv[i])) { if (!useXSLTC) quietConflictWarnings = true; else printInvalidXSLTCOption("-QC"); } */ else if ("-Q".equalsIgnoreCase(argv[i])) { setQuietMode = true; } else if ("-DIAG".equalsIgnoreCase(argv[i])) { doDiag = true; } else if ("-XML".equalsIgnoreCase(argv[i])) { outputType = "xml"; } else if ("-TEXT".equalsIgnoreCase(argv[i])) { outputType = "text"; } else if ("-HTML".equalsIgnoreCase(argv[i])) { outputType = "html"; } else if ("-EDUMP".equalsIgnoreCase(argv[i])) { doStackDumpOnError = true; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { dumpFileName = argv[++i]; } } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { uriResolver = (URIResolver) ObjectFactory.newInstance(argv[++i], true); tfactory.setURIResolver(uriResolver); } catch (ConfigurationError cnfe) { msg = XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] {"-URIResolver"}); System.err.println(msg); doExit(msg); } } else { msg = XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-URIResolver"}); // "Missing argument for); System.err.println(msg); doExit(msg); } } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { entityResolver = (EntityResolver) ObjectFactory.newInstance(argv[++i], true); } catch (ConfigurationError cnfe) { msg = XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] {"-EntityResolver"}); System.err.println(msg); doExit(msg); } } else { // "Missing argument for); msg = XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-EntityResolver"}); System.err.println(msg); doExit(msg); } } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { contentHandler = (ContentHandler) ObjectFactory.newInstance(argv[++i], true); } catch (ConfigurationError cnfe) { msg = XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] {"-ContentHandler"}); System.err.println(msg); doExit(msg); } } else { // "Missing argument for); msg = XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-ContentHandler"}); System.err.println(msg); doExit(msg); } } // J2SE does not support Xalan interpretive /* else if ("-L".equalsIgnoreCase(argv[i])) { if (!useXSLTC) tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); else printInvalidXSLTCOption("-L"); } else if ("-INCREMENTAL".equalsIgnoreCase(argv[i])) { if (!useXSLTC) tfactory.setAttribute ("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); else printInvalidXSLTCOption("-INCREMENTAL"); } else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i])) { // Default is true. // // %REVIEW% We should have a generalized syntax for negative // switches... and probably should accept the inverse even // if it is the default. if (!useXSLTC) tfactory.setAttribute ("http://xml.apache.org/xalan/features/optimize", java.lang.Boolean.FALSE); else printInvalidXSLTCOption("-NOOPTIMIZE"); } else if ("-RL".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (i + 1 < argv.length) recursionLimit = Integer.parseInt(argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-rl" })); //"Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXSLTCOption("-RL"); } } */ // Generate the translet class and optionally specify the name // of the translet class. else if ("-XO".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') { tfactory.setAttribute("generate-translet", "true"); tfactory.setAttribute("translet-name", argv[++i]); } else tfactory.setAttribute("generate-translet", "true"); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XO"); } } // Specify the destination directory for the translet classes. else if ("-XD".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') tfactory.setAttribute("destination-directory", argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XD"})); // "Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XD"); } } // Specify the jar file name which the translet classes are packaged into. else if ("-XJ".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') { tfactory.setAttribute("generate-translet", "true"); tfactory.setAttribute("jar-name", argv[++i]); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XJ"})); // "Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XJ"); } } // Specify the package name prefix for the generated translet classes. else if ("-XP".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') tfactory.setAttribute("package-name", argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XP"})); // "Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XP"); } } // Enable template inlining. else if ("-XN".equalsIgnoreCase(argv[i])) { if (useXSLTC) { tfactory.setAttribute("enable-inlining", "true"); } else printInvalidXalanOption("-XN"); } // Turns on additional debugging message output else if ("-XX".equalsIgnoreCase(argv[i])) { if (useXSLTC) { tfactory.setAttribute("debug", "true"); } else printInvalidXalanOption("-XX"); } // Create the Transformer from the translet if the translet class is newer // than the stylesheet. else if ("-XT".equalsIgnoreCase(argv[i])) { if (useXSLTC) { tfactory.setAttribute("auto-translet", "true"); } else printInvalidXalanOption("-XT"); } else if ("-SECURE".equalsIgnoreCase(argv[i])) { isSecureProcessing = true; try { tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (TransformerConfigurationException e) { } } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_INVALID_OPTION, new Object[] {argv[i]})); // "Invalid argument:); } // Print usage instructions if no xml and xsl file is specified in the command line if (inFileName == null && xslFileName == null) { msg = resbundle.getString("xslProc_no_input"); System.err.println(msg); doExit(msg); } // Note that there are usage cases for calling us without a -IN arg // The main XSL transformation occurs here! try { long start = System.currentTimeMillis(); if (null != dumpFileName) { dumpWriter = new PrintWriter(new FileWriter(dumpFileName)); } Templates stylesheet = null; if (null != xslFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); if (isSecureProcessing) { try { dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException pce) { } } DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); Node xslDOM = docBuilder.parse(new InputSource(xslFileName)); stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName)); } else { // System.out.println("Calling newTemplates: "+xslFileName); stylesheet = tfactory.newTemplates(new StreamSource(xslFileName)); // System.out.println("Done calling newTemplates: "+xslFileName); } } PrintWriter resultWriter; StreamResult strResult; if (null != outFileName) { strResult = new StreamResult(new FileOutputStream(outFileName)); // One possible improvement might be to ensure this is // a valid URI before setting the systemId, but that // might have subtle changes that pre-existing users // might notice; we can think about that later -sc r1.46 strResult.setSystemId(outFileName); } else { strResult = new StreamResult(System.out); // We used to default to incremental mode in this case. // We've since decided that since the -INCREMENTAL switch is // available, that default is probably not necessary nor // necessarily a good idea. } SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; // J2SE does not support Xalan interpretive /* // This is currently controlled via TransformerFactoryImpl. if (!useXSLTC && useSourceLocation) stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); */ // Did they pass in a stylesheet, or should we get it from the // document? if (null == stylesheet) { Source source = stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null); if (null != source) stylesheet = tfactory.newTemplates(source); else { if (null != media) throw new TransformerException( XSLMessages.createMessage( XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[] {inFileName, media})); // "No stylesheet found in: " // + inFileName + ", media=" // + media); else throw new TransformerException( XSLMessages.createMessage( XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[] {inFileName})); // "No xml-stylesheet PI found in: " // + inFileName); } } if (null != stylesheet) { Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer(); transformer.setErrorListener(new DefaultErrorHandler()); // Override the output format? if (null != outputType) { transformer.setOutputProperty(OutputKeys.METHOD, outputType); } // J2SE does not support Xalan interpretive /* if (transformer instanceof com.sun.org.apache.xalan.internal.transformer.TransformerImpl) { com.sun.org.apache.xalan.internal.transformer.TransformerImpl impl = (com.sun.org.apache.xalan.internal.transformer.TransformerImpl)transformer; TraceManager tm = impl.getTraceManager(); if (null != tracer) tm.addTraceListener(tracer); impl.setQuietConflictWarnings(quietConflictWarnings); // This is currently controlled via TransformerFactoryImpl. if (useSourceLocation) impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); if(recursionLimit>0) impl.setRecursionLimit(recursionLimit); // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter ); } */ int nParams = params.size(); for (int i = 0; i < nParams; i += 2) { transformer.setParameter( (String) params.elementAt(i), (String) params.elementAt(i + 1)); } if (uriResolver != null) transformer.setURIResolver(uriResolver); if (null != inFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setCoalescing(true); dfactory.setNamespaceAware(true); if (isSecureProcessing) { try { dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException pce) { } } DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); if (entityResolver != null) docBuilder.setEntityResolver(entityResolver); Node xmlDoc = docBuilder.parse(new InputSource(inFileName)); Document doc = docBuilder.newDocument(); org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment(); transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode)); // Now serialize output to disk with identity transformer Transformer serializer = stf.newTransformer(); serializer.setErrorListener(new DefaultErrorHandler()); Properties serializationProps = stylesheet.getOutputProperties(); serializer.setOutputProperties(serializationProps); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); serializer.transform(new DOMSource(outNode), result); } else serializer.transform(new DOMSource(outNode), strResult); } else if (flavor.equals("th")) { for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior { // System.out.println("Testing the TransformerHandler..."); XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); if (isSecureProcessing) { try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (org.xml.sax.SAXException se) { } } javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } catch (AbstractMethodError ame) { } if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } // J2SE does not support Xalan interpretive /* if (!useXSLTC) stf.setAttribute(com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL, Boolean.TRUE); */ TransformerHandler th = stf.newTransformerHandler(stylesheet); reader.setContentHandler(th); reader.setDTDHandler(th); if (th instanceof org.xml.sax.ErrorHandler) reader.setErrorHandler((org.xml.sax.ErrorHandler) th); try { reader.setProperty("http://xml.org/sax/properties/lexical-handler", th); } catch (org.xml.sax.SAXNotRecognizedException e) { } catch (org.xml.sax.SAXNotSupportedException e) { } try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (org.xml.sax.SAXException se) { } th.setResult(strResult); reader.parse(new InputSource(inFileName)); } } else { if (entityResolver != null) { XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); if (isSecureProcessing) { try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (org.xml.sax.SAXException se) { } } javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } catch (AbstractMethodError ame) { } if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } reader.setEntityResolver(entityResolver); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new SAXSource(reader, new InputSource(inFileName)), result); } else { transformer.transform( new SAXSource(reader, new InputSource(inFileName)), strResult); } } else if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new StreamSource(inFileName), result); } else { // System.out.println("Starting transform"); transformer.transform(new StreamSource(inFileName), strResult); // System.out.println("Done with transform"); } } } else { StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>"); transformer.transform(new StreamSource(reader), strResult); } } else { // "XSL Process was not successful."); msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null); diagnosticsWriter.println(msg); doExit(msg); } // close output streams if (null != outFileName && strResult != null) { java.io.OutputStream out = strResult.getOutputStream(); java.io.Writer writer = strResult.getWriter(); try { if (out != null) out.close(); if (writer != null) writer.close(); } catch (java.io.IOException ie) { } } long stop = System.currentTimeMillis(); long millisecondsDuration = stop - start; if (doDiag) { Object[] msgArgs = new Object[] {inFileName, xslFileName, new Long(millisecondsDuration)}; msg = XSLMessages.createMessage("diagTiming", msgArgs); diagnosticsWriter.println('\n'); diagnosticsWriter.println(msg); } } catch (Throwable throwable) { while (throwable instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) { throwable = ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) throwable) .getException(); } if ((throwable instanceof NullPointerException) || (throwable instanceof ClassCastException)) doStackDumpOnError = true; diagnosticsWriter.println(); if (doStackDumpOnError) throwable.printStackTrace(dumpWriter); else { DefaultErrorHandler.printLocation(diagnosticsWriter, throwable); diagnosticsWriter.println( XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null) + " (" + throwable.getClass().getName() + "): " + throwable.getMessage()); } // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, // null)); //"XSL Process was not successful."); if (null != dumpFileName) { dumpWriter.close(); } doExit(throwable.getMessage()); } if (null != dumpFileName) { dumpWriter.close(); } if (null != diagnosticsWriter) { // diagnosticsWriter.close(); } // if(!setQuietMode) // diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done"); // else // diagnosticsWriter.println(""); //"Xalan: done"); } }