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.

POIXMLProperties.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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.ooxml;
  16. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.util.Date;
  21. import java.util.Optional;
  22. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  23. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  24. import org.apache.poi.openxml4j.opc.ContentTypes;
  25. import org.apache.poi.openxml4j.opc.OPCPackage;
  26. import org.apache.poi.openxml4j.opc.PackagePart;
  27. import org.apache.poi.openxml4j.opc.PackagePartName;
  28. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  29. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  30. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  31. import org.apache.poi.openxml4j.opc.StreamHelper;
  32. import org.apache.poi.openxml4j.opc.TargetMode;
  33. import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
  34. import org.apache.xmlbeans.XmlException;
  35. import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty;
  36. /**
  37. * Wrapper around the three different kinds of OOXML properties
  38. * and metadata a document can have (Core, Extended and Custom),
  39. * as well Thumbnails.
  40. */
  41. public class POIXMLProperties {
  42. private OPCPackage pkg;
  43. private CoreProperties core;
  44. private ExtendedProperties ext;
  45. private CustomProperties cust;
  46. private PackagePart extPart;
  47. private PackagePart custPart;
  48. private static final org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument NEW_EXT_INSTANCE;
  49. private static final org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument NEW_CUST_INSTANCE;
  50. static {
  51. NEW_EXT_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.newInstance();
  52. NEW_EXT_INSTANCE.addNewProperties();
  53. NEW_CUST_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.newInstance();
  54. NEW_CUST_INSTANCE.addNewProperties();
  55. }
  56. public POIXMLProperties(OPCPackage docPackage) throws IOException, OpenXML4JException, XmlException {
  57. this.pkg = docPackage;
  58. // Core properties
  59. core = new CoreProperties((PackagePropertiesPart)pkg.getPackageProperties());
  60. // Extended properties
  61. PackageRelationshipCollection extRel =
  62. pkg.getRelationshipsByType(PackageRelationshipTypes.EXTENDED_PROPERTIES);
  63. if(extRel.size() == 1) {
  64. extPart = pkg.getPart(extRel.getRelationship(0));
  65. if (extPart == null) {
  66. ext = new ExtendedProperties((org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument)NEW_EXT_INSTANCE.copy());
  67. } else {
  68. org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.parse(
  69. extPart.getInputStream(), DEFAULT_XML_OPTIONS);
  70. ext = new ExtendedProperties(props);
  71. }
  72. } else {
  73. extPart = null;
  74. ext = new ExtendedProperties((org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument)NEW_EXT_INSTANCE.copy());
  75. }
  76. // Custom properties
  77. PackageRelationshipCollection custRel =
  78. pkg.getRelationshipsByType(PackageRelationshipTypes.CUSTOM_PROPERTIES);
  79. if(custRel.size() == 1) {
  80. custPart = pkg.getPart(custRel.getRelationship(0));
  81. if (custPart == null) {
  82. cust = new CustomProperties((org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument)NEW_CUST_INSTANCE.copy());
  83. } else {
  84. org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.parse(
  85. custPart.getInputStream(), DEFAULT_XML_OPTIONS);
  86. cust = new CustomProperties(props);
  87. }
  88. } else {
  89. custPart = null;
  90. cust = new CustomProperties((org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument)NEW_CUST_INSTANCE.copy());
  91. }
  92. }
  93. /**
  94. * Returns the core document properties
  95. *
  96. * @return the core document properties
  97. */
  98. public CoreProperties getCoreProperties() {
  99. return core;
  100. }
  101. /**
  102. * Returns the extended document properties
  103. *
  104. * @return the extended document properties
  105. */
  106. public ExtendedProperties getExtendedProperties() {
  107. return ext;
  108. }
  109. /**
  110. * Returns the custom document properties
  111. *
  112. * @return the custom document properties
  113. */
  114. public CustomProperties getCustomProperties() {
  115. return cust;
  116. }
  117. /**
  118. * Returns the {@link PackagePart} for the Document
  119. * Thumbnail, or <code>null</code> if there isn't one
  120. *
  121. * @return The Document Thumbnail part or null
  122. */
  123. protected PackagePart getThumbnailPart() {
  124. PackageRelationshipCollection rels =
  125. pkg.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL);
  126. if(rels.size() == 1) {
  127. return pkg.getPart(rels.getRelationship(0));
  128. }
  129. return null;
  130. }
  131. /**
  132. * Returns the name of the Document thumbnail, eg
  133. * <code>thumbnail.jpeg</code>, or <code>null</code> if there
  134. * isn't one.
  135. *
  136. * @return The thumbnail filename, or null
  137. */
  138. public String getThumbnailFilename() {
  139. PackagePart tPart = getThumbnailPart();
  140. if (tPart == null) return null;
  141. String name = tPart.getPartName().getName();
  142. return name.substring(name.lastIndexOf('/'));
  143. }
  144. /**
  145. * Returns the Document thumbnail image data, or {@code null} if there isn't one.
  146. *
  147. * @return The thumbnail data, or null
  148. *
  149. * @throws IOException if the thumbnail can't be read
  150. */
  151. public InputStream getThumbnailImage() throws IOException {
  152. PackagePart tPart = getThumbnailPart();
  153. if (tPart == null) return null;
  154. return tPart.getInputStream();
  155. }
  156. /**
  157. * Sets the Thumbnail for the document, replacing any existing one.
  158. *
  159. * @param filename The filename for the thumbnail image, eg {@code thumbnail.jpg}
  160. * @param imageData The inputstream to read the thumbnail image from
  161. *
  162. * @throws IOException if the thumbnail can't be written
  163. */
  164. public void setThumbnail(String filename, InputStream imageData) throws IOException {
  165. PackagePart tPart = getThumbnailPart();
  166. if (tPart == null) {
  167. // New thumbnail
  168. pkg.addThumbnail(filename, imageData);
  169. } else {
  170. // Change existing
  171. String newType = ContentTypes.getContentTypeFromFileExtension(filename);
  172. if (! newType.equals(tPart.getContentType())) {
  173. throw new IllegalArgumentException("Can't set a Thumbnail of type " +
  174. newType + " when existing one is of a different type " +
  175. tPart.getContentType());
  176. }
  177. StreamHelper.copyStream(imageData, tPart.getOutputStream());
  178. }
  179. }
  180. /**
  181. * Commit changes to the underlying OPC package
  182. *
  183. * @throws IOException if the properties can't be saved
  184. * @throws POIXMLException if the properties are erroneous
  185. */
  186. public void commit() throws IOException {
  187. if(extPart == null && ext != null && ext.props != null && !NEW_EXT_INSTANCE.toString().equals(ext.props.toString())){
  188. try {
  189. PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/app.xml");
  190. pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties");
  191. extPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.extended-properties+xml");
  192. } catch (InvalidFormatException e){
  193. throw new POIXMLException(e);
  194. }
  195. }
  196. if(custPart == null && cust != null && cust.props != null && !NEW_CUST_INSTANCE.toString().equals(cust.props.toString())){
  197. try {
  198. PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/custom.xml");
  199. pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
  200. custPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.custom-properties+xml");
  201. } catch (InvalidFormatException e){
  202. throw new POIXMLException(e);
  203. }
  204. }
  205. if(extPart != null){
  206. try (OutputStream out = extPart.getOutputStream()) {
  207. if (extPart.getSize() > 0) {
  208. extPart.clear();
  209. }
  210. ext.props.save(out, DEFAULT_XML_OPTIONS);
  211. }
  212. }
  213. if(custPart != null){
  214. try (OutputStream out = custPart.getOutputStream()) {
  215. cust.props.save(out, DEFAULT_XML_OPTIONS);
  216. }
  217. }
  218. }
  219. /**
  220. * The core document properties
  221. */
  222. public static class CoreProperties {
  223. private PackagePropertiesPart part;
  224. private CoreProperties(PackagePropertiesPart part) {
  225. this.part = part;
  226. }
  227. public String getCategory() {
  228. return part.getCategoryProperty().orElse(null);
  229. }
  230. public void setCategory(String category) {
  231. part.setCategoryProperty(category);
  232. }
  233. public String getContentStatus() {
  234. return part.getContentStatusProperty().orElse(null);
  235. }
  236. public void setContentStatus(String contentStatus) {
  237. part.setContentStatusProperty(contentStatus);
  238. }
  239. public String getContentType() {
  240. return part.getContentTypeProperty().orElse(null);
  241. }
  242. public void setContentType(String contentType) {
  243. part.setContentTypeProperty(contentType);
  244. }
  245. public Date getCreated() {
  246. return part.getCreatedProperty().orElse(null);
  247. }
  248. public void setCreated(Optional<Date> date) {
  249. part.setCreatedProperty(date);
  250. }
  251. public void setCreated(String date) {
  252. part.setCreatedProperty(date);
  253. }
  254. public String getCreator() {
  255. return part.getCreatorProperty().orElse(null);
  256. }
  257. public void setCreator(String creator) {
  258. part.setCreatorProperty(creator);
  259. }
  260. public String getDescription() {
  261. return part.getDescriptionProperty().orElse(null);
  262. }
  263. public void setDescription(String description) {
  264. part.setDescriptionProperty(description);
  265. }
  266. public String getIdentifier() {
  267. return part.getIdentifierProperty().orElse(null);
  268. }
  269. public void setIdentifier(String identifier) {
  270. part.setIdentifierProperty(identifier);
  271. }
  272. public String getKeywords() {
  273. return part.getKeywordsProperty().orElse(null);
  274. }
  275. public void setKeywords(String keywords) {
  276. part.setKeywordsProperty(keywords);
  277. }
  278. public Date getLastPrinted() {
  279. return part.getLastPrintedProperty().orElse(null);
  280. }
  281. public void setLastPrinted(Optional<Date> date) {
  282. part.setLastPrintedProperty(date);
  283. }
  284. public void setLastPrinted(String date) {
  285. part.setLastPrintedProperty(date);
  286. }
  287. /** @since POI 3.15 beta 3 */
  288. public String getLastModifiedByUser() {
  289. return part.getLastModifiedByProperty().orElse(null);
  290. }
  291. /** @since POI 3.15 beta 3 */
  292. public void setLastModifiedByUser(String user) {
  293. part.setLastModifiedByProperty(user);
  294. }
  295. public Date getModified() {
  296. return part.getModifiedProperty().orElse(null);
  297. }
  298. public void setModified(Optional<Date> date) {
  299. part.setModifiedProperty(date);
  300. }
  301. public void setModified(String date) {
  302. part.setModifiedProperty(date);
  303. }
  304. public String getSubject() {
  305. return part.getSubjectProperty().orElse(null);
  306. }
  307. public void setSubjectProperty(String subject) {
  308. part.setSubjectProperty(subject);
  309. }
  310. public void setTitle(String title) {
  311. part.setTitleProperty(title);
  312. }
  313. public String getTitle() {
  314. return part.getTitleProperty().orElse(null);
  315. }
  316. public String getRevision() {
  317. return part.getRevisionProperty().orElse(null);
  318. }
  319. public void setRevision(String revision) {
  320. try {
  321. Long.valueOf(revision);
  322. part.setRevisionProperty(revision);
  323. }
  324. catch (NumberFormatException e) {}
  325. }
  326. public PackagePropertiesPart getUnderlyingProperties() {
  327. return part;
  328. }
  329. }
  330. /**
  331. * Extended document properties
  332. */
  333. public static class ExtendedProperties {
  334. private org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props;
  335. private ExtendedProperties(org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props) {
  336. this.props = props;
  337. }
  338. public org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties getUnderlyingProperties() {
  339. return props.getProperties();
  340. }
  341. public String getTemplate() {
  342. if (props.getProperties().isSetTemplate()) {
  343. return props.getProperties().getTemplate();
  344. }
  345. return null;
  346. }
  347. public String getManager() {
  348. if (props.getProperties().isSetManager()) {
  349. return props.getProperties().getManager();
  350. }
  351. return null;
  352. }
  353. public String getCompany() {
  354. if (props.getProperties().isSetCompany()) {
  355. return props.getProperties().getCompany();
  356. }
  357. return null;
  358. }
  359. public String getPresentationFormat() {
  360. if (props.getProperties().isSetPresentationFormat()) {
  361. return props.getProperties().getPresentationFormat();
  362. }
  363. return null;
  364. }
  365. public String getApplication() {
  366. if (props.getProperties().isSetApplication()) {
  367. return props.getProperties().getApplication();
  368. }
  369. return null;
  370. }
  371. public String getAppVersion() {
  372. if (props.getProperties().isSetAppVersion()) {
  373. return props.getProperties().getAppVersion();
  374. }
  375. return null;
  376. }
  377. public int getPages() {
  378. if (props.getProperties().isSetPages()) {
  379. return props.getProperties().getPages();
  380. }
  381. return -1;
  382. }
  383. public int getWords() {
  384. if (props.getProperties().isSetWords()) {
  385. return props.getProperties().getWords();
  386. }
  387. return -1;
  388. }
  389. public int getCharacters() {
  390. if (props.getProperties().isSetCharacters()) {
  391. return props.getProperties().getCharacters();
  392. }
  393. return -1;
  394. }
  395. public int getCharactersWithSpaces() {
  396. if (props.getProperties().isSetCharactersWithSpaces()) {
  397. return props.getProperties().getCharactersWithSpaces();
  398. }
  399. return -1;
  400. }
  401. public int getLines() {
  402. if (props.getProperties().isSetLines()) {
  403. return props.getProperties().getLines();
  404. }
  405. return -1;
  406. }
  407. public int getParagraphs() {
  408. if (props.getProperties().isSetParagraphs()) {
  409. return props.getProperties().getParagraphs();
  410. }
  411. return -1;
  412. }
  413. public int getSlides() {
  414. if (props.getProperties().isSetSlides()) {
  415. return props.getProperties().getSlides();
  416. }
  417. return -1;
  418. }
  419. public int getNotes() {
  420. if (props.getProperties().isSetNotes()) {
  421. return props.getProperties().getNotes();
  422. }
  423. return -1;
  424. }
  425. public int getTotalTime() {
  426. if (props.getProperties().isSetTotalTime()) {
  427. return props.getProperties().getTotalTime();
  428. }
  429. return -1;
  430. }
  431. public int getHiddenSlides() {
  432. if (props.getProperties().isSetHiddenSlides()) {
  433. return props.getProperties().getHiddenSlides();
  434. }
  435. return -1;
  436. }
  437. public int getMMClips() {
  438. if (props.getProperties().isSetMMClips()) {
  439. return props.getProperties().getMMClips();
  440. }
  441. return -1;
  442. }
  443. public String getHyperlinkBase() {
  444. if (props.getProperties().isSetHyperlinkBase()) {
  445. return props.getProperties().getHyperlinkBase();
  446. }
  447. return null;
  448. }
  449. }
  450. /**
  451. * Custom document properties
  452. */
  453. public static class CustomProperties {
  454. /**
  455. * Each custom property element contains an fmtid attribute
  456. * with the same GUID value ({D5CDD505-2E9C-101B-9397-08002B2CF9AE}).
  457. */
  458. public static final String FORMAT_ID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
  459. private org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props;
  460. private CustomProperties(org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props) {
  461. this.props = props;
  462. }
  463. public org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties getUnderlyingProperties() {
  464. return props.getProperties();
  465. }
  466. /**
  467. * Add a new property
  468. *
  469. * @param name the property name
  470. * @throws IllegalArgumentException if a property with this name already exists
  471. */
  472. private CTProperty add(String name) {
  473. if(contains(name)) {
  474. throw new IllegalArgumentException("A property with this name " +
  475. "already exists in the custom properties");
  476. }
  477. CTProperty p = props.getProperties().addNewProperty();
  478. int pid = nextPid();
  479. p.setPid(pid);
  480. p.setFmtid(FORMAT_ID);
  481. p.setName(name);
  482. return p;
  483. }
  484. /**
  485. * Add a new string property
  486. *
  487. * @param name the property name
  488. * @param value the property value
  489. *
  490. * @throws IllegalArgumentException if a property with this name already exists
  491. */
  492. public void addProperty(String name, String value){
  493. CTProperty p = add(name);
  494. p.setLpwstr(value);
  495. }
  496. /**
  497. * Add a new double property
  498. *
  499. * @param name the property name
  500. * @param value the property value
  501. *
  502. * @throws IllegalArgumentException if a property with this name already exists
  503. */
  504. public void addProperty(String name, double value){
  505. CTProperty p = add(name);
  506. p.setR8(value);
  507. }
  508. /**
  509. * Add a new integer property
  510. *
  511. * @param name the property name
  512. * @param value the property value
  513. *
  514. * @throws IllegalArgumentException if a property with this name already exists
  515. */
  516. public void addProperty(String name, int value){
  517. CTProperty p = add(name);
  518. p.setI4(value);
  519. }
  520. /**
  521. * Add a new boolean property
  522. *
  523. * @param name the property name
  524. * @param value the property value
  525. *
  526. * @throws IllegalArgumentException if a property with this name already exists
  527. */
  528. public void addProperty(String name, boolean value){
  529. CTProperty p = add(name);
  530. p.setBool(value);
  531. }
  532. /**
  533. * Generate next id that uniquely relates a custom property
  534. *
  535. * @return next property id starting with 2
  536. */
  537. protected int nextPid() {
  538. int propid = 1;
  539. for(CTProperty p : props.getProperties().getPropertyList()) {
  540. if(p.getPid() > propid) propid = p.getPid();
  541. }
  542. return propid + 1;
  543. }
  544. /**
  545. * Check if a property with this name already exists in the collection of custom properties
  546. *
  547. * @param name the name to check
  548. * @return whether a property with the given name exists in the custom properties
  549. */
  550. public boolean contains(String name) {
  551. for(CTProperty p : props.getProperties().getPropertyList()) {
  552. if(p.getName().equals(name)) return true;
  553. }
  554. return false;
  555. }
  556. /**
  557. * Retrieve the custom property with this name, or null if none exists.
  558. *
  559. * You will need to test the various isSetX methods to work out
  560. * what the type of the property is, before fetching the
  561. * appropriate value for it.
  562. *
  563. * @param name the name of the property to fetch
  564. *
  565. * @return the custom property with this name, or null if none exists
  566. */
  567. public CTProperty getProperty(String name) {
  568. for(CTProperty p : props.getProperties().getPropertyList()) {
  569. if(p.getName().equals(name)) {
  570. return p;
  571. }
  572. }
  573. return null;
  574. }
  575. }
  576. }