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

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