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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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.lang.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.NPOIFSFileSystem;
  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 OleUtil.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. NPOIFSFileSystem.class.getName();
  53. }
  54. public CompoundOleUtil()
  55. {
  56. }
  57. /**
  58. * Creates a nes CompoundContent for the given blob information.
  59. */
  60. public ContentImpl createCompoundPackageContent(
  61. OleBlobImpl blob, String prettyName, String className, String typeName,
  62. ByteBuffer blobBb, int dataBlockLen)
  63. {
  64. return new CompoundContentImpl(blob, prettyName, className, typeName,
  65. blobBb.position(), dataBlockLen);
  66. }
  67. /**
  68. * Gets a DocumentEntry from compound storage based on a fully qualified,
  69. * encoded entry name.
  70. *
  71. * @param entryName fully qualified, encoded entry name
  72. * @param dir root directory of the compound storage
  73. *
  74. * @return the relevant DocumentEntry
  75. * @throws FileNotFoundException if the entry does not exist
  76. * @throws IOException if some other io error occurs
  77. */
  78. public static DocumentEntry getDocumentEntry(String entryName,
  79. DirectoryEntry dir)
  80. throws IOException
  81. {
  82. // split entry name into individual components and decode them
  83. List<String> entryNames = new ArrayList<String>();
  84. for(String str : entryName.split(ENTRY_SEPARATOR)) {
  85. if(str.length() == 0) {
  86. continue;
  87. }
  88. entryNames.add(decodeEntryName(str));
  89. }
  90. DocumentEntry entry = null;
  91. Iterator<String> iter = entryNames.iterator();
  92. while(iter.hasNext()) {
  93. org.apache.poi.poifs.filesystem.Entry tmpEntry = dir.getEntry(iter.next());
  94. if(tmpEntry instanceof DirectoryEntry) {
  95. dir = (DirectoryEntry)tmpEntry;
  96. } else if(!iter.hasNext() && (tmpEntry instanceof DocumentEntry)) {
  97. entry = (DocumentEntry)tmpEntry;
  98. } else {
  99. break;
  100. }
  101. }
  102. if(entry == null) {
  103. throw new FileNotFoundException("Could not find document " + entryName);
  104. }
  105. return entry;
  106. }
  107. private static String encodeEntryName(String name) {
  108. try {
  109. return URLEncoder.encode(name, ENTRY_NAME_CHARSET);
  110. } catch(UnsupportedEncodingException e) {
  111. throw new RuntimeException(e);
  112. }
  113. }
  114. private static String decodeEntryName(String name) {
  115. try {
  116. return URLDecoder.decode(name, ENTRY_NAME_CHARSET);
  117. } catch(UnsupportedEncodingException e) {
  118. throw new RuntimeException(e);
  119. }
  120. }
  121. private static final class CompoundContentImpl
  122. extends EmbeddedPackageContentImpl
  123. implements CompoundContent
  124. {
  125. private NPOIFSFileSystem _fs;
  126. private CompoundContentImpl(
  127. OleBlobImpl blob, String prettyName, String className,
  128. String typeName, int position, int length)
  129. {
  130. super(blob, prettyName, className, typeName, position, length);
  131. }
  132. public ContentType getType() {
  133. return ContentType.COMPOUND_STORAGE;
  134. }
  135. private NPOIFSFileSystem getFileSystem() throws IOException {
  136. if(_fs == null) {
  137. _fs = new NPOIFSFileSystem(MemFileChannel.newChannel(getStream(), "r"));
  138. }
  139. return _fs;
  140. }
  141. public Iterator<Entry> iterator() {
  142. try {
  143. return getEntries(new ArrayList<Entry>(), getFileSystem().getRoot(),
  144. ENTRY_SEPARATOR).iterator();
  145. } catch(IOException e) {
  146. throw new RuntimeIOException(e);
  147. }
  148. }
  149. public EntryImpl getEntry(String entryName) throws IOException {
  150. return new EntryImpl(entryName,
  151. getDocumentEntry(entryName, getFileSystem().getRoot()));
  152. }
  153. public boolean hasContentsEntry() throws IOException {
  154. return getFileSystem().getRoot().hasEntry(CONTENTS_ENTRY);
  155. }
  156. public EntryImpl getContentsEntry() throws IOException {
  157. return getEntry(CONTENTS_ENTRY);
  158. }
  159. private List<Entry> getEntries(List<Entry> entries, DirectoryEntry dir,
  160. String prefix) {
  161. for(org.apache.poi.poifs.filesystem.Entry entry : dir) {
  162. if (entry instanceof DirectoryEntry) {
  163. // .. recurse into this directory
  164. getEntries(entries, (DirectoryEntry)entry, prefix + ENTRY_SEPARATOR);
  165. } else if(entry instanceof DocumentEntry) {
  166. // grab the entry name/detils
  167. DocumentEntry de = (DocumentEntry)entry;
  168. String entryName = prefix + encodeEntryName(entry.getName());
  169. entries.add(new EntryImpl(entryName, de));
  170. }
  171. }
  172. return entries;
  173. }
  174. @Override
  175. public void close() {
  176. ByteUtil.closeQuietly(_fs);
  177. _fs = null;
  178. super.close();
  179. }
  180. @Override
  181. public String toString() {
  182. ToStringBuilder sb = toString(CustomToStringStyle.builder(this));
  183. try {
  184. sb.append("hasContentsEntry", hasContentsEntry());
  185. sb.append("entries", getEntries(new ArrayList<Entry>(),
  186. getFileSystem().getRoot(),
  187. ENTRY_SEPARATOR));
  188. } catch(IOException e) {
  189. sb.append("entries", "<" + e + ">");
  190. }
  191. return sb.toString();
  192. }
  193. private final class EntryImpl implements CompoundContent.Entry
  194. {
  195. private final String _name;
  196. private final DocumentEntry _docEntry;
  197. private EntryImpl(String name, DocumentEntry docEntry) {
  198. _name = name;
  199. _docEntry = docEntry;
  200. }
  201. public ContentType getType() {
  202. return ContentType.UNKNOWN;
  203. }
  204. public String getName() {
  205. return _name;
  206. }
  207. public CompoundContentImpl getParent() {
  208. return CompoundContentImpl.this;
  209. }
  210. public OleBlobImpl getBlob() {
  211. return getParent().getBlob();
  212. }
  213. public long length() {
  214. return _docEntry.getSize();
  215. }
  216. public InputStream getStream() throws IOException {
  217. return new DocumentInputStream(_docEntry);
  218. }
  219. public void writeTo(OutputStream out) throws IOException {
  220. InputStream in = null;
  221. try {
  222. ByteUtil.copy(in = getStream(), out);
  223. } finally {
  224. ByteUtil.closeQuietly(in);
  225. }
  226. }
  227. @Override
  228. public String toString() {
  229. return CustomToStringStyle.valueBuilder(this)
  230. .append("name", _name)
  231. .append("length", length())
  232. .toString();
  233. }
  234. }
  235. }
  236. }