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.

CompoundOleUtil.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. Copyright (c) 2013 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.FileNotFoundException;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.OutputStream;
  18. import java.io.UnsupportedEncodingException;
  19. import java.net.URLDecoder;
  20. import java.net.URLEncoder;
  21. import java.nio.ByteBuffer;
  22. import java.util.ArrayList;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import com.healthmarketscience.jackcess.RuntimeIOException;
  26. import static com.healthmarketscience.jackcess.impl.OleUtil.*;
  27. import com.healthmarketscience.jackcess.util.MemFileChannel;
  28. import static com.healthmarketscience.jackcess.util.OleBlob.*;
  29. import org.apache.commons.lang3.builder.ToStringBuilder;
  30. import org.apache.poi.poifs.filesystem.DirectoryEntry;
  31. import org.apache.poi.poifs.filesystem.DocumentEntry;
  32. import org.apache.poi.poifs.filesystem.DocumentInputStream;
  33. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  34. /**
  35. * Utility code for working with OLE data which is in the compound storage
  36. * format. This functionality relies on the optional POI library.
  37. * <p>
  38. * Note that all POI usage is restricted to this file so that the basic ole
  39. * support in OleUtil can be utilized without requiring POI.
  40. *
  41. * @author James Ahlborn
  42. * @usage _advanced_class_
  43. */
  44. public class CompoundOleUtil implements CompoundPackageFactory
  45. {
  46. private static final String ENTRY_NAME_CHARSET = "UTF-8";
  47. private static final String ENTRY_SEPARATOR = "/";
  48. private static final String CONTENTS_ENTRY = "CONTENTS";
  49. static {
  50. // force a poi class to be loaded to ensure that when this class is
  51. // loaded, we know that the poi classes are available
  52. POIFSFileSystem.class.getName();
  53. }
  54. public CompoundOleUtil()
  55. {
  56. }
  57. /**
  58. * Creates a nes CompoundContent for the given blob information.
  59. */
  60. @Override
  61. public ContentImpl createCompoundPackageContent(
  62. OleBlobImpl blob, String prettyName, String className, String typeName,
  63. ByteBuffer blobBb, int dataBlockLen)
  64. {
  65. return new CompoundContentImpl(blob, prettyName, className, typeName,
  66. blobBb.position(), dataBlockLen);
  67. }
  68. /**
  69. * Gets a DocumentEntry from compound storage based on a fully qualified,
  70. * encoded entry name.
  71. *
  72. * @param entryName fully qualified, encoded entry name
  73. * @param dir root directory of the compound storage
  74. *
  75. * @return the relevant DocumentEntry
  76. * @throws FileNotFoundException if the entry does not exist
  77. * @throws IOException if some other io error occurs
  78. */
  79. public static DocumentEntry getDocumentEntry(String entryName,
  80. DirectoryEntry dir)
  81. throws IOException
  82. {
  83. // split entry name into individual components and decode them
  84. List<String> entryNames = new ArrayList<String>();
  85. for(String str : entryName.split(ENTRY_SEPARATOR)) {
  86. if(str.length() == 0) {
  87. continue;
  88. }
  89. entryNames.add(decodeEntryName(str));
  90. }
  91. DocumentEntry entry = null;
  92. Iterator<String> iter = entryNames.iterator();
  93. while(iter.hasNext()) {
  94. org.apache.poi.poifs.filesystem.Entry tmpEntry = dir.getEntry(iter.next());
  95. if(tmpEntry instanceof DirectoryEntry) {
  96. dir = (DirectoryEntry)tmpEntry;
  97. } else if(!iter.hasNext() && (tmpEntry instanceof DocumentEntry)) {
  98. entry = (DocumentEntry)tmpEntry;
  99. } else {
  100. break;
  101. }
  102. }
  103. if(entry == null) {
  104. throw new FileNotFoundException("Could not find document " + entryName);
  105. }
  106. return entry;
  107. }
  108. private static String encodeEntryName(String name) {
  109. try {
  110. return URLEncoder.encode(name, ENTRY_NAME_CHARSET);
  111. } catch(UnsupportedEncodingException e) {
  112. throw new RuntimeException(e);
  113. }
  114. }
  115. private static String decodeEntryName(String name) {
  116. try {
  117. return URLDecoder.decode(name, ENTRY_NAME_CHARSET);
  118. } catch(UnsupportedEncodingException e) {
  119. throw new RuntimeException(e);
  120. }
  121. }
  122. private static final class CompoundContentImpl
  123. extends EmbeddedPackageContentImpl
  124. implements CompoundContent
  125. {
  126. private POIFSFileSystem _fs;
  127. private CompoundContentImpl(
  128. OleBlobImpl blob, String prettyName, String className,
  129. String typeName, int position, int length)
  130. {
  131. super(blob, prettyName, className, typeName, position, length);
  132. }
  133. @Override
  134. public ContentType getType() {
  135. return ContentType.COMPOUND_STORAGE;
  136. }
  137. private POIFSFileSystem getFileSystem() throws IOException {
  138. if(_fs == null) {
  139. _fs = new POIFSFileSystem(MemFileChannel.newChannel(getStream(), "r"));
  140. }
  141. return _fs;
  142. }
  143. @Override
  144. public Iterator<Entry> iterator() {
  145. try {
  146. return getEntries(new ArrayList<Entry>(), getFileSystem().getRoot(),
  147. ENTRY_SEPARATOR).iterator();
  148. } catch(IOException e) {
  149. throw new RuntimeIOException(e);
  150. }
  151. }
  152. @Override
  153. public EntryImpl getEntry(String entryName) throws IOException {
  154. return new EntryImpl(entryName,
  155. getDocumentEntry(entryName, getFileSystem().getRoot()));
  156. }
  157. @Override
  158. public boolean hasContentsEntry() throws IOException {
  159. return getFileSystem().getRoot().hasEntry(CONTENTS_ENTRY);
  160. }
  161. @Override
  162. public EntryImpl getContentsEntry() throws IOException {
  163. return getEntry(CONTENTS_ENTRY);
  164. }
  165. private List<Entry> getEntries(List<Entry> entries, DirectoryEntry dir,
  166. String prefix) {
  167. for(org.apache.poi.poifs.filesystem.Entry entry : dir) {
  168. if (entry instanceof DirectoryEntry) {
  169. // .. recurse into this directory
  170. getEntries(entries, (DirectoryEntry)entry, prefix + ENTRY_SEPARATOR);
  171. } else if(entry instanceof DocumentEntry) {
  172. // grab the entry name/detils
  173. DocumentEntry de = (DocumentEntry)entry;
  174. String entryName = prefix + encodeEntryName(entry.getName());
  175. entries.add(new EntryImpl(entryName, de));
  176. }
  177. }
  178. return entries;
  179. }
  180. @Override
  181. public void close() {
  182. ByteUtil.closeQuietly(_fs);
  183. _fs = null;
  184. super.close();
  185. }
  186. @Override
  187. public String toString() {
  188. ToStringBuilder sb = toString(CustomToStringStyle.builder(this));
  189. try {
  190. sb.append("hasContentsEntry", hasContentsEntry());
  191. sb.append("entries", getEntries(new ArrayList<Entry>(),
  192. getFileSystem().getRoot(),
  193. ENTRY_SEPARATOR));
  194. } catch(IOException e) {
  195. sb.append("entries", "<" + e + ">");
  196. }
  197. return sb.toString();
  198. }
  199. private final class EntryImpl implements CompoundContent.Entry
  200. {
  201. private final String _name;
  202. private final DocumentEntry _docEntry;
  203. private EntryImpl(String name, DocumentEntry docEntry) {
  204. _name = name;
  205. _docEntry = docEntry;
  206. }
  207. @Override
  208. public ContentType getType() {
  209. return ContentType.UNKNOWN;
  210. }
  211. @Override
  212. public String getName() {
  213. return _name;
  214. }
  215. @Override
  216. public CompoundContentImpl getParent() {
  217. return CompoundContentImpl.this;
  218. }
  219. @Override
  220. public OleBlobImpl getBlob() {
  221. return getParent().getBlob();
  222. }
  223. @Override
  224. public long length() {
  225. return _docEntry.getSize();
  226. }
  227. @Override
  228. public InputStream getStream() throws IOException {
  229. return new DocumentInputStream(_docEntry);
  230. }
  231. @Override
  232. public void writeTo(OutputStream out) throws IOException {
  233. InputStream in = null;
  234. try {
  235. ByteUtil.copy(in = getStream(), out);
  236. } finally {
  237. ByteUtil.closeQuietly(in);
  238. }
  239. }
  240. @Override
  241. public String toString() {
  242. return CustomToStringStyle.valueBuilder(this)
  243. .append("name", _name)
  244. .append("length", length())
  245. .toString();
  246. }
  247. }
  248. }
  249. }