aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/poi/POIDocument.java
blob: 4d7e50c0fb0c292a0ce281c3a3a6733bfff5482f (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
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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 org.apache.poi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.MutablePropertySet;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;

/**
 * This holds the common functionality for all POI
 *  Document classes.
 * Currently, this relates to Document Information Properties 
 * 
 * @author Nick Burch
 */
public abstract class POIDocument {
	/** Holds metadata on our document */
	protected SummaryInformation sInf;
	/** Holds further metadata on our document */
	protected DocumentSummaryInformation dsInf;
	/** The open POIFS FileSystem that contains our document */
	protected POIFSFileSystem filesystem;
	/**	The directory that our document lives in */
	protected DirectoryNode directory;
	
	/** For our own logging use */
	protected POILogger logger = POILogFactory.getLogger(this.getClass());

    /* Have the property streams been read yet? (Only done on-demand) */
    protected boolean initialized = false;
    

    protected POIDocument(DirectoryNode dir, POIFSFileSystem fs) {
    	this.filesystem = fs;
    	this.directory = dir;
    }
    protected POIDocument(POIFSFileSystem fs) {
    	this(fs.getRoot(), fs);
    }

	/**
	 * Fetch the Document Summary Information of the document
	 */
	public DocumentSummaryInformation getDocumentSummaryInformation() {
        if(!initialized) readProperties();
        return dsInf;
    }

	/** 
	 * Fetch the Summary Information of the document
	 */
	public SummaryInformation getSummaryInformation() {
        if(!initialized) readProperties();
        return sInf;
    }

	/**
	 * Find, and create objects for, the standard
	 *  Documment Information Properties (HPSF).
	 * If a given property set is missing or corrupt,
	 *  it will remain null;
	 */
	protected void readProperties() {
		PropertySet ps;
		
		// DocumentSummaryInformation
		ps = getPropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
		if(ps != null && ps instanceof DocumentSummaryInformation) {
			dsInf = (DocumentSummaryInformation)ps;
		} else if(ps != null) {
			logger.log(POILogger.WARN, "DocumentSummaryInformation property set came back with wrong class - ", ps.getClass());
		}

		// SummaryInformation
		ps = getPropertySet(SummaryInformation.DEFAULT_STREAM_NAME);
		if(ps instanceof SummaryInformation) {
			sInf = (SummaryInformation)ps;
		} else if(ps != null) {
			logger.log(POILogger.WARN, "SummaryInformation property set came back with wrong class - ", ps.getClass());
		}

		// Mark the fact that we've now loaded up the properties
        initialized = true;
	}

	/** 
	 * For a given named property entry, either return it or null if
	 *  if it wasn't found
	 */
	protected PropertySet getPropertySet(String setName) {
		DocumentInputStream dis;
		try {
			// Find the entry, and get an input stream for it
			dis = directory.createDocumentInputStream(setName);
		} catch(IOException ie) {
			// Oh well, doesn't exist
			logger.log(POILogger.WARN, "Error getting property set with name " + setName + "\n" + ie);
			return null;
		}

		try {
			// Create the Property Set
			PropertySet set = PropertySetFactory.create(dis);
			return set;
		} catch(IOException ie) {
			// Must be corrupt or something like that
			logger.log(POILogger.WARN, "Error creating property set with name " + setName + "\n" + ie);
		} catch(org.apache.poi.hpsf.HPSFException he) {
			// Oh well, doesn't exist
			logger.log(POILogger.WARN, "Error creating property set with name " + setName + "\n" + he);
		}
		return null;
	}
	
	/**
	 * Writes out the standard Documment Information Properties (HPSF)
	 * @param outFS the POIFSFileSystem to write the properties into
	 */
	protected void writeProperties(POIFSFileSystem outFS) throws IOException {
		writeProperties(outFS, null);
	}
	/**
	 * Writes out the standard Documment Information Properties (HPSF)
	 * @param outFS the POIFSFileSystem to write the properties into
	 * @param writtenEntries a list of POIFS entries to add the property names too
	 */
	protected void writeProperties(POIFSFileSystem outFS, List writtenEntries) throws IOException {
        if(sInf != null) {
			writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME,sInf,outFS);
			if(writtenEntries != null) {
				writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME);
			}
		}
		if(dsInf != null) {
			writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME,dsInf,outFS);
			if(writtenEntries != null) {
				writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
			}
		}
	}
	
	/**
	 * Writes out a given ProperySet
	 * @param name the (POIFS Level) name of the property to write
	 * @param set the PropertySet to write out 
	 * @param outFS the POIFSFileSystem to write the property into
	 */
	protected void writePropertySet(String name, PropertySet set, POIFSFileSystem outFS) throws IOException {
		try {
			MutablePropertySet mSet = new MutablePropertySet(set);
			ByteArrayOutputStream bOut = new ByteArrayOutputStream();

			mSet.write(bOut);
			byte[] data = bOut.toByteArray();
			ByteArrayInputStream bIn = new ByteArrayInputStream(data);
			outFS.createDocument(bIn,name);

			logger.log(POILogger.INFO, "Wrote property set " + name + " of size " + data.length);
		} catch(org.apache.poi.hpsf.WritingNotSupportedException wnse) {
			System.err.println("Couldn't write property set with name " + name + " as not supported by HPSF yet");
		}
	}
	
	/**
	 * Writes the document out to the specified output stream
	 */
	public abstract void write(OutputStream out) throws IOException;

	/**
	 * Copies nodes from one POIFS to the other minus the excepts
	 * @param source is the source POIFS to copy from
	 * @param target is the target POIFS to copy to
	 * @param excepts is a list of Strings specifying what nodes NOT to copy
	 */
	protected void copyNodes(POIFSFileSystem source, POIFSFileSystem target,
	                          List excepts) throws IOException {
		//System.err.println("CopyNodes called");

		DirectoryEntry root = source.getRoot();
		DirectoryEntry newRoot = target.getRoot();

		Iterator entries = root.getEntries();

		while (entries.hasNext()) {
			Entry entry = (Entry)entries.next();
			if (!isInList(entry.getName(), excepts)) {
				copyNodeRecursively(entry,newRoot);
			}
		}
	}
		
	/**
	 * Checks to see if the String is in the list, used when copying
	 *  nodes between one POIFS and another
	 */
	private boolean isInList(String entry, List list) {
		for (int k = 0; k < list.size(); k++) {
			if (list.get(k).equals(entry)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Copies an Entry into a target POIFS directory, recursively
	 */
	private void copyNodeRecursively(Entry entry, DirectoryEntry target)
	throws IOException {
		//System.err.println("copyNodeRecursively called with "+entry.getName()+
		//                   ","+target.getName());
		DirectoryEntry newTarget = null;
		if (entry.isDirectoryEntry()) {
			newTarget = target.createDirectory(entry.getName());
			Iterator entries = ((DirectoryEntry)entry).getEntries();

			while (entries.hasNext()) {
				copyNodeRecursively((Entry)entries.next(),newTarget);
			}
		} else {
			DocumentEntry dentry = (DocumentEntry)entry;
			DocumentInputStream dstream = new DocumentInputStream(dentry);
			target.createDocument(dentry.getName(),dstream);
			dstream.close();
		}
	}
}