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.

CustomProperties.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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.hpsf;
  16. import java.io.UnsupportedEncodingException;
  17. import java.math.BigInteger;
  18. import java.nio.charset.Charset;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.Date;
  23. import java.util.HashMap;
  24. import java.util.LinkedHashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import org.apache.commons.collections4.bidimap.TreeBidiMap;
  29. import org.apache.logging.log4j.LogManager;
  30. import org.apache.logging.log4j.Logger;
  31. import org.apache.poi.hpsf.wellknown.PropertyIDMap;
  32. import org.apache.poi.util.CodePageUtil;
  33. import static org.apache.logging.log4j.util.Unbox.box;
  34. /**
  35. * Maintains the instances of {@link CustomProperty} that belong to a
  36. * {@link DocumentSummaryInformation}. The class maintains the names of the
  37. * custom properties in a dictionary. It implements the {@link Map} interface
  38. * and by this provides a simplified view on custom properties: A property's
  39. * name is the key that maps to a typed value. This implementation hides
  40. * property IDs from the developer and regards the property names as keys to
  41. * typed values.<p>
  42. *
  43. * While this class provides a simple API to custom properties, it ignores
  44. * the fact that not names, but IDs are the real keys to properties. Under the
  45. * hood this class maintains a 1:1 relationship between IDs and names. Therefore
  46. * you should not use this class to process property sets with several IDs
  47. * mapping to the same name or with properties without a name: the result will
  48. * contain only a subset of the original properties. If you really need to deal
  49. * such property sets, use HPSF's low-level access methods.<p>
  50. *
  51. * An application can call the {@link #isPure} method to check whether a
  52. * property set parsed by {@link CustomProperties} is still pure (i.e.
  53. * unmodified) or whether one or more properties have been dropped.<p>
  54. *
  55. * This class is not thread-safe; concurrent access to instances of this
  56. * class must be synchronized.<p>
  57. *
  58. * While this class is roughly HashMap&lt;Long,CustomProperty&gt;, that's the
  59. * internal representation. To external calls, it should appear as
  60. * HashMap&lt;String,Object&gt; mapping between Names and Custom Property Values.
  61. */
  62. public class CustomProperties implements Map<String,Object> {
  63. private static final Logger LOG = LogManager.getLogger(CustomProperties.class);
  64. /**
  65. * The custom properties
  66. */
  67. private final HashMap<Long,CustomProperty> props = new HashMap<>();
  68. /**
  69. * Maps property IDs to property names and vice versa.
  70. */
  71. private final TreeBidiMap<Long,String> dictionary = new TreeBidiMap<>();
  72. /**
  73. * Tells whether this object is pure or not.
  74. */
  75. private boolean isPure = true;
  76. private int codepage = -1;
  77. /**
  78. * Puts a {@link CustomProperty} into this map. It is assumed that the
  79. * {@link CustomProperty} already has a valid ID. Otherwise use
  80. * {@link #put(CustomProperty)}.
  81. *
  82. * @param name the property name
  83. * @param cp the property
  84. *
  85. * @return the previous property stored under this name
  86. */
  87. public CustomProperty put(final String name, final CustomProperty cp) {
  88. if (name == null) {
  89. /* Ignoring a property without a name. */
  90. isPure = false;
  91. return null;
  92. }
  93. if (!name.equals(cp.getName())) {
  94. throw new IllegalArgumentException("Parameter \"name\" (" + name +
  95. ") and custom property's name (" + cp.getName() +
  96. ") do not match.");
  97. }
  98. checkCodePage(name);
  99. /* Register name and ID in the dictionary. Mapping in both directions is possible. If there is already a */
  100. props.remove(dictionary.getKey(name));
  101. dictionary.put(cp.getID(), name);
  102. /* Put the custom property into this map. */
  103. return props.put(cp.getID(), cp);
  104. }
  105. /**
  106. * Adds a named property.
  107. *
  108. * @param key The property's name.
  109. * @param value The property's value.
  110. * @return the property that was stored under the specified name before, or
  111. * {@code null} if there was no such property before.
  112. */
  113. @Override
  114. public Object put(String key, Object value) {
  115. int variantType;
  116. if (value instanceof String) {
  117. variantType = Variant.VT_LPSTR;
  118. } else if (value instanceof Short) {
  119. variantType = Variant.VT_I2;
  120. } else if (value instanceof Integer) {
  121. variantType = Variant.VT_I4;
  122. } else if (value instanceof Long) {
  123. variantType = Variant.VT_I8;
  124. } else if (value instanceof Float) {
  125. variantType = Variant.VT_R4;
  126. } else if (value instanceof Double) {
  127. variantType = Variant.VT_R8;
  128. } else if (value instanceof Boolean) {
  129. variantType = Variant.VT_BOOL;
  130. } else if (value instanceof BigInteger
  131. && ((BigInteger)value).bitLength() <= 64
  132. && ((BigInteger)value).compareTo(BigInteger.ZERO) >= 0) {
  133. variantType = Variant.VT_UI8;
  134. } else if (value instanceof Date) {
  135. variantType = Variant.VT_FILETIME;
  136. } else {
  137. throw new IllegalStateException("unsupported datatype - currently String,Short,Integer,Long,Float,Double,Boolean,BigInteger(unsigned long),Date can be processed.");
  138. }
  139. final Property p = new Property(-1, variantType, value);
  140. return put(new CustomProperty(p, key));
  141. }
  142. /**
  143. * Gets a named value from the custom properties - only works for keys of type String
  144. *
  145. * @param key the name of the value to get
  146. * @return the value or {@code null} if a value with the specified
  147. * name is not found in the custom properties.
  148. */
  149. @Override
  150. public Object get(final Object key) {
  151. final Long id = dictionary.getKey(key);
  152. final CustomProperty cp = props.get(id);
  153. return cp != null ? cp.getValue() : null;
  154. }
  155. /**
  156. * Removes a custom property - only works for keys of type String
  157. * @param key The name of the custom property to remove
  158. * @return The removed property or {@code null} if the specified property was not found.
  159. */
  160. @Override
  161. public CustomProperty remove(Object key) {
  162. final Long id = dictionary.removeValue(key);
  163. return props.remove(id);
  164. }
  165. @Override
  166. public int size() {
  167. return props.size();
  168. }
  169. @Override
  170. public boolean isEmpty() {
  171. return props.isEmpty();
  172. }
  173. @Override
  174. public void clear() {
  175. props.clear();
  176. }
  177. @Override
  178. public int hashCode() {
  179. return props.hashCode();
  180. }
  181. @Override
  182. public boolean equals(Object obj) {
  183. return obj instanceof CustomProperties && props.equals(((CustomProperties) obj).props);
  184. }
  185. @Override
  186. public void putAll(Map<? extends String, ?> m) {
  187. for (Entry<? extends String, ?> me : m.entrySet()) {
  188. put(me.getKey(), me.getValue());
  189. }
  190. }
  191. /**
  192. * @return the list of properties
  193. */
  194. public List<CustomProperty> properties() {
  195. List<CustomProperty> list = new ArrayList<>(props.size());
  196. for (Long l : dictionary.keySet()) {
  197. list.add(props.get(l));
  198. }
  199. return Collections.unmodifiableList(list);
  200. }
  201. /**
  202. * @return the list of property values - use {@link #properties()} for the wrapped values
  203. */
  204. @Override
  205. public Collection<Object> values() {
  206. List<Object> list = new ArrayList<>(props.size());
  207. for (Long l : dictionary.keySet()) {
  208. list.add(props.get(l).getValue());
  209. }
  210. return Collections.unmodifiableCollection(list);
  211. }
  212. @Override
  213. public Set<Entry<String, Object>> entrySet() {
  214. Map<String,Object> set = new LinkedHashMap<>(props.size());
  215. for (Entry<Long,String> se : dictionary.entrySet()) {
  216. set.put(se.getValue(), props.get(se.getKey()).getValue());
  217. }
  218. return Collections.unmodifiableSet(set.entrySet());
  219. }
  220. /**
  221. * Returns a set of all the names of our custom properties.
  222. * Equivalent to {@link #nameSet()}
  223. *
  224. * @return a set of all the names of our custom properties
  225. */
  226. @Override
  227. @SuppressWarnings({ "rawtypes", "unchecked" })
  228. public Set keySet() {
  229. return Collections.unmodifiableSet(dictionary.values());
  230. }
  231. /**
  232. * Returns a set of all the names of our custom properties
  233. *
  234. * @return a set of all the names of our custom properties
  235. */
  236. public Set<String> nameSet() {
  237. return Collections.unmodifiableSet(dictionary.values());
  238. }
  239. /**
  240. * Returns a set of all the IDs of our custom properties
  241. *
  242. * @return a set of all the IDs of our custom properties
  243. */
  244. public Set<Long> idSet() {
  245. return Collections.unmodifiableSet(dictionary.keySet());
  246. }
  247. /**
  248. * Sets the codepage.
  249. *
  250. * @param codepage the codepage
  251. */
  252. public void setCodepage(final int codepage) {
  253. this.codepage = codepage;
  254. }
  255. /**
  256. * Gets the codepage.
  257. *
  258. * @return the codepage or -1 if the codepage is undefined.
  259. */
  260. public int getCodepage() {
  261. return codepage;
  262. }
  263. /**
  264. * <p>Gets the dictionary which contains IDs and names of the named custom
  265. * properties.
  266. *
  267. * @return the dictionary.
  268. */
  269. Map<Long,String> getDictionary() {
  270. return dictionary;
  271. }
  272. /**
  273. * Checks against both String Name and Long ID
  274. */
  275. @Override
  276. public boolean containsKey(Object key) {
  277. return ((key instanceof Long && dictionary.containsKey(key)) || dictionary.containsValue(key));
  278. }
  279. /**
  280. * Checks against both the property, and its values.
  281. */
  282. @Override
  283. public boolean containsValue(Object value) {
  284. if(value instanceof CustomProperty) {
  285. return props.containsValue(value);
  286. }
  287. for(CustomProperty cp : props.values()) {
  288. if(cp.getValue() == value) {
  289. return true;
  290. }
  291. }
  292. return false;
  293. }
  294. /**
  295. * Tells whether this {@link CustomProperties} instance is pure or one or
  296. * more properties of the underlying low-level property set has been
  297. * dropped.
  298. *
  299. * @return {@code true} if the {@link CustomProperties} is pure, else
  300. * {@code false}.
  301. */
  302. public boolean isPure() {
  303. return isPure;
  304. }
  305. /**
  306. * Sets the purity of the custom property set.
  307. *
  308. * @param isPure the purity
  309. */
  310. public void setPure(final boolean isPure) {
  311. this.isPure = isPure;
  312. }
  313. /**
  314. * Puts a {@link CustomProperty} that has not yet a valid ID into this
  315. * map. The method will allocate a suitable ID for the custom property:
  316. *
  317. * <ul>
  318. * <li>If there is already a property with the same name, take the ID
  319. * of that property.
  320. *
  321. * <li>Otherwise find the highest ID and use its value plus one.
  322. * </ul>
  323. *
  324. * @param customProperty The {@link CustomProperty} to add.
  325. * @return If there was already a property with the same name, the old property
  326. * @throws ClassCastException
  327. */
  328. private Object put(final CustomProperty customProperty) throws ClassCastException {
  329. final String name = customProperty.getName();
  330. /* Check whether a property with this name is in the map already. */
  331. final Long oldId = (name == null) ? null : dictionary.getKey(name);
  332. if (oldId != null) {
  333. customProperty.setID(oldId);
  334. } else {
  335. long lastKey = (dictionary.isEmpty()) ? 0 : dictionary.lastKey();
  336. long nextKey = Math.max(lastKey,PropertyIDMap.PID_MAX)+1;
  337. customProperty.setID(nextKey);
  338. }
  339. return this.put(name, customProperty);
  340. }
  341. private void checkCodePage(String value) {
  342. int cp = getCodepage();
  343. if (cp == -1) {
  344. cp = Property.DEFAULT_CODEPAGE;
  345. }
  346. if (cp == CodePageUtil.CP_UNICODE) {
  347. return;
  348. }
  349. String cps = "";
  350. try {
  351. cps = CodePageUtil.codepageToEncoding(cp, false);
  352. } catch (UnsupportedEncodingException e) {
  353. LOG.atError().log("Codepage '{}' can't be found.", box(cp));
  354. }
  355. if (!cps.isEmpty() && Charset.forName(cps).newEncoder().canEncode(value)) {
  356. return;
  357. }
  358. LOG.atDebug().log("Charset '{}' can't encode '{}' - switching to unicode.", cps, value);
  359. setCodepage(CodePageUtil.CP_UNICODE);
  360. }
  361. }