You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackageRelationshipCollection.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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;
  16. import java.net.URI;
  17. import java.net.URISyntaxException;
  18. import java.util.*;
  19. import org.apache.logging.log4j.LogManager;
  20. import org.apache.logging.log4j.Logger;
  21. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  22. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  23. import org.apache.poi.ooxml.util.DocumentHelper;
  24. import org.w3c.dom.Attr;
  25. import org.w3c.dom.Document;
  26. import org.w3c.dom.Element;
  27. import org.w3c.dom.NodeList;
  28. /**
  29. * Represents a collection of PackageRelationship elements that are owned by a
  30. * given PackagePart or the Package.
  31. */
  32. public final class PackageRelationshipCollection implements Iterable<PackageRelationship> {
  33. private static final Logger LOG = LogManager.getLogger(PackageRelationshipCollection.class);
  34. /**
  35. * Package relationships ordered by ID.
  36. */
  37. private final TreeMap<String, PackageRelationship> relationshipsByID = new TreeMap<>();
  38. /**
  39. * Package relationships ordered by type.
  40. */
  41. private final TreeMap<String, PackageRelationship> relationshipsByType = new TreeMap<>();
  42. /**
  43. * A lookup of internal relationships to avoid
  44. */
  45. private HashMap<String, PackageRelationship> internalRelationshipsByTargetName = new HashMap<>();
  46. /**
  47. * This relationshipPart.
  48. */
  49. private PackagePart relationshipPart;
  50. /**
  51. * Source part.
  52. */
  53. private PackagePart sourcePart;
  54. /**
  55. * This part name.
  56. */
  57. private PackagePartName partName;
  58. /**
  59. * Reference to the package.
  60. */
  61. private OPCPackage container;
  62. /**
  63. * The ID number of the next rID# to generate, or -1
  64. * if that is still to be determined.
  65. */
  66. private int nextRelationshipId = -1;
  67. /**
  68. * Constructor.
  69. */
  70. PackageRelationshipCollection() {
  71. }
  72. /**
  73. * Copy constructor.
  74. *
  75. * This collection will contain only elements from the specified collection
  76. * for which the type is compatible with the specified relationship type
  77. * filter.
  78. *
  79. * @param coll
  80. * Collection to import.
  81. * @param filter
  82. * Relationship type filter.
  83. */
  84. public PackageRelationshipCollection(PackageRelationshipCollection coll,
  85. String filter) {
  86. this();
  87. for (PackageRelationship rel : coll.relationshipsByID.values()) {
  88. if (filter == null || rel.getRelationshipType().equals(filter))
  89. addRelationship(rel);
  90. }
  91. }
  92. /**
  93. * Constructor.
  94. */
  95. public PackageRelationshipCollection(OPCPackage container)
  96. throws InvalidFormatException {
  97. this(container, null);
  98. }
  99. /**
  100. * Constructor.
  101. *
  102. * @throws InvalidFormatException
  103. * Throws if the format of the content part is invalid.
  104. *
  105. * @throws InvalidOperationException
  106. * Throws if the specified part is a relationship part.
  107. */
  108. public PackageRelationshipCollection(PackagePart part)
  109. throws InvalidFormatException {
  110. this(part._container, part);
  111. }
  112. /**
  113. * Constructor. Parse the existing package relationship part if one exists.
  114. *
  115. * @param container
  116. * The parent package.
  117. * @param part
  118. * The part that own this relationships collection. If <b>null</b>
  119. * then this part is considered as the package root.
  120. * @throws InvalidFormatException
  121. * If an error occurs during the parsing of the relatinships
  122. * part fo the specified part.
  123. */
  124. public PackageRelationshipCollection(OPCPackage container, PackagePart part)
  125. throws InvalidFormatException {
  126. if (container == null)
  127. throw new IllegalArgumentException("container needs to be specified");
  128. // Check if the specified part is not a relationship part
  129. if (part != null && part.isRelationshipPart())
  130. throw new IllegalArgumentException("part");
  131. this.container = container;
  132. this.sourcePart = part;
  133. this.partName = getRelationshipPartName(part);
  134. if ((container.getPackageAccess() != PackageAccess.WRITE)
  135. && container.containPart(this.partName)) {
  136. relationshipPart = container.getPart(this.partName);
  137. parseRelationshipsPart(relationshipPart);
  138. }
  139. }
  140. /**
  141. * Get the relationship part name of the specified part.
  142. *
  143. * @param part
  144. * The part .
  145. * @return The relationship part name of the specified part. Be careful,
  146. * only the correct name is returned, this method does not check if
  147. * the part really exist in a package !
  148. * @throws InvalidOperationException
  149. * Throws if the specified part is a relationship part.
  150. */
  151. private static PackagePartName getRelationshipPartName(PackagePart part)
  152. throws InvalidOperationException {
  153. PackagePartName partName;
  154. if (part == null) {
  155. partName = PackagingURIHelper.PACKAGE_ROOT_PART_NAME;
  156. } else {
  157. partName = part.getPartName();
  158. }
  159. return PackagingURIHelper.getRelationshipPartName(partName);
  160. }
  161. /**
  162. * Add the specified relationship to the collection.
  163. *
  164. * @param relPart
  165. * The relationship to add.
  166. */
  167. public void addRelationship(PackageRelationship relPart) {
  168. if (relPart == null || relPart.getId() == null || relPart.getId().isEmpty()) {
  169. throw new IllegalArgumentException("invalid relationship part/id: " +
  170. (relPart == null ? "<null>" : relPart.getId()) + " for relationship: " + relPart);
  171. }
  172. relationshipsByID.put(relPart.getId(), relPart);
  173. relationshipsByType.put(relPart.getRelationshipType(), relPart);
  174. }
  175. /**
  176. * Add a relationship to the collection.
  177. *
  178. * @param targetUri
  179. * Target URI.
  180. * @param targetMode
  181. * The target mode : INTERNAL or EXTERNAL
  182. * @param relationshipType
  183. * Relationship type.
  184. * @param id
  185. * Relationship ID.
  186. * @return The newly created relationship.
  187. * @see PackageAccess
  188. */
  189. public PackageRelationship addRelationship(URI targetUri,
  190. TargetMode targetMode, String relationshipType, String id) {
  191. if (id == null || id.length() == 0) {
  192. // Generate a unique ID is id parameter is null.
  193. if (nextRelationshipId == -1) {
  194. nextRelationshipId = size() + 1;
  195. }
  196. // Work up until we find a unique number (there could be gaps etc)
  197. do {
  198. id = "rId" + nextRelationshipId++;
  199. } while (relationshipsByID.get(id) != null);
  200. }
  201. PackageRelationship rel = new PackageRelationship(container,
  202. sourcePart, targetUri, targetMode, relationshipType, id);
  203. addRelationship(rel);
  204. if (targetMode == TargetMode.INTERNAL){
  205. internalRelationshipsByTargetName.put(targetUri.toASCIIString(), rel);
  206. }
  207. return rel;
  208. }
  209. /**
  210. * Remove a relationship by its ID.
  211. *
  212. * @param id
  213. * The relationship ID to remove.
  214. */
  215. public void removeRelationship(String id) {
  216. PackageRelationship rel = relationshipsByID.get(id);
  217. if (rel != null) {
  218. relationshipsByID.remove(rel.getId());
  219. relationshipsByType.values().remove(rel);
  220. internalRelationshipsByTargetName.values().remove(rel);
  221. }
  222. }
  223. /**
  224. * Retrieves a relationship by its index in the collection.
  225. *
  226. * @param index
  227. * Must be a value between [0-relationships_count-1]
  228. */
  229. public PackageRelationship getRelationship(int index) {
  230. if (index < 0 || index > relationshipsByID.values().size())
  231. throw new IllegalArgumentException("index");
  232. int i = 0;
  233. for (PackageRelationship rel : relationshipsByID.values()) {
  234. if (index == i++)
  235. return rel;
  236. }
  237. return null;
  238. }
  239. /**
  240. * Retrieves a package relationship based on its id.
  241. *
  242. * @param id
  243. * ID of the package relationship to retrieve.
  244. * @return The package relationship identified by the specified id.
  245. */
  246. public PackageRelationship getRelationshipByID(String id) {
  247. return relationshipsByID.get(id);
  248. }
  249. /**
  250. * Get the numbe rof relationships in the collection.
  251. */
  252. public int size() {
  253. return relationshipsByID.values().size();
  254. }
  255. /**
  256. * Parse the relationship part and add all relationship in this collection.
  257. *
  258. * @param relPart
  259. * The package part to parse.
  260. * @throws InvalidFormatException
  261. * Throws if the relationship part is invalid.
  262. */
  263. public void parseRelationshipsPart(PackagePart relPart)
  264. throws InvalidFormatException {
  265. try {
  266. LOG.atDebug().log("Parsing relationship: {}", relPart.getPartName());
  267. Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream());
  268. // Browse default types
  269. Element root = xmlRelationshipsDoc.getDocumentElement();
  270. // Check OPC compliance M4.1 rule
  271. boolean fCorePropertiesRelationship = false;
  272. NodeList nodeList = root.getElementsByTagNameNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME);
  273. int nodeCount = nodeList.getLength();
  274. for (int i = 0; i < nodeCount; i++) {
  275. Element element = (Element)nodeList.item(i);
  276. // Relationship ID
  277. String id = element.getAttribute(PackageRelationship.ID_ATTRIBUTE_NAME);
  278. // Relationship type
  279. String type = element.getAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME);
  280. /* Check OPC Compliance */
  281. // Check Rule M4.1
  282. if (type.equals(PackageRelationshipTypes.CORE_PROPERTIES))
  283. if (!fCorePropertiesRelationship)
  284. fCorePropertiesRelationship = true;
  285. else
  286. throw new InvalidFormatException(
  287. "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !");
  288. /* End OPC Compliance */
  289. // TargetMode (default value "Internal")
  290. Attr targetModeAttr = element.getAttributeNode(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
  291. TargetMode targetMode = TargetMode.INTERNAL;
  292. if (targetModeAttr != null) {
  293. targetMode = targetModeAttr.getValue().toLowerCase(Locale.ROOT)
  294. .equals("internal") ? TargetMode.INTERNAL
  295. : TargetMode.EXTERNAL;
  296. }
  297. // Target converted in URI
  298. URI target = PackagingURIHelper.toURI("http://invalid.uri"); // dummy url
  299. String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
  300. try {
  301. // when parsing of the given uri fails, we can either
  302. // ignore this relationship, which leads to IllegalStateException
  303. // later on, or use a dummy value and thus enable processing of the
  304. // package
  305. target = PackagingURIHelper.toURI(value);
  306. } catch (URISyntaxException e) {
  307. LOG.atError().withThrowable(e).log("Cannot convert {} in a valid relationship URI-> dummy-URI used", value);
  308. }
  309. addRelationship(target, targetMode, type, id);
  310. }
  311. } catch (Exception e) {
  312. throw new InvalidFormatException("Failed to parse relationships", e);
  313. }
  314. }
  315. /**
  316. * Retrieves all relations with the specified type.
  317. *
  318. * @param typeFilter
  319. * Relationship type filter. If <b>null</b> then all
  320. * relationships are returned.
  321. * @return All relationships of the type specified by the filter.
  322. */
  323. public PackageRelationshipCollection getRelationships(String typeFilter) {
  324. return new PackageRelationshipCollection(this, typeFilter);
  325. }
  326. /**
  327. * Get this collection's iterator.
  328. */
  329. public Iterator<PackageRelationship> iterator() {
  330. return relationshipsByID.values().iterator();
  331. }
  332. /**
  333. * Get this collection's spliterator.
  334. *
  335. * @since POI 5.2.0
  336. */
  337. @Override
  338. public Spliterator<PackageRelationship> spliterator() {
  339. return relationshipsByID.values().spliterator();
  340. }
  341. /**
  342. * Get an iterator of a collection with all relationship with the specified
  343. * type.
  344. *
  345. * @param typeFilter
  346. * Type filter.
  347. * @return An iterator to a collection containing all relationships with the
  348. * specified type contain in this collection.
  349. */
  350. public Iterator<PackageRelationship> iterator(String typeFilter) {
  351. ArrayList<PackageRelationship> retArr = new ArrayList<>();
  352. for (PackageRelationship rel : relationshipsByID.values()) {
  353. if (rel.getRelationshipType().equals(typeFilter))
  354. retArr.add(rel);
  355. }
  356. return retArr.iterator();
  357. }
  358. /**
  359. * Clear all relationships.
  360. */
  361. public void clear() {
  362. relationshipsByID.clear();
  363. relationshipsByType.clear();
  364. internalRelationshipsByTargetName.clear();
  365. }
  366. public PackageRelationship findExistingInternalRelation(PackagePart packagePart) {
  367. return internalRelationshipsByTargetName.get(packagePart.getPartName().getName());
  368. }
  369. @Override
  370. public String toString() {
  371. String str = relationshipsByID.size() + " relationship(s) = [";
  372. if ((relationshipPart != null) && (relationshipPart._partName != null)) {
  373. str += relationshipPart._partName;
  374. } else {
  375. str += "relationshipPart=null";
  376. }
  377. // Source of this relationship
  378. if ((sourcePart != null) && (sourcePart._partName != null)) {
  379. str += "," + sourcePart._partName;
  380. } else {
  381. str += ",sourcePart=null";
  382. }
  383. if (partName != null) {
  384. str += "," + partName;
  385. } else {
  386. str += ",uri=null)";
  387. }
  388. return str + "]";
  389. }
  390. }