aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/healthmarketscience/jackcess/impl/CompoundOleUtil.java
blob: 98584266b1d7c3156fad2f58d6e267013531c0ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
Copyright (c) 2013 James Ahlborn

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.healthmarketscience.jackcess.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.healthmarketscience.jackcess.RuntimeIOException;
import static com.healthmarketscience.jackcess.impl.OleUtil.*;
import com.healthmarketscience.jackcess.util.MemFileChannel;
import static com.healthmarketscience.jackcess.util.OleBlob.*;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * Utility code for working with OLE data which is in the compound storage
 * format.  This functionality relies on the optional POI library.
 * <br>
 * Note that all POI usage is restricted to this file so that the basic ole
 * support in OleUtil can be utilized without requiring POI.
 *
 * @author James Ahlborn
 * @usage _advanced_class_
 */
public class CompoundOleUtil implements CompoundPackageFactory
{
  private static final String ENTRY_NAME_CHARSET = "UTF-8";
  private static final String ENTRY_SEPARATOR = "/";
  private static final String CONTENTS_ENTRY = "CONTENTS";

  static {
    // force a poi class to be loaded to ensure that when this class is
    // loaded, we know that the poi classes are available
    POIFSFileSystem.class.getName();
  }

  public CompoundOleUtil()
  {
  }

  /**
   * Creates a nes CompoundContent for the given blob information.
   */
  public ContentImpl createCompoundPackageContent(
      OleBlobImpl blob, String prettyName, String className, String typeName,
      ByteBuffer blobBb, int dataBlockLen)
  {
    return new CompoundContentImpl(blob, prettyName, className, typeName,
                                   blobBb.position(), dataBlockLen);
  }

  /**
   * Gets a DocumentEntry from compound storage based on a fully qualified,
   * encoded entry name.
   *
   * @param entryName fully qualified, encoded entry name
   * @param dir root directory of the compound storage
   *
   * @return the relevant DocumentEntry
   * @throws FileNotFoundException if the entry does not exist
   * @throws IOException if some other io error occurs
   */
  public static DocumentEntry getDocumentEntry(String entryName,
                                               DirectoryEntry dir)
    throws IOException
  {
    // split entry name into individual components and decode them
    List<String> entryNames = new ArrayList<String>();
    for(String str : entryName.split(ENTRY_SEPARATOR)) {
      if(str.length() == 0) {
        continue;
      }
      entryNames.add(decodeEntryName(str));
    }

    DocumentEntry entry = null;
    Iterator<String> iter = entryNames.iterator();
    while(iter.hasNext()) {
      org.apache.poi.poifs.filesystem.Entry tmpEntry = dir.getEntry(iter.next());
      if(tmpEntry instanceof DirectoryEntry) {
        dir = (DirectoryEntry)tmpEntry;
      } else if(!iter.hasNext() && (tmpEntry instanceof DocumentEntry)) {
        entry = (DocumentEntry)tmpEntry;
      } else {
        break;
      }
    }

    if(entry == null) {
      throw new FileNotFoundException("Could not find document " + entryName);
    }

    return entry;
  }

  private static String encodeEntryName(String name) {
    try {
      return URLEncoder.encode(name, ENTRY_NAME_CHARSET);
    } catch(UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  private static String decodeEntryName(String name) {
    try {
      return URLDecoder.decode(name, ENTRY_NAME_CHARSET);
    } catch(UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  private static final class CompoundContentImpl
    extends EmbeddedPackageContentImpl
    implements CompoundContent
  {
    private POIFSFileSystem _fs;

    private CompoundContentImpl(
        OleBlobImpl blob, String prettyName, String className,
        String typeName, int position, int length)
    {
      super(blob, prettyName, className, typeName, position, length);
    }

    public ContentType getType() {
      return ContentType.COMPOUND_STORAGE;
    }

    private POIFSFileSystem getFileSystem() throws IOException {
      if(_fs == null) {
        _fs = new POIFSFileSystem(MemFileChannel.newChannel(getStream(), "r"));
      }
      return _fs;
    }

    public Iterator<Entry> iterator() {
      try {
      return getEntries(new ArrayList<Entry>(), getFileSystem().getRoot(),
                        ENTRY_SEPARATOR).iterator();
      } catch(IOException e) {
        throw new RuntimeIOException(e);
      }
    }

    public EntryImpl getEntry(String entryName) throws IOException {
      return new EntryImpl(entryName,
                           getDocumentEntry(entryName, getFileSystem().getRoot()));
    }

    public boolean hasContentsEntry() throws IOException {
      return getFileSystem().getRoot().hasEntry(CONTENTS_ENTRY);
    }

    public EntryImpl getContentsEntry() throws IOException {
      return getEntry(CONTENTS_ENTRY);
    }

    private List<Entry> getEntries(List<Entry> entries, DirectoryEntry dir,
                                   String prefix) {
      for(org.apache.poi.poifs.filesystem.Entry entry : dir) {
        if (entry instanceof DirectoryEntry) {
          // .. recurse into this directory
          getEntries(entries, (DirectoryEntry)entry, prefix + ENTRY_SEPARATOR);
        } else if(entry instanceof DocumentEntry) {
          // grab the entry name/detils
          DocumentEntry de = (DocumentEntry)entry;
          String entryName = prefix + encodeEntryName(entry.getName());
          entries.add(new EntryImpl(entryName, de));
        }
      }
      return entries;
    }

    @Override
    public void close() {
      ByteUtil.closeQuietly(_fs);
      _fs = null;
      super.close();
    }

    @Override
    public String toString() {
      ToStringBuilder sb = toString(CustomToStringStyle.builder(this));

      try {
        sb.append("hasContentsEntry", hasContentsEntry());
        sb.append("entries", getEntries(new ArrayList<Entry>(),
                                        getFileSystem().getRoot(),
                                        ENTRY_SEPARATOR));
      } catch(IOException e) {
        sb.append("entries", "<" + e + ">");
      }

      return sb.toString();
    }

    private final class EntryImpl implements CompoundContent.Entry
    {
      private final String _name;
      private final DocumentEntry _docEntry;

      private EntryImpl(String name, DocumentEntry docEntry) {
        _name = name;
        _docEntry = docEntry;
      }

      public ContentType getType() {
        return ContentType.UNKNOWN;
      }

      public String getName() {
        return _name;
      }

      public CompoundContentImpl getParent() {
        return CompoundContentImpl.this;
      }

      public OleBlobImpl getBlob() {
        return getParent().getBlob();
      }

      public long length() {
        return _docEntry.getSize();
      }

      public InputStream getStream() throws IOException {
        return new DocumentInputStream(_docEntry);
      }

      public void writeTo(OutputStream out) throws IOException {
        InputStream in = null;
        try {
          ByteUtil.copy(in = getStream(), out);
        } finally {
          ByteUtil.closeQuietly(in);
        }
      }

      @Override
      public String toString() {
        return CustomToStringStyle.valueBuilder(this)
          .append("name", _name)
          .append("length", length())
          .toString();
      }
    }
  }

}