PageRenderTime 46ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/poi-3.6/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentTypeManager.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 489 lines | 206 code | 45 blank | 238 comment | 53 complexity | 9ec261b3aa9562d50030271bae5bc669 MD5 | raw file
  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.openxml4j.opc.internal;
  16. import java.io.InputStream;
  17. import java.io.OutputStream;
  18. import java.net.URI;
  19. import java.net.URISyntaxException;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import java.util.TreeMap;
  23. import java.util.Map.Entry;
  24. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  25. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  26. import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;
  27. import org.apache.poi.openxml4j.opc.OPCPackage;
  28. import org.apache.poi.openxml4j.opc.PackagePart;
  29. import org.apache.poi.openxml4j.opc.PackagePartName;
  30. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  31. import org.dom4j.Document;
  32. import org.dom4j.DocumentException;
  33. import org.dom4j.DocumentHelper;
  34. import org.dom4j.Element;
  35. import org.dom4j.Namespace;
  36. import org.dom4j.QName;
  37. import org.dom4j.io.SAXReader;
  38. /**
  39. * Manage package content types ([Content_Types].xml part).
  40. *
  41. * @author Julien Chable
  42. */
  43. public abstract class ContentTypeManager {
  44. /**
  45. * Content type part name.
  46. */
  47. public static final String CONTENT_TYPES_PART_NAME = "[Content_Types].xml";
  48. /**
  49. * Content type namespace
  50. */
  51. public static final String TYPES_NAMESPACE_URI = "http://schemas.openxmlformats.org/package/2006/content-types";
  52. /* Xml elements in content type part */
  53. private static final String TYPES_TAG_NAME = "Types";
  54. private static final String DEFAULT_TAG_NAME = "Default";
  55. private static final String EXTENSION_ATTRIBUTE_NAME = "Extension";
  56. private static final String CONTENT_TYPE_ATTRIBUTE_NAME = "ContentType";
  57. private static final String OVERRIDE_TAG_NAME = "Override";
  58. private static final String PART_NAME_ATTRIBUTE_NAME = "PartName";
  59. /**
  60. * Reference to the package using this content type manager.
  61. */
  62. protected OPCPackage container;
  63. /**
  64. * Default content type tree. <Extension, ContentType>
  65. */
  66. private TreeMap<String, String> defaultContentType;
  67. /**
  68. * Override content type tree.
  69. */
  70. private TreeMap<PackagePartName, String> overrideContentType;
  71. /**
  72. * Constructor. Parses the content of the specified input stream.
  73. *
  74. * @param in
  75. * If different of <i>null</i> then the content types part is
  76. * retrieve and parse.
  77. * @throws InvalidFormatException
  78. * If the content types part content is not valid.
  79. */
  80. public ContentTypeManager(InputStream in, OPCPackage pkg)
  81. throws InvalidFormatException {
  82. this.container = pkg;
  83. this.defaultContentType = new TreeMap<String, String>();
  84. if (in != null) {
  85. try {
  86. parseContentTypesFile(in);
  87. } catch (InvalidFormatException e) {
  88. throw new InvalidFormatException(
  89. "Can't read content types part !");
  90. }
  91. }
  92. }
  93. /**
  94. * Build association extention-> content type (will be stored in
  95. * [Content_Types].xml) for example ContentType="image/png" Extension="png"
  96. * <p>
  97. * [M2.8]: When adding a new part to a package, the package implementer
  98. * shall ensure that a content type for that part is specified in the
  99. * Content Types stream; the package implementer shall perform the steps
  100. * described in &#167;9.1.2.3:
  101. * </p><p>
  102. * 1. Get the extension from the part name by taking the substring to the
  103. * right of the rightmost occurrence of the dot character (.) from the
  104. * rightmost segment.
  105. * </p><p>
  106. * 2. If a part name has no extension, a corresponding Override element
  107. * shall be added to the Content Types stream.
  108. * </p><p>
  109. * 3. Compare the resulting extension with the values specified for the
  110. * Extension attributes of the Default elements in the Content Types stream.
  111. * The comparison shall be case-insensitive ASCII.
  112. * </p><p>
  113. * 4. If there is a Default element with a matching Extension attribute,
  114. * then the content type of the new part shall be compared with the value of
  115. * the ContentType attribute. The comparison might be case-sensitive and
  116. * include every character regardless of the role it plays in the
  117. * content-type grammar of RFC 2616, or it might follow the grammar of RFC
  118. * 2616.
  119. * </p><p>
  120. * a. If the content types match, no further action is required.
  121. * </p><p>
  122. * b. If the content types do not match, a new Override element shall be
  123. * added to the Content Types stream. .
  124. * </p><p>
  125. * 5. If there is no Default element with a matching Extension attribute, a
  126. * new Default element or Override element shall be added to the Content
  127. * Types stream.
  128. * </p>
  129. */
  130. public void addContentType(PackagePartName partName, String contentType) {
  131. boolean defaultCTExists = false;
  132. String extension = partName.getExtension().toLowerCase();
  133. if ((extension.length() == 0)
  134. || (this.defaultContentType.containsKey(extension) && !(defaultCTExists = this.defaultContentType
  135. .containsValue(contentType))))
  136. this.addOverrideContentType(partName, contentType);
  137. else if (!defaultCTExists)
  138. this.addDefaultContentType(extension, contentType);
  139. }
  140. /**
  141. * Add an override content type for a specific part.
  142. *
  143. * @param partName
  144. * Name of the part.
  145. * @param contentType
  146. * Content type of the part.
  147. */
  148. private void addOverrideContentType(PackagePartName partName,
  149. String contentType) {
  150. if (overrideContentType == null)
  151. overrideContentType = new TreeMap<PackagePartName, String>();
  152. overrideContentType.put(partName, contentType);
  153. }
  154. /**
  155. * Add a content type associated with the specified extension.
  156. *
  157. * @param extension
  158. * The part name extension to bind to a content type.
  159. * @param contentType
  160. * The content type associated with the specified extension.
  161. */
  162. private void addDefaultContentType(String extension, String contentType) {
  163. // Remark : Originally the latest parameter was :
  164. // contentType.toLowerCase(). Change due to a request ID 1996748.
  165. defaultContentType.put(extension.toLowerCase(), contentType);
  166. }
  167. /**
  168. * <p>
  169. * Delete a content type based on the specified part name. If the specified
  170. * part name is register with an override content type, then this content
  171. * type is remove, else the content type is remove in the default content
  172. * type list if it exists and if no part is associated with it yet.
  173. * </p><p>
  174. * Check rule M2.4: The package implementer shall require that the Content
  175. * Types stream contain one of the following for every part in the package:
  176. * One matching Default element One matching Override element Both a
  177. * matching Default element and a matching Override element, in which case
  178. * the Override element takes precedence.
  179. * </p>
  180. * @param partName
  181. * The part URI associated with the override content type to
  182. * delete.
  183. * @exception InvalidOperationException
  184. * Throws if
  185. */
  186. public void removeContentType(PackagePartName partName)
  187. throws InvalidOperationException {
  188. if (partName == null)
  189. throw new IllegalArgumentException("partName");
  190. /* Override content type */
  191. if (this.overrideContentType != null
  192. && (this.overrideContentType.get(partName) != null)) {
  193. // Remove the override definition for the specified part.
  194. this.overrideContentType.remove(partName);
  195. return;
  196. }
  197. /* Default content type */
  198. String extensionToDelete = partName.getExtension();
  199. boolean deleteDefaultContentTypeFlag = true;
  200. if (this.container != null) {
  201. try {
  202. for (PackagePart part : this.container.getParts()) {
  203. if (!part.getPartName().equals(partName)
  204. && part.getPartName().getExtension()
  205. .equalsIgnoreCase(extensionToDelete)) {
  206. deleteDefaultContentTypeFlag = false;
  207. break;
  208. }
  209. }
  210. } catch (InvalidFormatException e) {
  211. throw new InvalidOperationException(e.getMessage());
  212. }
  213. }
  214. // Remove the default content type, no other part use this content type.
  215. if (deleteDefaultContentTypeFlag) {
  216. this.defaultContentType.remove(extensionToDelete);
  217. }
  218. /*
  219. * Check rule 2.4: The package implementer shall require that the
  220. * Content Types stream contain one of the following for every part in
  221. * the package: One matching Default element One matching Override
  222. * element Both a matching Default element and a matching Override
  223. * element, in which case the Override element takes precedence.
  224. */
  225. if (this.container != null) {
  226. try {
  227. for (PackagePart part : this.container.getParts()) {
  228. if (!part.getPartName().equals(partName)
  229. && this.getContentType(part.getPartName()) == null)
  230. throw new InvalidOperationException(
  231. "Rule M2.4 is not respected: Nor a default element or override element is associated with the part: "
  232. + part.getPartName().getName());
  233. }
  234. } catch (InvalidFormatException e) {
  235. throw new InvalidOperationException(e.getMessage());
  236. }
  237. }
  238. }
  239. /**
  240. * Check if the specified content type is already register.
  241. *
  242. * @param contentType
  243. * The content type to check.
  244. * @return <code>true</code> if the specified content type is already
  245. * register, then <code>false</code>.
  246. */
  247. public boolean isContentTypeRegister(String contentType) {
  248. if (contentType == null)
  249. throw new IllegalArgumentException("contentType");
  250. return (this.defaultContentType.values().contains(contentType) || (this.overrideContentType != null && this.overrideContentType
  251. .values().contains(contentType)));
  252. }
  253. /**
  254. * Get the content type for the specified part, if any.
  255. * <p>
  256. * Rule [M2.9]: To get the content type of a part, the package implementer
  257. * shall perform the steps described in &#167;9.1.2.4:
  258. * </p><p>
  259. * 1. Compare the part name with the values specified for the PartName
  260. * attribute of the Override elements. The comparison shall be
  261. * case-insensitive ASCII.
  262. * </p><p>
  263. * 2. If there is an Override element with a matching PartName attribute,
  264. * return the value of its ContentType attribute. No further action is
  265. * required.
  266. * </p><p>
  267. * 3. If there is no Override element with a matching PartName attribute,
  268. * then a. Get the extension from the part name by taking the substring to
  269. * the right of the rightmost occurrence of the dot character (.) from the
  270. * rightmost segment. b. Check the Default elements of the Content Types
  271. * stream, comparing the extension with the value of the Extension
  272. * attribute. The comparison shall be case-insensitive ASCII.
  273. * </p><p>
  274. * 4. If there is a Default element with a matching Extension attribute,
  275. * return the value of its ContentType attribute. No further action is
  276. * required.
  277. * </p><p>
  278. * 5. If neither Override nor Default elements with matching attributes are
  279. * found for the specified part name, the implementation shall not map this
  280. * part name to a part.
  281. * </p>
  282. * @param partName
  283. * The URI part to check.
  284. * @return The content type associated with the URI (in case of an override
  285. * content type) or the extension (in case of default content type),
  286. * else <code>null</code>.
  287. *
  288. * @exception OpenXML4JRuntimeException
  289. * Throws if the content type manager is not able to find the
  290. * content from an existing part.
  291. */
  292. public String getContentType(PackagePartName partName) {
  293. if (partName == null)
  294. throw new IllegalArgumentException("partName");
  295. if ((this.overrideContentType != null)
  296. && this.overrideContentType.containsKey(partName))
  297. return this.overrideContentType.get(partName);
  298. String extension = partName.getExtension().toLowerCase();
  299. if (this.defaultContentType.containsKey(extension))
  300. return this.defaultContentType.get(extension);
  301. /*
  302. * [M2.4] : The package implementer shall require that the Content Types
  303. * stream contain one of the following for every part in the package:
  304. * One matching Default element, One matching Override element, Both a
  305. * matching Default element and a matching Override element, in which
  306. * case the Override element takes precedence.
  307. */
  308. if (this.container != null && this.container.getPart(partName) != null) {
  309. throw new OpenXML4JRuntimeException(
  310. "Rule M2.4 exception : this error should NEVER happen, if so please send a mail to the developers team, thanks !");
  311. }
  312. return null;
  313. }
  314. /**
  315. * Clear all content types.
  316. */
  317. public void clearAll() {
  318. this.defaultContentType.clear();
  319. if (this.overrideContentType != null)
  320. this.overrideContentType.clear();
  321. }
  322. /**
  323. * Clear all override content types.
  324. *
  325. */
  326. public void clearOverrideContentTypes() {
  327. if (this.overrideContentType != null)
  328. this.overrideContentType.clear();
  329. }
  330. /**
  331. * Parse the content types part.
  332. *
  333. * @throws InvalidFormatException
  334. * Throws if the content type doesn't exist or the XML format is
  335. * invalid.
  336. */
  337. private void parseContentTypesFile(InputStream in)
  338. throws InvalidFormatException {
  339. try {
  340. SAXReader xmlReader = new SAXReader();
  341. Document xmlContentTypetDoc = xmlReader.read(in);
  342. // Default content types
  343. List defaultTypes = xmlContentTypetDoc.getRootElement().elements(
  344. DEFAULT_TAG_NAME);
  345. Iterator elementIteratorDefault = defaultTypes.iterator();
  346. while (elementIteratorDefault.hasNext()) {
  347. Element element = (Element) elementIteratorDefault.next();
  348. String extension = element.attribute(EXTENSION_ATTRIBUTE_NAME)
  349. .getValue();
  350. String contentType = element.attribute(
  351. CONTENT_TYPE_ATTRIBUTE_NAME).getValue();
  352. addDefaultContentType(extension, contentType);
  353. }
  354. // Overriden content types
  355. List overrideTypes = xmlContentTypetDoc.getRootElement().elements(
  356. OVERRIDE_TAG_NAME);
  357. Iterator elementIteratorOverride = overrideTypes.iterator();
  358. while (elementIteratorOverride.hasNext()) {
  359. Element element = (Element) elementIteratorOverride.next();
  360. URI uri = new URI(element.attribute(PART_NAME_ATTRIBUTE_NAME)
  361. .getValue());
  362. PackagePartName partName = PackagingURIHelper
  363. .createPartName(uri);
  364. String contentType = element.attribute(
  365. CONTENT_TYPE_ATTRIBUTE_NAME).getValue();
  366. addOverrideContentType(partName, contentType);
  367. }
  368. } catch (URISyntaxException urie) {
  369. throw new InvalidFormatException(urie.getMessage());
  370. } catch (DocumentException e) {
  371. throw new InvalidFormatException(e.getMessage());
  372. }
  373. }
  374. /**
  375. * Save the contents type part.
  376. *
  377. * @param outStream
  378. * The output stream use to save the XML content of the content
  379. * types part.
  380. * @return <b>true</b> if the operation success, else <b>false</b>.
  381. */
  382. public boolean save(OutputStream outStream) {
  383. Document xmlOutDoc = DocumentHelper.createDocument();
  384. // Building namespace
  385. Namespace dfNs = Namespace.get("", TYPES_NAMESPACE_URI);
  386. Element typesElem = xmlOutDoc
  387. .addElement(new QName(TYPES_TAG_NAME, dfNs));
  388. // Adding default types
  389. for (Entry<String, String> entry : defaultContentType.entrySet()) {
  390. appendDefaultType(typesElem, entry);
  391. }
  392. // Adding specific types if any exist
  393. if (overrideContentType != null) {
  394. for (Entry<PackagePartName, String> entry : overrideContentType
  395. .entrySet()) {
  396. appendSpecificTypes(typesElem, entry);
  397. }
  398. }
  399. xmlOutDoc.normalize();
  400. // Save content in the specified output stream
  401. return this.saveImpl(xmlOutDoc, outStream);
  402. }
  403. /**
  404. * Use to append specific type XML elements, use by the save() method.
  405. *
  406. * @param root
  407. * XML parent element use to append this override type element.
  408. * @param entry
  409. * The values to append.
  410. * @see #save(java.io.OutputStream)
  411. */
  412. private void appendSpecificTypes(Element root,
  413. Entry<PackagePartName, String> entry) {
  414. root.addElement(OVERRIDE_TAG_NAME).addAttribute(
  415. PART_NAME_ATTRIBUTE_NAME,
  416. entry.getKey().getName()).addAttribute(
  417. CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
  418. }
  419. /**
  420. * Use to append default types XML elements, use by the save() metid.
  421. *
  422. * @param root
  423. * XML parent element use to append this default type element.
  424. * @param entry
  425. * The values to append.
  426. * @see #save(java.io.OutputStream)
  427. */
  428. private void appendDefaultType(Element root, Entry<String, String> entry) {
  429. root.addElement(DEFAULT_TAG_NAME).addAttribute(
  430. EXTENSION_ATTRIBUTE_NAME, entry.getKey())
  431. .addAttribute(CONTENT_TYPE_ATTRIBUTE_NAME,
  432. entry.getValue());
  433. }
  434. /**
  435. * Specific implementation of the save method. Call by the save() method,
  436. * call before exiting.
  437. *
  438. * @param out
  439. * The output stream use to write the content type XML.
  440. */
  441. public abstract boolean saveImpl(Document content, OutputStream out);
  442. }