Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

XSSFExportToXml.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.extractor;
  16. import java.io.IOException;
  17. import java.io.OutputStream;
  18. import java.text.DateFormat;
  19. import java.text.SimpleDateFormat;
  20. import java.util.Comparator;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Locale;
  24. import java.util.Map;
  25. import java.util.Vector;
  26. import javax.xml.XMLConstants;
  27. import javax.xml.transform.OutputKeys;
  28. import javax.xml.transform.Source;
  29. import javax.xml.transform.Transformer;
  30. import javax.xml.transform.TransformerException;
  31. import javax.xml.transform.TransformerFactory;
  32. import javax.xml.transform.dom.DOMSource;
  33. import javax.xml.transform.stream.StreamResult;
  34. import javax.xml.validation.Schema;
  35. import javax.xml.validation.SchemaFactory;
  36. import javax.xml.validation.Validator;
  37. import org.apache.poi.ss.usermodel.CellType;
  38. import org.apache.poi.ss.usermodel.DateUtil;
  39. import org.apache.poi.ooxml.util.DocumentHelper;
  40. import org.apache.poi.util.LocaleUtil;
  41. import org.apache.poi.util.POILogFactory;
  42. import org.apache.poi.util.POILogger;
  43. import org.apache.poi.xssf.usermodel.XSSFCell;
  44. import org.apache.poi.xssf.usermodel.XSSFMap;
  45. import org.apache.poi.xssf.usermodel.XSSFRow;
  46. import org.apache.poi.xssf.usermodel.XSSFSheet;
  47. import org.apache.poi.xssf.usermodel.XSSFTable;
  48. import org.apache.poi.xssf.usermodel.XSSFTableColumn;
  49. import org.apache.poi.xssf.usermodel.helpers.XSSFSingleXmlCell;
  50. import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr;
  51. import org.w3c.dom.Document;
  52. import org.w3c.dom.Element;
  53. import org.w3c.dom.NamedNodeMap;
  54. import org.w3c.dom.Node;
  55. import org.w3c.dom.NodeList;
  56. import org.xml.sax.SAXException;
  57. /**
  58. *
  59. * Maps an XLSX to an XML according to one of the mapping defined.
  60. *
  61. *
  62. * The output XML Schema must respect this limitations:
  63. *
  64. * <ul>
  65. * <li> all mandatory elements and attributes must be mapped (enable validation to check this)</li>
  66. *
  67. * <li> no &lt;any&gt; in complex type/element declaration </li>
  68. * <li> no &lt;anyAttribute&gt; attributes declaration </li>
  69. * <li> no recursive structures: recursive structures can't be nested more than one level </li>
  70. * <li> no abstract elements: abstract complex types can be declared but must not be used in elements. </li>
  71. * <li> no mixed content: an element can't contain simple text and child element(s) together </li>
  72. * <li> no &lt;substitutionGroup&gt; in complex type/element declaration </li>
  73. * </ul>
  74. */
  75. public class XSSFExportToXml implements Comparator<String>{
  76. private static final POILogger LOG = POILogFactory.getLogger(XSSFExportToXml.class);
  77. private XSSFMap map;
  78. private final HashMap<String, Integer> indexMap = new HashMap<>();
  79. /**
  80. * Creates a new exporter and sets the mapping to be used when generating the XML output document
  81. *
  82. * @param map the mapping rule to be used
  83. */
  84. public XSSFExportToXml(XSSFMap map) {
  85. this.map = map;
  86. }
  87. /**
  88. *
  89. * Exports the data in an XML stream
  90. *
  91. * @param os OutputStream in which will contain the output XML
  92. * @param validate if true, validates the XML against the XML Schema
  93. * @throws SAXException If validating the document fails
  94. * @throws TransformerException If transforming the document fails
  95. */
  96. public void exportToXML(OutputStream os, boolean validate) throws SAXException, TransformerException {
  97. exportToXML(os, "UTF-8", validate);
  98. }
  99. /**
  100. * Exports the data in an XML stream
  101. *
  102. * @param os OutputStream in which will contain the output XML
  103. * @param encoding the output charset encoding
  104. * @param validate if true, validates the XML against the XML Schema
  105. * @throws SAXException If validating the document fails
  106. * @throws TransformerException If transforming the document fails
  107. */
  108. public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException, TransformerException{
  109. List<XSSFSingleXmlCell> singleXMLCells = map.getRelatedSingleXMLCell();
  110. List<XSSFTable> tables = map.getRelatedTables();
  111. String rootElement = map.getCtMap().getRootElement();
  112. Document doc = DocumentHelper.createDocument();
  113. final Element root;
  114. if (isNamespaceDeclared()) {
  115. root = doc.createElementNS(getNamespace(),rootElement);
  116. } else {
  117. root = doc.createElementNS("", rootElement);
  118. }
  119. doc.appendChild(root);
  120. List<String> xpaths = new Vector<>();
  121. Map<String,XSSFSingleXmlCell> singleXmlCellsMappings = new HashMap<>();
  122. Map<String,XSSFTable> tableMappings = new HashMap<>();
  123. for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) {
  124. xpaths.add(simpleXmlCell.getXpath());
  125. singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell);
  126. }
  127. for(XSSFTable table : tables) {
  128. String commonXPath = table.getCommonXpath();
  129. xpaths.add(commonXPath);
  130. tableMappings.put(commonXPath, table);
  131. }
  132. indexMap.clear();
  133. xpaths.sort(this);
  134. indexMap.clear();
  135. for(String xpath : xpaths) {
  136. XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath);
  137. XSSFTable table = tableMappings.get(xpath);
  138. if (!xpath.matches(".*\\[.*")) {
  139. // Exports elements and attributes mapped with simpleXmlCell
  140. if (simpleXmlCell!=null) {
  141. XSSFCell cell = simpleXmlCell.getReferencedCell();
  142. if (cell!=null) {
  143. Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false);
  144. mapCellOnNode(cell,currentNode);
  145. //remove nodes which are empty in order to keep the output xml valid
  146. // FIXME: what should be done if currentNode.getTextContent() is null?
  147. if ("".equals(currentNode.getTextContent()) && currentNode.getParentNode() != null) {
  148. currentNode.getParentNode().removeChild(currentNode);
  149. }
  150. }
  151. }
  152. // Exports elements and attributes mapped with tables
  153. if (table!=null) {
  154. List<XSSFTableColumn> tableColumns = table.getColumns();
  155. XSSFSheet sheet = table.getXSSFSheet();
  156. int startRow = table.getStartCellReference().getRow() + table.getHeaderRowCount();
  157. int endRow = table.getEndCellReference().getRow();
  158. for(int i = startRow; i<= endRow; i++) {
  159. XSSFRow row = sheet.getRow(i);
  160. Node tableRootNode = getNodeByXPath(table.getCommonXpath(), doc.getFirstChild(), doc, true);
  161. short startColumnIndex = table.getStartCellReference().getCol();
  162. for (XSSFTableColumn tableColumn : tableColumns) {
  163. XSSFCell cell = row.getCell(startColumnIndex + tableColumn.getColumnIndex());
  164. if (cell != null) {
  165. XSSFXmlColumnPr xmlColumnPr = tableColumn.getXmlColumnPr();
  166. if (xmlColumnPr != null) {
  167. String localXPath = xmlColumnPr.getLocalXPath();
  168. Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false);
  169. mapCellOnNode(cell, currentNode);
  170. }
  171. }
  172. }
  173. }
  174. }
  175. } /*else {
  176. // TODO: implement filtering management in xpath
  177. }*/
  178. }
  179. boolean isValid = true;
  180. if (validate) {
  181. isValid =isValid(doc);
  182. }
  183. if (isValid) {
  184. /////////////////
  185. //Output the XML
  186. //set up a transformer
  187. TransformerFactory transfac = TransformerFactory.newInstance();
  188. Transformer trans = transfac.newTransformer();
  189. trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  190. trans.setOutputProperty(OutputKeys.INDENT, "yes");
  191. trans.setOutputProperty(OutputKeys.ENCODING, encoding);
  192. //create string from xml tree
  193. StreamResult result = new StreamResult(os);
  194. DOMSource source = new DOMSource(doc);
  195. trans.transform(source, result);
  196. }
  197. }
  198. /**
  199. * Validate the generated XML against the XML Schema associated with the XSSFMap
  200. *
  201. * @param xml the XML to validate
  202. * @return true, if document is valid
  203. * @throws SAXException If validating the document fails
  204. */
  205. private boolean isValid(Document xml) throws SAXException{
  206. try {
  207. String language = "http://www.w3.org/2001/XMLSchema";
  208. SchemaFactory factory = SchemaFactory.newInstance(language);
  209. trySetFeature(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
  210. Source source = new DOMSource(map.getSchema());
  211. Schema schema = factory.newSchema(source);
  212. Validator validator = schema.newValidator();
  213. validator.validate(new DOMSource(xml));
  214. //if no exceptions where raised, the document is valid
  215. return true;
  216. } catch(IOException e) {
  217. LOG.log(POILogger.ERROR, "document is not valid", e);
  218. }
  219. return false;
  220. }
  221. private void mapCellOnNode(XSSFCell cell, Node node) {
  222. String value ="";
  223. switch (cell.getCellType()) {
  224. case STRING: value = cell.getStringCellValue(); break;
  225. case BOOLEAN: value += cell.getBooleanCellValue(); break;
  226. case ERROR: value = cell.getErrorCellString(); break;
  227. case FORMULA:
  228. if (cell.getCachedFormulaResultType() == CellType.STRING) {
  229. value = cell.getStringCellValue();
  230. } else {
  231. if (DateUtil.isCellDateFormatted(cell)) {
  232. value = getFormattedDate(cell);
  233. } else {
  234. value += cell.getNumericCellValue();
  235. }
  236. }
  237. break;
  238. case NUMERIC:
  239. if (DateUtil.isCellDateFormatted(cell)) {
  240. value = getFormattedDate(cell);
  241. } else {
  242. value += cell.getRawValue();
  243. }
  244. break;
  245. default:
  246. }
  247. if (node instanceof Element) {
  248. Element currentElement = (Element) node;
  249. currentElement.setTextContent(value);
  250. } else {
  251. node.setNodeValue(value);
  252. }
  253. }
  254. private String removeNamespace(String elementName) {
  255. return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName;
  256. }
  257. private String getFormattedDate(XSSFCell cell) {
  258. DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
  259. sdf.setTimeZone(LocaleUtil.getUserTimeZone());
  260. return sdf.format(cell.getDateCellValue());
  261. }
  262. private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) {
  263. String[] xpathTokens = xpath.split("/");
  264. Node currentNode = rootNode;
  265. // The first token is empty, the second is the root node
  266. for(int i =2; i<xpathTokens.length;i++) {
  267. String axisName = removeNamespace(xpathTokens[i]);
  268. if (!axisName.startsWith("@")) {
  269. NodeList list =currentNode.getChildNodes();
  270. Node selectedNode = null;
  271. if (!(createMultipleInstances && i==xpathTokens.length-1) ) {
  272. // select the last child node only if we need to map to a single cell
  273. selectedNode = selectNode(axisName, list);
  274. }
  275. if (selectedNode==null) {
  276. selectedNode = createElement(doc, currentNode, axisName);
  277. }
  278. currentNode = selectedNode;
  279. } else {
  280. currentNode = createAttribute(doc, currentNode, axisName);
  281. }
  282. }
  283. return currentNode;
  284. }
  285. private Node createAttribute(Document doc, Node currentNode, String axisName) {
  286. String attributeName = axisName.substring(1);
  287. NamedNodeMap attributesMap = currentNode.getAttributes();
  288. Node attribute = attributesMap.getNamedItem(attributeName);
  289. if (attribute==null) {
  290. attribute = doc.createAttributeNS("", attributeName);
  291. attributesMap.setNamedItem(attribute);
  292. }
  293. return attribute;
  294. }
  295. private Node createElement(Document doc, Node currentNode, String axisName) {
  296. Node selectedNode;
  297. if (isNamespaceDeclared()) {
  298. selectedNode =doc.createElementNS(getNamespace(),axisName);
  299. } else {
  300. selectedNode = doc.createElementNS("", axisName);
  301. }
  302. currentNode.appendChild(selectedNode);
  303. return selectedNode;
  304. }
  305. private Node selectNode(String axisName, NodeList list) {
  306. Node selectedNode = null;
  307. for(int j=0;j<list.getLength();j++) {
  308. Node node = list.item(j);
  309. if (node.getNodeName().equals(axisName)) {
  310. selectedNode=node;
  311. break;
  312. }
  313. }
  314. return selectedNode;
  315. }
  316. private boolean isNamespaceDeclared() {
  317. String schemaNamespace = getNamespace();
  318. return schemaNamespace!=null && !schemaNamespace.isEmpty();
  319. }
  320. private String getNamespace() {
  321. return map.getCTSchema().getNamespace();
  322. }
  323. /**
  324. * Compares two xpaths to define an ordering according to the XML Schema
  325. *
  326. */
  327. @Override
  328. public int compare(String leftXpath, String rightXpath) {
  329. Node xmlSchema = map.getSchema();
  330. String[] leftTokens = leftXpath.split("/");
  331. String[] rightTokens = rightXpath.split("/");
  332. String samePath = "";
  333. int minLength = leftTokens.length< rightTokens.length? leftTokens.length : rightTokens.length;
  334. Node localComplexTypeRootNode = xmlSchema;
  335. for(int i =1;i <minLength; i++) {
  336. String leftElementName = leftTokens[i];
  337. String rightElementName = rightTokens[i];
  338. if (leftElementName.equals(rightElementName)) {
  339. samePath += "/" + leftElementName;
  340. localComplexTypeRootNode = getComplexTypeForElement(leftElementName, xmlSchema, localComplexTypeRootNode);
  341. } else {
  342. return indexOfElementInComplexType(samePath, leftElementName, rightElementName,localComplexTypeRootNode);
  343. }
  344. }
  345. return 0;
  346. }
  347. private int indexOfElementInComplexType(String samePath,String leftElementName,String rightElementName,Node complexType) {
  348. if(complexType == null) {
  349. return 0;
  350. }
  351. int i = 0;
  352. Node node = complexType.getFirstChild();
  353. final String leftWithoutNamespace = removeNamespace(leftElementName);
  354. int leftIndexOf = getAndStoreIndex(samePath, leftWithoutNamespace);
  355. final String rightWithoutNamespace = removeNamespace(rightElementName);
  356. int rightIndexOf = getAndStoreIndex(samePath, rightWithoutNamespace);
  357. while (node != null && (rightIndexOf==-1||leftIndexOf==-1)) {
  358. if (node instanceof Element && "element".equals(node.getLocalName())) {
  359. String elementValue = getNameOrRefElement(node).getNodeValue();
  360. if (elementValue.equals(leftWithoutNamespace)) {
  361. leftIndexOf = i;
  362. indexMap.put(samePath+"/"+leftWithoutNamespace, leftIndexOf);
  363. }
  364. if (elementValue.equals(rightWithoutNamespace)) {
  365. rightIndexOf = i;
  366. indexMap.put(samePath+"/"+rightWithoutNamespace, rightIndexOf);
  367. }
  368. }
  369. i++;
  370. node = node.getNextSibling();
  371. }
  372. if(leftIndexOf == -1 || rightIndexOf == -1) {
  373. return 0;
  374. }
  375. return Integer.compare(leftIndexOf, rightIndexOf);
  376. }
  377. private int getAndStoreIndex(String samePath,String withoutNamespace) {
  378. String withPath = samePath+"/"+withoutNamespace;
  379. return indexMap.getOrDefault(withPath, -1);
  380. }
  381. private Node getNameOrRefElement(Node node) {
  382. Node returnNode = node.getAttributes().getNamedItem("ref");
  383. if(returnNode != null) {
  384. return returnNode;
  385. }
  386. return node.getAttributes().getNamedItem("name");
  387. }
  388. private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) {
  389. String elementNameWithoutNamespace = removeNamespace(elementName);
  390. String complexTypeName = getComplexTypeNameFromChildren(localComplexTypeRootNode, elementNameWithoutNamespace);
  391. // Note: we expect that all the complex types are defined at root level
  392. Node complexTypeNode = null;
  393. // FIXME: what should be done if complexTypeName is null?
  394. if (!"".equals(complexTypeName)) {
  395. complexTypeNode = getComplexTypeNodeFromSchemaChildren(xmlSchema, null, complexTypeName);
  396. }
  397. return complexTypeNode;
  398. }
  399. private String getComplexTypeNameFromChildren(Node localComplexTypeRootNode,
  400. String elementNameWithoutNamespace) {
  401. if(localComplexTypeRootNode == null) {
  402. return "";
  403. }
  404. Node node = localComplexTypeRootNode.getFirstChild();
  405. String complexTypeName = "";
  406. while (node != null) {
  407. if ( node instanceof Element && "element".equals(node.getLocalName())) {
  408. Node nameAttribute = getNameOrRefElement(node);
  409. if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) {
  410. Node complexTypeAttribute = node.getAttributes().getNamedItem("type");
  411. if (complexTypeAttribute!=null) {
  412. complexTypeName = complexTypeAttribute.getNodeValue();
  413. break;
  414. }
  415. }
  416. }
  417. node = node.getNextSibling();
  418. }
  419. return complexTypeName;
  420. }
  421. private Node getComplexTypeNodeFromSchemaChildren(Node xmlSchema, Node complexTypeNode,
  422. String complexTypeName) {
  423. Node node = xmlSchema.getFirstChild();
  424. while (node != null) {
  425. if ( node instanceof Element) {
  426. if ("complexType".equals(node.getLocalName())) {
  427. Node nameAttribute = getNameOrRefElement(node);
  428. if (nameAttribute.getNodeValue().equals(complexTypeName)) {
  429. Node sequence = node.getFirstChild();
  430. while(sequence != null) {
  431. if ( sequence instanceof Element) {
  432. final String localName = sequence.getLocalName();
  433. if ("sequence".equals(localName) || "all".equals(localName)) {
  434. complexTypeNode = sequence;
  435. break;
  436. }
  437. }
  438. sequence = sequence.getNextSibling();
  439. }
  440. if (complexTypeNode!=null) {
  441. break;
  442. }
  443. }
  444. }
  445. }
  446. node = node.getNextSibling();
  447. }
  448. return complexTypeNode;
  449. }
  450. private static void trySetFeature(SchemaFactory sf, String feature, boolean enabled) {
  451. try {
  452. sf.setFeature(feature, enabled);
  453. } catch (Exception e) {
  454. LOG.log(POILogger.WARN, "SchemaFactory Feature unsupported", feature, e);
  455. } catch (AbstractMethodError ame) {
  456. LOG.log(POILogger.WARN, "Cannot set SchemaFactory feature because outdated XML parser in classpath", feature, ame);
  457. }
  458. }
  459. }