View | Details | Raw Unified | Return to bug 56814
Collapse All | Expand All

(-)src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/PackagePropertiesMarshaller.java (-249 / +90 lines)
Lines 19-34 Link Here
19
19
20
import java.io.OutputStream;
20
import java.io.OutputStream;
21
21
22
import org.dom4j.Document;
23
import org.dom4j.DocumentHelper;
24
import org.dom4j.Element;
25
import org.dom4j.Namespace;
26
import org.dom4j.QName;
27
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
22
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
28
import org.apache.poi.openxml4j.opc.PackagePart;
23
import org.apache.poi.openxml4j.opc.PackagePart;
29
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
24
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
30
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
25
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
26
import org.apache.poi.openxml4j.util.Nullable;
27
import org.apache.poi.util.DocumentHelper;
28
import org.apache.poi.util.XMLHelper;
29
import org.w3c.dom.Document;
30
import org.w3c.dom.Element;
31
31
32
import javax.xml.XMLConstants;
33
import javax.xml.stream.XMLEventFactory;
34
import javax.xml.stream.events.Namespace;
35
32
/**
36
/**
33
 * Package properties marshaller.
37
 * Package properties marshaller.
34
 *
38
 *
Lines 36-52 Link Here
36
 */
40
 */
37
public class PackagePropertiesMarshaller implements PartMarshaller {
41
public class PackagePropertiesMarshaller implements PartMarshaller {
38
42
39
	private final static Namespace namespaceDC = new Namespace("dc",
43
    private final static Namespace namespaceDC = XMLEventFactory.newFactory().createNamespace("dc",
40
			PackagePropertiesPart.NAMESPACE_DC_URI);
44
			PackagePropertiesPart.NAMESPACE_DC_URI);
41
45
42
	private final static Namespace namespaceCoreProperties = new Namespace("",
46
	private final static Namespace namespaceCoreProperties = XMLEventFactory.newFactory().createNamespace("",
43
			PackagePropertiesPart.NAMESPACE_CP_URI);
47
			PackagePropertiesPart.NAMESPACE_CP_URI);
44
48
45
	private final static Namespace namespaceDcTerms = new Namespace("dcterms",
49
	private final static Namespace namespaceDcTerms = XMLEventFactory.newFactory().createNamespace("dcterms",
46
			PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
50
			PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
47
51
48
	private final static Namespace namespaceXSI = new Namespace("xsi",
52
	private final static Namespace namespaceXSI = XMLEventFactory.newFactory().createNamespace("xsi",
49
			PackagePropertiesPart.NAMESPACE_XSI_URI);
53
			XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
50
54
51
	protected static final String KEYWORD_CATEGORY = "category";
55
	protected static final String KEYWORD_CATEGORY = "category";
52
56
Lines 98-110 Link Here
98
102
99
		// Configure the document
103
		// Configure the document
100
		xmlDoc = DocumentHelper.createDocument();
104
		xmlDoc = DocumentHelper.createDocument();
101
		Element rootElem = xmlDoc.addElement(new QName("coreProperties",
105
        Element rootElem = xmlDoc.createElementNS(namespaceCoreProperties.getNamespaceURI(), "coreProperties");
102
				namespaceCoreProperties));
106
        XMLHelper.addNamespaceDeclaration(rootElem, "cp", PackagePropertiesPart.NAMESPACE_CP_URI);
103
		rootElem.addNamespace("cp", PackagePropertiesPart.NAMESPACE_CP_URI);
107
        XMLHelper.addNamespaceDeclaration(rootElem, "dc", PackagePropertiesPart.NAMESPACE_DC_URI);
104
		rootElem.addNamespace("dc", PackagePropertiesPart.NAMESPACE_DC_URI);
108
        XMLHelper.addNamespaceDeclaration(rootElem, "dcterms", PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
105
		rootElem.addNamespace("dcterms",
109
        XMLHelper.addNamespaceDeclaration(rootElem, "xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
106
				PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
110
        xmlDoc.appendChild(rootElem);
107
		rootElem.addNamespace("xsi", PackagePropertiesPart.NAMESPACE_XSI_URI);
108
111
109
		addCategory();
112
		addCategory();
110
		addContentStatus();
113
		addContentStatus();
Lines 125-433 Link Here
125
		return true;
128
		return true;
126
	}
129
	}
127
130
128
	/**
131
    /**
129
	 * Add category property element if needed.
132
     * Sets the given element's text content, creating it if necessary.
130
	 */
133
     */
131
	private void addCategory() {
134
    private Element setElementTextContent(String localName, Namespace namespace, Nullable<String> property) {
132
		if (!propsPart.getCategoryProperty().hasValue())
135
        return setElementTextContent(localName, namespace, property, property.getValue());
133
			return;
136
    }
134
137
135
		Element elem = xmlDoc.getRootElement().element(
138
    private Element setElementTextContent(String localName, Namespace namespace, Nullable<?> property, String propertyValue) {
136
				new QName(KEYWORD_CATEGORY, namespaceCoreProperties));
139
        if (!property.hasValue())
140
            return null;
141
142
        Element root = xmlDoc.getDocumentElement();
143
        Element elem = (Element) root.getElementsByTagNameNS(namespace.getNamespaceURI(), localName).item(0);
137
		if (elem == null) {
144
        if (elem == null) {
138
			// Missing, we add it
145
            // missing, we add it
139
			elem = xmlDoc.getRootElement().addElement(
146
            String qualifiedName = namespace.getPrefix().isEmpty() ? localName : namespace.getPrefix() + ':' + localName;
140
					new QName(KEYWORD_CATEGORY, namespaceCoreProperties));
147
            elem = xmlDoc.createElementNS(namespace.getNamespaceURI(), qualifiedName);
141
		} else {
148
            root.appendChild(elem);
142
			elem.clearContent();// clear the old value
143
		}
149
        }
144
		elem.addText(propsPart.getCategoryProperty().getValue());
150
        elem.setTextContent(propertyValue);
151
        return elem;
145
	}
152
    }
146
153
147
	/**
154
    private Element setElementTextContent(String localName, Namespace namespace, Nullable<?> property, String propertyValue, String xsiType) {
155
        Element element = setElementTextContent(localName, namespace, property, propertyValue);
156
        if (element != null) {
157
            element.setAttributeNS(namespaceXSI.getNamespaceURI(), namespaceXSI.getPrefix() + ':' + "type", xsiType);
158
        }
159
        return element;
160
    }
161
162
163
    /**
164
	 * Add category property element if needed.
165
	 */
166
	private void addCategory() {
167
        setElementTextContent(KEYWORD_CATEGORY, namespaceCoreProperties, propsPart.getCategoryProperty());
168
	}
169
170
	/**
148
	 * Add content status property element if needed.
171
	 * Add content status property element if needed.
149
	 */
172
	 */
150
	private void addContentStatus() {
173
	private void addContentStatus() {
151
		if (!propsPart.getContentStatusProperty().hasValue())
174
        setElementTextContent(KEYWORD_CONTENT_STATUS, namespaceCoreProperties, propsPart.getContentStatusProperty());
152
			return;
153
154
		Element elem = xmlDoc.getRootElement().element(
155
				new QName(KEYWORD_CONTENT_STATUS, namespaceCoreProperties));
156
		if (elem == null) {
157
			// Missing, we add it
158
			elem = xmlDoc.getRootElement().addElement(
159
					new QName(KEYWORD_CONTENT_STATUS, namespaceCoreProperties));
160
		} else {
161
			elem.clearContent();// clear the old value
162
		}
175
	}
163
		elem.addText(propsPart.getContentStatusProperty().getValue());
164
	}
165
176
166
	/**
177
	/**
167
	 * Add content type property element if needed.
178
	 * Add content type property element if needed.
168
	 */
179
	 */
169
	private void addContentType() {
180
	private void addContentType() {
170
		if (!propsPart.getContentTypeProperty().hasValue())
181
        setElementTextContent(KEYWORD_CONTENT_TYPE, namespaceCoreProperties, propsPart.getContentTypeProperty());
171
			return;
172
173
		Element elem = xmlDoc.getRootElement().element(
174
				new QName(KEYWORD_CONTENT_TYPE, namespaceCoreProperties));
175
		if (elem == null) {
176
			// Missing, we add it
177
			elem = xmlDoc.getRootElement().addElement(
178
					new QName(KEYWORD_CONTENT_TYPE, namespaceCoreProperties));
179
		} else {
180
			elem.clearContent();// clear the old value
181
		}
182
	}
182
		elem.addText(propsPart.getContentTypeProperty().getValue());
183
	}
184
183
185
	/**
184
	/**
186
	 * Add created property element if needed.
185
	 * Add created property element if needed.
187
	 */
186
	 */
188
	private void addCreated() {
187
	private void addCreated() {
189
		if (!propsPart.getCreatedProperty().hasValue())
188
        setElementTextContent(KEYWORD_CREATED, namespaceDcTerms, propsPart.getCreatedProperty(),
190
			return;
189
                propsPart.getCreatedPropertyString(), "dcterms:W3CDTF");
191
192
		Element elem = xmlDoc.getRootElement().element(
193
				new QName(KEYWORD_CREATED, namespaceDcTerms));
194
		if (elem == null) {
195
			// missing, we add it
196
			elem = xmlDoc.getRootElement().addElement(
197
					new QName(KEYWORD_CREATED, namespaceDcTerms));
198
		} else {
199
			elem.clearContent();// clear the old value
200
		}
190
	}
201
		elem.addAttribute(new QName("type", namespaceXSI), "dcterms:W3CDTF");
202
		elem.addText(propsPart.getCreatedPropertyString());
203
	}
204
191
205
	/**
192
	/**
206
	 * Add creator property element if needed.
193
	 * Add creator property element if needed.
207
	 */
194
	 */
208
	private void addCreator() {
195
	private void addCreator() {
209
		if (!propsPart.getCreatorProperty().hasValue())
196
        setElementTextContent(KEYWORD_CREATOR, namespaceDC, propsPart.getCreatorProperty());
210
			return;
211
212
		Element elem = xmlDoc.getRootElement().element(
213
				new QName(KEYWORD_CREATOR, namespaceDC));
214
		if (elem == null) {
215
			// missing, we add it
216
			elem = xmlDoc.getRootElement().addElement(
217
					new QName(KEYWORD_CREATOR, namespaceDC));
218
		} else {
219
			elem.clearContent();// clear the old value
220
		}
197
	}
221
		elem.addText(propsPart.getCreatorProperty().getValue());
222
	}
223
198
224
	/**
199
	/**
225
	 * Add description property element if needed.
200
	 * Add description property element if needed.
226
	 */
201
	 */
227
	private void addDescription() {
202
	private void addDescription() {
228
		if (!propsPart.getDescriptionProperty().hasValue())
203
        setElementTextContent(KEYWORD_DESCRIPTION, namespaceDC, propsPart.getDescriptionProperty());
229
			return;
230
231
		Element elem = xmlDoc.getRootElement().element(
232
				new QName(KEYWORD_DESCRIPTION, namespaceDC));
233
		if (elem == null) {
234
			// missing, we add it
235
			elem = xmlDoc.getRootElement().addElement(
236
					new QName(KEYWORD_DESCRIPTION, namespaceDC));
237
		} else {
238
			elem.clearContent();// clear the old value
239
		}
204
	}
240
		elem.addText(propsPart.getDescriptionProperty().getValue());
241
	}
242
205
243
	/**
206
	/**
244
	 * Add identifier property element if needed.
207
	 * Add identifier property element if needed.
245
	 */
208
	 */
246
	private void addIdentifier() {
209
	private void addIdentifier() {
247
		if (!propsPart.getIdentifierProperty().hasValue())
210
        setElementTextContent(KEYWORD_IDENTIFIER, namespaceDC, propsPart.getIdentifierProperty());
248
			return;
249
250
		Element elem = xmlDoc.getRootElement().element(
251
				new QName(KEYWORD_IDENTIFIER, namespaceDC));
252
		if (elem == null) {
253
			// missing, we add it
254
			elem = xmlDoc.getRootElement().addElement(
255
					new QName(KEYWORD_IDENTIFIER, namespaceDC));
256
		} else {
257
			elem.clearContent();// clear the old value
258
		}
211
	}
259
		elem.addText(propsPart.getIdentifierProperty().getValue());
260
	}
261
212
262
	/**
213
    /**
263
	 * Add keywords property element if needed.
214
	 * Add keywords property element if needed.
264
	 */
215
	 */
265
	private void addKeywords() {
216
	private void addKeywords() {
266
		if (!propsPart.getKeywordsProperty().hasValue())
217
        setElementTextContent(KEYWORD_KEYWORDS, namespaceCoreProperties, propsPart.getKeywordsProperty());
267
			return;
268
269
		Element elem = xmlDoc.getRootElement().element(
270
				new QName(KEYWORD_KEYWORDS, namespaceCoreProperties));
271
		if (elem == null) {
272
			// missing, we add it
273
			elem = xmlDoc.getRootElement().addElement(
274
					new QName(KEYWORD_KEYWORDS, namespaceCoreProperties));
275
		} else {
276
			elem.clearContent();// clear the old value
277
		}
218
	}
278
		elem.addText(propsPart.getKeywordsProperty().getValue());
279
	}
280
219
281
	/**
220
	/**
282
	 * Add language property element if needed.
221
	 * Add language property element if needed.
283
	 */
222
	 */
284
	private void addLanguage() {
223
	private void addLanguage() {
285
		if (!propsPart.getLanguageProperty().hasValue())
224
        setElementTextContent(KEYWORD_LANGUAGE, namespaceDC, propsPart.getLanguageProperty());
286
			return;
287
288
		Element elem = xmlDoc.getRootElement().element(
289
				new QName(KEYWORD_LANGUAGE, namespaceDC));
290
		if (elem == null) {
291
			// missing, we add it
292
			elem = xmlDoc.getRootElement().addElement(
293
					new QName(KEYWORD_LANGUAGE, namespaceDC));
294
		} else {
295
			elem.clearContent();// clear the old value
296
		}
225
	}
297
		elem.addText(propsPart.getLanguageProperty().getValue());
298
	}
299
226
300
	/**
227
	/**
301
	 * Add 'last modified by' property if needed.
228
	 * Add 'last modified by' property if needed.
302
	 */
229
	 */
303
	private void addLastModifiedBy() {
230
	private void addLastModifiedBy() {
304
		if (!propsPart.getLastModifiedByProperty().hasValue())
231
        setElementTextContent(KEYWORD_LAST_MODIFIED_BY, namespaceCoreProperties, propsPart.getLastModifiedByProperty());
305
			return;
306
307
		Element elem = xmlDoc.getRootElement().element(
308
				new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCoreProperties));
309
		if (elem == null) {
310
			// missing, we add it
311
			elem = xmlDoc.getRootElement()
312
					.addElement(
313
							new QName(KEYWORD_LAST_MODIFIED_BY,
314
									namespaceCoreProperties));
315
		} else {
316
			elem.clearContent();// clear the old value
317
		}
232
	}
318
		elem.addText(propsPart.getLastModifiedByProperty().getValue());
319
	}
320
233
321
	/**
234
	/**
322
	 * Add 'last printed' property if needed.
235
	 * Add 'last printed' property if needed.
323
	 *
236
	 *
324
	 */
237
	 */
325
	private void addLastPrinted() {
238
	private void addLastPrinted() {
326
		if (!propsPart.getLastPrintedProperty().hasValue())
239
        setElementTextContent(KEYWORD_LAST_PRINTED, namespaceCoreProperties, propsPart.getLastPrintedProperty(), propsPart.getLastPrintedPropertyString());
327
			return;
328
329
		Element elem = xmlDoc.getRootElement().element(
330
				new QName(KEYWORD_LAST_PRINTED, namespaceCoreProperties));
331
		if (elem == null) {
332
			// missing, we add it
333
			elem = xmlDoc.getRootElement().addElement(
334
					new QName(KEYWORD_LAST_PRINTED, namespaceCoreProperties));
335
		} else {
336
			elem.clearContent();// clear the old value
337
		}
240
	}
338
		elem.addText(propsPart.getLastPrintedPropertyString());
339
	}
340
241
341
	/**
242
	/**
342
	 * Add modified property element if needed.
243
	 * Add modified property element if needed.
343
	 */
244
	 */
344
	private void addModified() {
245
	private void addModified() {
345
		if (!propsPart.getModifiedProperty().hasValue())
246
        setElementTextContent(KEYWORD_MODIFIED, namespaceDcTerms, propsPart.getModifiedProperty(),
346
			return;
247
                propsPart.getModifiedPropertyString(), "dcterms:W3CDTF");
347
348
		Element elem = xmlDoc.getRootElement().element(
349
				new QName(KEYWORD_MODIFIED, namespaceDcTerms));
350
		if (elem == null) {
351
			// missing, we add it
352
			elem = xmlDoc.getRootElement().addElement(
353
					new QName(KEYWORD_MODIFIED, namespaceDcTerms));
354
		} else {
355
			elem.clearContent();// clear the old value
356
		}
248
    }
357
		elem.addAttribute(new QName("type", namespaceXSI), "dcterms:W3CDTF");
358
		elem.addText(propsPart.getModifiedPropertyString());
359
	}
360
249
361
	/**
250
	/**
362
	 * Add revision property if needed.
251
	 * Add revision property if needed.
363
	 */
252
	 */
364
	private void addRevision() {
253
	private void addRevision() {
365
		if (!propsPart.getRevisionProperty().hasValue())
254
        setElementTextContent(KEYWORD_REVISION, namespaceCoreProperties, propsPart.getRevisionProperty());
366
			return;
367
368
		Element elem = xmlDoc.getRootElement().element(
369
				new QName(KEYWORD_REVISION, namespaceCoreProperties));
370
		if (elem == null) {
371
			// missing, we add it
372
			elem = xmlDoc.getRootElement().addElement(
373
					new QName(KEYWORD_REVISION, namespaceCoreProperties));
374
		} else {
375
			elem.clearContent();// clear the old value
376
		}
255
	}
377
		elem.addText(propsPart.getRevisionProperty().getValue());
378
	}
379
256
380
	/**
257
	/**
381
	 * Add subject property if needed.
258
	 * Add subject property if needed.
382
	 */
259
	 */
383
	private void addSubject() {
260
	private void addSubject() {
384
		if (!propsPart.getSubjectProperty().hasValue())
261
        setElementTextContent(KEYWORD_SUBJECT, namespaceDC, propsPart.getSubjectProperty());
385
			return;
386
387
		Element elem = xmlDoc.getRootElement().element(
388
				new QName(KEYWORD_SUBJECT, namespaceDC));
389
		if (elem == null) {
390
			// missing, we add it
391
			elem = xmlDoc.getRootElement().addElement(
392
					new QName(KEYWORD_SUBJECT, namespaceDC));
393
		} else {
394
			elem.clearContent();// clear the old value
395
		}
262
	}
396
		elem.addText(propsPart.getSubjectProperty().getValue());
397
	}
398
263
399
	/**
264
	/**
400
	 * Add title property if needed.
265
	 * Add title property if needed.
401
	 */
266
	 */
402
	private void addTitle() {
267
	private void addTitle() {
403
		if (!propsPart.getTitleProperty().hasValue())
268
        setElementTextContent(KEYWORD_TITLE, namespaceDC, propsPart.getTitleProperty());
404
			return;
405
406
		Element elem = xmlDoc.getRootElement().element(
407
				new QName(KEYWORD_TITLE, namespaceDC));
408
		if (elem == null) {
409
			// missing, we add it
410
			elem = xmlDoc.getRootElement().addElement(
411
					new QName(KEYWORD_TITLE, namespaceDC));
412
		} else {
413
			elem.clearContent();// clear the old value
414
		}
269
	}
415
		elem.addText(propsPart.getTitleProperty().getValue());
416
	}
417
270
418
	private void addVersion() {
271
	private void addVersion() {
419
		if (!propsPart.getVersionProperty().hasValue())
272
        setElementTextContent(KEYWORD_VERSION, namespaceCoreProperties, propsPart.getVersionProperty());
420
			return;
421
422
		Element elem = xmlDoc.getRootElement().element(
423
				new QName(KEYWORD_VERSION, namespaceCoreProperties));
424
		if (elem == null) {
425
			// missing, we add it
426
			elem = xmlDoc.getRootElement().addElement(
427
					new QName(KEYWORD_VERSION, namespaceCoreProperties));
428
		} else {
429
			elem.clearContent();// clear the old value
430
		}
431
		elem.addText(propsPart.getVersionProperty().getValue());
432
	}
273
	}
433
}
274
}
(-)sonar/ooxml/pom.xml (-6 lines)
Lines 116-127 Link Here
116
		  <version>2.3.0</version>
116
		  <version>2.3.0</version>
117
		</dependency>        
117
		</dependency>        
118
		
118
		
119
		<dependency>
120
			<groupId>dom4j</groupId>
121
			<artifactId>dom4j</artifactId>
122
			<version>1.6.1</version>
123
		</dependency>
124
		
125
		<!-- non-test dependency for OOXMLLite -->
119
		<!-- non-test dependency for OOXMLLite -->
126
        <dependency>
120
        <dependency>
127
            <groupId>junit</groupId>
121
            <groupId>junit</groupId>
(-)legal/NOTICE (-3 lines)
Lines 4-12 Link Here
4
This product includes software developed by
4
This product includes software developed by
5
The Apache Software Foundation (http://www.apache.org/).
5
The Apache Software Foundation (http://www.apache.org/).
6
6
7
This product contains the DOM4J library (http://www.dom4j.org).
8
Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
9
10
This product contains parts that were originally based on software from BEA.
7
This product contains parts that were originally based on software from BEA.
11
Copyright (c) 2000-2003, BEA Systems, <http://www.bea.com/>.
8
Copyright (c) 2000-2003, BEA Systems, <http://www.bea.com/>.
12
9
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java (-162 / +83 lines)
Lines 19-26 Link Here
19
19
20
import java.io.IOException;
20
import java.io.IOException;
21
import java.io.InputStream;
21
import java.io.InputStream;
22
import java.util.Iterator;
23
import java.util.List;
24
import java.util.zip.ZipEntry;
22
import java.util.zip.ZipEntry;
25
23
26
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
24
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
Lines 32-44 Link Here
32
import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller;
30
import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller;
33
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
31
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
34
import org.apache.poi.util.SAXHelper;
32
import org.apache.poi.util.SAXHelper;
35
import org.dom4j.Attribute;
33
import org.w3c.dom.*;
36
import org.dom4j.Document;
34
import org.xml.sax.SAXException;
37
import org.dom4j.DocumentException;
38
import org.dom4j.Element;
39
import org.dom4j.Namespace;
40
import org.dom4j.QName;
41
35
36
import javax.xml.XMLConstants;
37
import javax.xml.stream.XMLEventFactory;
38
import javax.xml.stream.events.Namespace;
39
42
/**
40
/**
43
 * Package properties unmarshaller.
41
 * Package properties unmarshaller.
44
 *
42
 *
Lines 46-66 Link Here
46
 */
44
 */
47
public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
45
public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
48
46
49
	private final static Namespace namespaceDC = new Namespace("dc",
47
	private final static Namespace namespaceDC = XMLEventFactory.newFactory().createNamespace("dc",
50
			PackageProperties.NAMESPACE_DC);
48
			PackageProperties.NAMESPACE_DC);
51
49
52
	private final static Namespace namespaceCP = new Namespace("cp",
50
	private final static Namespace namespaceCP = XMLEventFactory.newFactory().createNamespace("cp",
53
			PackageNamespaces.CORE_PROPERTIES);
51
			PackageNamespaces.CORE_PROPERTIES);
54
52
55
	private final static Namespace namespaceDcTerms = new Namespace("dcterms",
53
	private final static Namespace namespaceDcTerms = XMLEventFactory.newFactory().createNamespace("dcterms",
56
			PackageProperties.NAMESPACE_DCTERMS);
54
			PackageProperties.NAMESPACE_DCTERMS);
57
55
58
	private final static Namespace namespaceXML = new Namespace("xml",
56
	private final static Namespace namespaceXSI = XMLEventFactory.newFactory().createNamespace("xsi",
59
			"http://www.w3.org/XML/1998/namespace");
57
			XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
60
58
61
	private final static Namespace namespaceXSI = new Namespace("xsi",
62
			"http://www.w3.org/2001/XMLSchema-instance");
63
64
	protected static final String KEYWORD_CATEGORY = "category";
59
	protected static final String KEYWORD_CATEGORY = "category";
65
60
66
	protected static final String KEYWORD_CONTENT_STATUS = "contentStatus";
61
	protected static final String KEYWORD_CONTENT_STATUS = "contentStatus";
Lines 125-139 Link Here
125
			/* Check OPC compliance */
120
			/* Check OPC compliance */
126
121
127
			// Rule M4.2, M4.3, M4.4 and M4.5/
122
			// Rule M4.2, M4.3, M4.4 and M4.5/
128
			checkElementForOPCCompliance(xmlDoc.getRootElement());
123
			checkElementForOPCCompliance(xmlDoc.getDocumentElement());
129
124
130
			/* End OPC compliance */
125
			/* End OPC compliance */
131
126
132
		} catch (DocumentException e) {
127
        } catch (SAXException e) {
133
			throw new IOException(e.getMessage());
128
            throw new IOException(e.getMessage());
134
		}
129
        }
135
130
136
		coreProps.setCategoryProperty(loadCategory(xmlDoc));
131
        coreProps.setCategoryProperty(loadCategory(xmlDoc));
137
		coreProps.setContentStatusProperty(loadContentStatus(xmlDoc));
132
		coreProps.setContentStatusProperty(loadContentStatus(xmlDoc));
138
		coreProps.setContentTypeProperty(loadContentType(xmlDoc));
133
		coreProps.setContentTypeProperty(loadContentType(xmlDoc));
139
		coreProps.setCreatedProperty(loadCreated(xmlDoc));
134
		coreProps.setCreatedProperty(loadCreated(xmlDoc));
Lines 153-301 Link Here
153
		return coreProps;
148
		return coreProps;
154
	}
149
	}
155
150
156
	private String loadCategory(Document xmlDoc) {
151
    private String readElement(Document xmlDoc, String localName, Namespace namespace) {
157
		Element el = xmlDoc.getRootElement().element(
152
        Element el = (Element)xmlDoc.getDocumentElement().getElementsByTagNameNS(namespace.getNamespaceURI(), localName).item(0);
158
				new QName(KEYWORD_CATEGORY, namespaceCP));
159
		if (el == null) {
153
        if (el == null) {
160
			return null;
154
            return null;
161
		}
155
        }
162
		return el.getStringValue();
156
        return el.getTextContent();
163
	}
157
    }
164
158
165
	private String loadContentStatus(Document xmlDoc) {
159
	private String loadCategory(Document xmlDoc) {
160
        return readElement(xmlDoc, KEYWORD_CATEGORY, namespaceCP);
161
	}
162
166
		Element el = xmlDoc.getRootElement().element(
163
    private String loadContentStatus(Document xmlDoc) {
167
				new QName(KEYWORD_CONTENT_STATUS, namespaceCP));
168
		if (el == null) {
169
			return null;
170
		}
164
        return readElement(xmlDoc, KEYWORD_CONTENT_STATUS, namespaceCP);
171
		return el.getStringValue();
165
	}
172
	}
173
166
174
	private String loadContentType(Document xmlDoc) {
167
	private String loadContentType(Document xmlDoc) {
175
		Element el = xmlDoc.getRootElement().element(
168
        return readElement(xmlDoc, KEYWORD_CONTENT_TYPE, namespaceCP);
176
				new QName(KEYWORD_CONTENT_TYPE, namespaceCP));
177
		if (el == null) {
178
			return null;
179
		}
169
	}
180
		return el.getStringValue();
181
	}
182
170
183
	private String loadCreated(Document xmlDoc) {
171
	private String loadCreated(Document xmlDoc) {
184
		Element el = xmlDoc.getRootElement().element(
172
        return readElement(xmlDoc, KEYWORD_CREATED, namespaceDcTerms);
185
				new QName(KEYWORD_CREATED, namespaceDcTerms));
186
		if (el == null) {
187
			return null;
188
		}
173
	}
189
		return el.getStringValue();
190
	}
191
174
192
	private String loadCreator(Document xmlDoc) {
175
	private String loadCreator(Document xmlDoc) {
193
		Element el = xmlDoc.getRootElement().element(
176
        return readElement(xmlDoc, KEYWORD_CREATOR, namespaceDC);
194
				new QName(KEYWORD_CREATOR, namespaceDC));
195
		if (el == null) {
196
			return null;
197
		}
177
	}
198
		return el.getStringValue();
199
	}
200
178
201
	private String loadDescription(Document xmlDoc) {
179
	private String loadDescription(Document xmlDoc) {
202
		Element el = xmlDoc.getRootElement().element(
180
        return readElement(xmlDoc, KEYWORD_DESCRIPTION, namespaceDC);
203
				new QName(KEYWORD_DESCRIPTION, namespaceDC));
204
		if (el == null) {
205
			return null;
206
		}
181
	}
207
		return el.getStringValue();
208
	}
209
182
210
	private String loadIdentifier(Document xmlDoc) {
183
	private String loadIdentifier(Document xmlDoc) {
211
		Element el = xmlDoc.getRootElement().element(
184
        return readElement(xmlDoc, KEYWORD_IDENTIFIER, namespaceDC);
212
				new QName(KEYWORD_IDENTIFIER, namespaceDC));
213
		if (el == null) {
214
			return null;
215
		}
185
	}
216
		return el.getStringValue();
217
	}
218
186
219
	private String loadKeywords(Document xmlDoc) {
187
	private String loadKeywords(Document xmlDoc) {
220
		Element el = xmlDoc.getRootElement().element(
188
        return readElement(xmlDoc, KEYWORD_KEYWORDS, namespaceCP);
221
				new QName(KEYWORD_KEYWORDS, namespaceCP));
222
		if (el == null) {
223
			return null;
224
		}
189
	}
225
		return el.getStringValue();
226
	}
227
190
228
	private String loadLanguage(Document xmlDoc) {
191
	private String loadLanguage(Document xmlDoc) {
229
		Element el = xmlDoc.getRootElement().element(
192
        return readElement(xmlDoc, KEYWORD_LANGUAGE, namespaceDC);
230
				new QName(KEYWORD_LANGUAGE, namespaceDC));
231
		if (el == null) {
232
			return null;
233
		}
193
	}
234
		return el.getStringValue();
235
	}
236
194
237
	private String loadLastModifiedBy(Document xmlDoc) {
195
	private String loadLastModifiedBy(Document xmlDoc) {
238
		Element el = xmlDoc.getRootElement().element(
196
        return readElement(xmlDoc, KEYWORD_LAST_MODIFIED_BY, namespaceCP);
239
				new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCP));
240
		if (el == null) {
241
			return null;
242
		}
197
	}
243
		return el.getStringValue();
244
	}
245
198
246
	private String loadLastPrinted(Document xmlDoc) {
199
	private String loadLastPrinted(Document xmlDoc) {
247
		Element el = xmlDoc.getRootElement().element(
200
        return readElement(xmlDoc, KEYWORD_LAST_PRINTED, namespaceCP);
248
				new QName(KEYWORD_LAST_PRINTED, namespaceCP));
249
		if (el == null) {
250
			return null;
251
		}
201
	}
252
		return el.getStringValue();
253
	}
254
202
255
	private String loadModified(Document xmlDoc) {
203
	private String loadModified(Document xmlDoc) {
256
		Element el = xmlDoc.getRootElement().element(
204
        return readElement(xmlDoc, KEYWORD_MODIFIED, namespaceDcTerms);
257
				new QName(KEYWORD_MODIFIED, namespaceDcTerms));
258
		if (el == null) {
259
			return null;
260
		}
205
	}
261
		return el.getStringValue();
262
	}
263
206
264
	private String loadRevision(Document xmlDoc) {
207
	private String loadRevision(Document xmlDoc) {
265
		Element el = xmlDoc.getRootElement().element(
208
        return readElement(xmlDoc, KEYWORD_REVISION, namespaceCP);
266
				new QName(KEYWORD_REVISION, namespaceCP));
267
		if (el == null) {
268
			return null;
269
		}
209
	}
270
		return el.getStringValue();
271
	}
272
210
273
	private String loadSubject(Document xmlDoc) {
211
	private String loadSubject(Document xmlDoc) {
274
		Element el = xmlDoc.getRootElement().element(
212
        return readElement(xmlDoc, KEYWORD_SUBJECT, namespaceDC);
275
				new QName(KEYWORD_SUBJECT, namespaceDC));
276
		if (el == null) {
277
			return null;
278
		}
213
	}
279
		return el.getStringValue();
280
	}
281
214
282
	private String loadTitle(Document xmlDoc) {
215
	private String loadTitle(Document xmlDoc) {
283
		Element el = xmlDoc.getRootElement().element(
216
        return readElement(xmlDoc, KEYWORD_TITLE, namespaceDC);
284
				new QName(KEYWORD_TITLE, namespaceDC));
285
		if (el == null) {
286
			return null;
287
		}
217
	}
288
		return el.getStringValue();
289
	}
290
218
291
	private String loadVersion(Document xmlDoc) {
219
	private String loadVersion(Document xmlDoc) {
292
		Element el = xmlDoc.getRootElement().element(
220
        return readElement(xmlDoc, KEYWORD_VERSION, namespaceCP);
293
				new QName(KEYWORD_VERSION, namespaceCP));
294
		if (el == null) {
295
			return null;
296
		}
221
	}
297
		return el.getStringValue();
298
	}
299
222
300
	/* OPC Compliance methods */
223
	/* OPC Compliance methods */
301
224
Lines 325-368 Link Here
325
	public void checkElementForOPCCompliance(Element el)
248
	public void checkElementForOPCCompliance(Element el)
326
			throws InvalidFormatException {
249
			throws InvalidFormatException {
327
		// Check the current element
250
		// Check the current element
328
		@SuppressWarnings("unchecked")
251
        NamedNodeMap namedNodeMap = el.getAttributes();
329
		List<Namespace> declaredNamespaces = el.declaredNamespaces();
252
        int namedNodeCount = namedNodeMap.getLength();
330
		Iterator<Namespace> itNS = declaredNamespaces.iterator();
253
        for (int i = 0; i < namedNodeCount; i++) {
331
		while (itNS.hasNext()) {
254
            Attr attr = (Attr)namedNodeMap.item(0);
332
			Namespace ns = itNS.next();
333
255
334
			// Rule M4.2
256
            if (attr.getNamespaceURI().equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
335
			if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
257
                // Rule M4.2
336
				throw new InvalidFormatException(
258
                if (attr.getValue().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
337
						"OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
338
		}
259
                    throw new InvalidFormatException(
260
                            "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
261
262
            }
263
        }
339
264
340
		// Rule M4.3
265
		// Rule M4.3
341
		if (el.getNamespace().getURI().equals(
266
        String elName = el.getLocalName();
342
				PackageProperties.NAMESPACE_DCTERMS)
267
        if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS))
343
				&& !(el.getName().equals(KEYWORD_CREATED) || el.getName()
268
            if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED)))
344
						.equals(KEYWORD_MODIFIED)))
345
			throw new InvalidFormatException(
269
                throw new InvalidFormatException(
346
					"OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");
270
                        "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");
347
271
348
		// Rule M4.4
272
		// Rule M4.4
349
		if (el.attribute(new QName("lang", namespaceXML)) != null)
273
		if (el.getAttributeNodeNS(XMLConstants.XML_NS_URI, "lang") != null)
350
			throw new InvalidFormatException(
274
			throw new InvalidFormatException(
351
					"OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");
275
					"OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");
352
276
353
		// Rule M4.5
277
		// Rule M4.5
354
		if (el.getNamespace().getURI().equals(
278
		if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS)) {
355
				PackageProperties.NAMESPACE_DCTERMS)) {
356
			// DCTerms namespace only use with 'created' and 'modified' elements
279
			// DCTerms namespace only use with 'created' and 'modified' elements
357
			String elName = el.getName();
280
			if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED)))
358
			if (!(elName.equals(KEYWORD_CREATED) || elName
359
					.equals(KEYWORD_MODIFIED)))
360
				throw new InvalidFormatException("Namespace error : " + elName
281
				throw new InvalidFormatException("Namespace error : " + elName
361
						+ " shouldn't have the following naemspace -> "
282
						+ " shouldn't have the following naemspace -> "
362
						+ PackageProperties.NAMESPACE_DCTERMS);
283
						+ PackageProperties.NAMESPACE_DCTERMS);
363
284
364
			// Check for the 'xsi:type' attribute
285
			// Check for the 'xsi:type' attribute
365
			Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));
286
			Attr typeAtt = el.getAttributeNodeNS(namespaceXSI.getNamespaceURI(), "type");
366
			if (typeAtt == null)
287
			if (typeAtt == null)
367
				throw new InvalidFormatException("The element '" + elName
288
				throw new InvalidFormatException("The element '" + elName
368
						+ "' must have the '" + namespaceXSI.getPrefix()
289
						+ "' must have the '" + namespaceXSI.getPrefix()
Lines 376-384 Link Here
376
		}
297
		}
377
298
378
		// Check its children
299
		// Check its children
379
		@SuppressWarnings("unchecked")
300
        NodeList childElements = el.getElementsByTagName("*");
380
		Iterator<Element> itChildren = el.elementIterator();
301
        int childElementCount = childElements.getLength();
381
		while (itChildren.hasNext())
302
        for (int i = 0; i < childElementCount; i++)
382
			checkElementForOPCCompliance(itChildren.next());
303
            checkElementForOPCCompliance((Element)childElements.item(i));
383
	}
304
	}
384
}
305
}
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipCollection.java (-18 / +10 lines)
Lines 27-35 Link Here
27
import org.apache.poi.util.POILogFactory;
27
import org.apache.poi.util.POILogFactory;
28
import org.apache.poi.util.POILogger;
28
import org.apache.poi.util.POILogger;
29
import org.apache.poi.util.SAXHelper;
29
import org.apache.poi.util.SAXHelper;
30
import org.dom4j.Attribute;
30
import org.w3c.dom.*;
31
import org.dom4j.Document;
32
import org.dom4j.Element;
33
31
34
/**
32
/**
35
 * Represents a collection of PackageRelationship elements that are owned by a
33
 * Represents a collection of PackageRelationship elements that are owned by a
Lines 313-334 Link Here
313
            Document xmlRelationshipsDoc = SAXHelper.readSAXDocument(relPart.getInputStream());
311
            Document xmlRelationshipsDoc = SAXHelper.readSAXDocument(relPart.getInputStream());
314
312
315
            // Browse default types
313
            // Browse default types
316
            Element root = xmlRelationshipsDoc.getRootElement();
314
            Element root = xmlRelationshipsDoc.getDocumentElement();
317
315
318
            // Check OPC compliance M4.1 rule
316
            // Check OPC compliance M4.1 rule
319
            boolean fCorePropertiesRelationship = false;
317
            boolean fCorePropertiesRelationship = false;
320
318
321
            @SuppressWarnings("unchecked")
319
            NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME);
322
            Iterator<Element> iter = (Iterator<Element>)
320
            int nodeCount = nodeList.getLength();
323
                root.elementIterator(PackageRelationship.RELATIONSHIP_TAG_NAME);
321
            for (int i = 0; i < nodeCount; i++) {
324
            while (iter.hasNext()) {
322
                Element element = (Element)nodeList.item(i);
325
                Element element = iter.next();
326
                // Relationship ID
323
                // Relationship ID
327
                String id = element.attribute(
324
                String id = element.getAttribute(PackageRelationship.ID_ATTRIBUTE_NAME);
328
                        PackageRelationship.ID_ATTRIBUTE_NAME).getValue();
329
                // Relationship type
325
                // Relationship type
330
                String type = element.attribute(
326
                String type = element.getAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME);
331
                        PackageRelationship.TYPE_ATTRIBUTE_NAME).getValue();
332
327
333
                /* Check OPC Compliance */
328
                /* Check OPC Compliance */
334
                // Check Rule M4.1
329
                // Check Rule M4.1
Lines 342-349 Link Here
342
                /* End OPC Compliance */
337
                /* End OPC Compliance */
343
338
344
                // TargetMode (default value "Internal")
339
                // TargetMode (default value "Internal")
345
                Attribute targetModeAttr = element
340
                Attr targetModeAttr = element.getAttributeNode(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
346
                        .attribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
347
                TargetMode targetMode = TargetMode.INTERNAL;
341
                TargetMode targetMode = TargetMode.INTERNAL;
348
                if (targetModeAttr != null) {
342
                if (targetModeAttr != null) {
349
                    targetMode = targetModeAttr.getValue().toLowerCase()
343
                    targetMode = targetModeAttr.getValue().toLowerCase()
Lines 353-361 Link Here
353
347
354
                // Target converted in URI
348
                // Target converted in URI
355
                URI target = PackagingURIHelper.toURI("http://invalid.uri"); // dummy url
349
                URI target = PackagingURIHelper.toURI("http://invalid.uri"); // dummy url
356
                String value = element.attribute(
350
                String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
357
                        PackageRelationship.TARGET_ATTRIBUTE_NAME)
358
                        .getValue();
359
                try {
351
                try {
360
                    // when parsing of the given uri fails, we can either
352
                    // when parsing of the given uri fails, we can either
361
                    // ignore this relationship, which leads to IllegalStateException
353
                    // ignore this relationship, which leads to IllegalStateException
(-)src/java/org/apache/poi/util/XMLHelper.java (+12 lines)
Lines 17-22 Link Here
17
17
18
package org.apache.poi.util;
18
package org.apache.poi.util;
19
19
20
import org.w3c.dom.Element;
21
20
import javax.xml.XMLConstants;
22
import javax.xml.XMLConstants;
21
import javax.xml.parsers.DocumentBuilderFactory;
23
import javax.xml.parsers.DocumentBuilderFactory;
22
import javax.xml.parsers.ParserConfigurationException;
24
import javax.xml.parsers.ParserConfigurationException;
Lines 45-48 Link Here
45
            throw new RuntimeException("Broken XML Setup", e);
47
            throw new RuntimeException("Broken XML Setup", e);
46
        }
48
        }
47
    }
49
    }
50
51
    /**
52
     * Adds a namespace declaration attribute to the given element.
53
     */
54
    public static void addNamespaceDeclaration(Element element, String namespacePrefix, String namespaceURI) {
55
        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
56
                XMLConstants.XMLNS_ATTRIBUTE + ':' + namespacePrefix,
57
                namespaceURI);
58
    }
59
48
}
60
}
(-)src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTask.java (-1 / +1 lines)
Lines 179-185 Link Here
179
            throw new BuildException(
179
            throw new BuildException(
180
                    "The <classpath> for <excelant> must include poi.jar and poi-ooxml.jar " +
180
                    "The <classpath> for <excelant> must include poi.jar and poi-ooxml.jar " +
181
                    "if not in Ant's own classpath. Processing .xlsx spreadsheets requires " +
181
                    "if not in Ant's own classpath. Processing .xlsx spreadsheets requires " +
182
                    "additional poi-ooxml-schemas.jar, xmlbeans.jar and dom4j.jar" ,
182
                    "additional poi-ooxml-schemas.jar, xmlbeans.jar" ,
183
                    e, getLocation());
183
                    e, getLocation());
184
        }
184
        }
185
185
(-)src/documentation/content/xdocs/spreadsheet/excelant.xml (-1 lines)
Lines 50-56 Link Here
50
            <ul>
50
            <ul>
51
                <li>poi-ooxml-schemas-$version-YYYYDDMM.jar</li>
51
                <li>poi-ooxml-schemas-$version-YYYYDDMM.jar</li>
52
                <li>xmlbeans.jar</li>
52
                <li>xmlbeans.jar</li>
53
                <li>dom4j.jar</li>
54
            </ul>
53
            </ul>
55
            <p>For example, if you have these jars in a lib/ dir in your project, your build.xml 
54
            <p>For example, if you have these jars in a lib/ dir in your project, your build.xml 
56
            might look like this:</p>
55
            might look like this:</p>
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java (-5 / +14 lines)
Lines 17-29 Link Here
17
17
18
package org.apache.poi.openxml4j.opc;
18
package org.apache.poi.openxml4j.opc;
19
19
20
import org.w3c.dom.Document;
21
22
import javax.xml.transform.Result;
23
import javax.xml.transform.Source;
24
import javax.xml.transform.TransformerFactory;
25
import javax.xml.transform.dom.DOMSource;
26
import javax.xml.transform.stream.StreamResult;
20
import java.io.InputStream;
27
import java.io.InputStream;
21
import java.io.OutputStream;
28
import java.io.OutputStream;
22
29
23
import org.dom4j.Document;
24
import org.dom4j.io.OutputFormat;
25
import org.dom4j.io.XMLWriter;
26
27
public final class StreamHelper {
30
public final class StreamHelper {
28
31
29
	private StreamHelper() {
32
	private StreamHelper() {
Lines 31-37 Link Here
31
	}
34
	}
32
35
33
	/**
36
	/**
34
	 * Turning the DOM4j object in the specified output stream.
37
	 * Save the document object in the specified output stream.
35
	 *
38
	 *
36
	 * @param xmlContent
39
	 * @param xmlContent
37
	 *            The XML document.
40
	 *            The XML document.
Lines 43-52 Link Here
43
	public static boolean saveXmlInStream(Document xmlContent,
46
	public static boolean saveXmlInStream(Document xmlContent,
44
			OutputStream outStream) {
47
			OutputStream outStream) {
45
		try {
48
		try {
49
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
50
            Source xmlSource = new DOMSource(xmlContent);
51
            Result outputTarget = new StreamResult(outStream);
52
            transformerFactory.newTransformer().transform(xmlSource, outputTarget);
53
/*
46
			OutputFormat outformat = OutputFormat.createPrettyPrint();
54
			OutputFormat outformat = OutputFormat.createPrettyPrint();
47
			outformat.setEncoding("UTF-8");
55
			outformat.setEncoding("UTF-8");
48
			XMLWriter writer = new XMLWriter(outStream, outformat);
56
			XMLWriter writer = new XMLWriter(outStream, outformat);
49
			writer.write(xmlContent);
57
			writer.write(xmlContent);
58
*/
50
		} catch (Exception e) {
59
		} catch (Exception e) {
51
			return false;
60
			return false;
52
		}
61
		}
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentTypeManager.java (-44 / +35 lines)
Lines 17-28 Link Here
17
17
18
package org.apache.poi.openxml4j.opc.internal;
18
package org.apache.poi.openxml4j.opc.internal;
19
19
20
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.InputStream;
21
import java.io.OutputStream;
22
import java.io.OutputStream;
22
import java.net.URI;
23
import java.net.URI;
23
import java.net.URISyntaxException;
24
import java.net.URISyntaxException;
24
import java.util.Iterator;
25
import java.util.List;
26
import java.util.Map.Entry;
25
import java.util.Map.Entry;
27
import java.util.TreeMap;
26
import java.util.TreeMap;
28
27
Lines 33-45 Link Here
33
import org.apache.poi.openxml4j.opc.PackagePart;
32
import org.apache.poi.openxml4j.opc.PackagePart;
34
import org.apache.poi.openxml4j.opc.PackagePartName;
33
import org.apache.poi.openxml4j.opc.PackagePartName;
35
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
34
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
35
import org.apache.poi.util.DocumentHelper;
36
import org.apache.poi.util.SAXHelper;
36
import org.apache.poi.util.SAXHelper;
37
import org.dom4j.Document;
37
import org.w3c.dom.Document;
38
import org.dom4j.DocumentException;
38
import org.w3c.dom.Element;
39
import org.dom4j.DocumentHelper;
39
import org.w3c.dom.NodeList;
40
import org.dom4j.Element;
40
import org.xml.sax.SAXException;
41
import org.dom4j.Namespace;
42
import org.dom4j.QName;
43
41
44
/**
42
/**
45
 * Manage package content types ([Content_Types].xml part).
43
 * Manage package content types ([Content_Types].xml part).
Lines 376-413 Link Here
376
			Document xmlContentTypetDoc = SAXHelper.readSAXDocument(in);
374
			Document xmlContentTypetDoc = SAXHelper.readSAXDocument(in);
377
375
378
			// Default content types
376
			// Default content types
379
			List defaultTypes = xmlContentTypetDoc.getRootElement().elements(
377
			NodeList defaultTypes = xmlContentTypetDoc.getDocumentElement().getElementsByTagName(DEFAULT_TAG_NAME);
380
					DEFAULT_TAG_NAME);
378
			int defaultTypeCount = defaultTypes.getLength();
381
			Iterator elementIteratorDefault = defaultTypes.iterator();
379
			for (int i = 0; i < defaultTypeCount; i++) {
382
			while (elementIteratorDefault.hasNext()) {
380
                Element element = (Element) defaultTypes.item(i);
383
				Element element = (Element) elementIteratorDefault.next();
381
				String extension = element.getAttribute(EXTENSION_ATTRIBUTE_NAME);
384
				String extension = element.attribute(EXTENSION_ATTRIBUTE_NAME)
382
				String contentType = element.getAttribute(CONTENT_TYPE_ATTRIBUTE_NAME);
385
						.getValue();
386
				String contentType = element.attribute(
387
						CONTENT_TYPE_ATTRIBUTE_NAME).getValue();
388
				addDefaultContentType(extension, contentType);
383
				addDefaultContentType(extension, contentType);
389
			}
384
			}
390
385
391
			// Overriden content types
386
			// Overriden content types
392
			List overrideTypes = xmlContentTypetDoc.getRootElement().elements(
387
            NodeList overrideTypes = xmlContentTypetDoc.getDocumentElement().getElementsByTagName(OVERRIDE_TAG_NAME);
393
					OVERRIDE_TAG_NAME);
388
            int overrideTypeCount = overrideTypes.getLength();
394
			Iterator elementIteratorOverride = overrideTypes.iterator();
389
            for (int i = 0; i < overrideTypeCount; i++) {
395
			while (elementIteratorOverride.hasNext()) {
390
				Element element = (Element) overrideTypes.item(i);
396
				Element element = (Element) elementIteratorOverride.next();
391
				URI uri = new URI(element.getAttribute(PART_NAME_ATTRIBUTE_NAME));
397
				URI uri = new URI(element.attribute(PART_NAME_ATTRIBUTE_NAME)
392
				PackagePartName partName = PackagingURIHelper.createPartName(uri);
398
						.getValue());
393
				String contentType = element.getAttribute(CONTENT_TYPE_ATTRIBUTE_NAME);
399
				PackagePartName partName = PackagingURIHelper
400
						.createPartName(uri);
401
				String contentType = element.attribute(
402
						CONTENT_TYPE_ATTRIBUTE_NAME).getValue();
403
				addOverrideContentType(partName, contentType);
394
				addOverrideContentType(partName, contentType);
404
			}
395
			}
405
		} catch (URISyntaxException urie) {
396
		} catch (URISyntaxException urie) {
406
			throw new InvalidFormatException(urie.getMessage());
397
			throw new InvalidFormatException(urie.getMessage());
407
		} catch (DocumentException e) {
398
        } catch (SAXException e) {
408
			throw new InvalidFormatException(e.getMessage());
399
            throw new InvalidFormatException(e.getMessage());
400
        } catch (IOException e) {
401
            throw new InvalidFormatException(e.getMessage());
409
		}
402
        }
410
	}
403
    }
411
404
412
	/**
405
	/**
413
	 * Save the contents type part.
406
	 * Save the contents type part.
Lines 421-429 Link Here
421
		Document xmlOutDoc = DocumentHelper.createDocument();
414
		Document xmlOutDoc = DocumentHelper.createDocument();
422
415
423
		// Building namespace
416
		// Building namespace
424
		Namespace dfNs = Namespace.get("", TYPES_NAMESPACE_URI);
417
		Element typesElem = xmlOutDoc.createElementNS(TYPES_NAMESPACE_URI, TYPES_TAG_NAME);
425
		Element typesElem = xmlOutDoc
418
        xmlOutDoc.appendChild(typesElem);
426
				.addElement(new QName(TYPES_TAG_NAME, dfNs));
427
419
428
		// Adding default types
420
		// Adding default types
429
		for (Entry<String, String> entry : defaultContentType.entrySet()) {
421
		for (Entry<String, String> entry : defaultContentType.entrySet()) {
Lines 454-463 Link Here
454
	 */
446
	 */
455
	private void appendSpecificTypes(Element root,
447
	private void appendSpecificTypes(Element root,
456
			Entry<PackagePartName, String> entry) {
448
			Entry<PackagePartName, String> entry) {
457
		root.addElement(OVERRIDE_TAG_NAME).addAttribute(
449
        Element specificType = root.getOwnerDocument().createElement(OVERRIDE_TAG_NAME);
458
				PART_NAME_ATTRIBUTE_NAME,
450
        specificType.setAttribute(PART_NAME_ATTRIBUTE_NAME, entry.getKey().getName());
459
				entry.getKey().getName()).addAttribute(
451
        specificType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
460
				CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
452
        root.appendChild(specificType);
461
	}
453
	}
462
454
463
	/**
455
	/**
Lines 470-480 Link Here
470
	 * @see #save(java.io.OutputStream)
462
	 * @see #save(java.io.OutputStream)
471
	 */
463
	 */
472
	private void appendDefaultType(Element root, Entry<String, String> entry) {
464
	private void appendDefaultType(Element root, Entry<String, String> entry) {
473
		root.addElement(DEFAULT_TAG_NAME).addAttribute(
465
        Element defaultType = root.getOwnerDocument().createElement(DEFAULT_TAG_NAME);
474
				EXTENSION_ATTRIBUTE_NAME, entry.getKey())
466
        defaultType.setAttribute(EXTENSION_ATTRIBUTE_NAME, entry.getKey());
475
				.addAttribute(CONTENT_TYPE_ATTRIBUTE_NAME,
467
        defaultType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
476
						entry.getValue());
468
        root.appendChild(defaultType);
477
478
	}
469
	}
479
470
480
	/**
471
	/**
(-)src/documentation/content/xdocs/overview.xml (-1 / +1 lines)
Lines 270-276 Link Here
270
        </tr>
270
        </tr>
271
        <tr>
271
        <tr>
272
          <td>poi-ooxml</td>
272
          <td>poi-ooxml</td>
273
          <td>poi, poi-ooxml-schemas, dom4j</td>
273
          <td>poi, poi-ooxml-schemas</td>
274
          <td>poi-ooxml-version-yyyymmdd.jar</td>
274
          <td>poi-ooxml-version-yyyymmdd.jar</td>
275
        </tr>
275
        </tr>
276
        <tr>
276
        <tr>
(-)maven/poi-ooxml.pom (-5 lines)
Lines 69-78 Link Here
69
      <artifactId>poi-ooxml-schemas</artifactId>
69
      <artifactId>poi-ooxml-schemas</artifactId>
70
      <version>@VERSION@</version>
70
      <version>@VERSION@</version>
71
    </dependency>
71
    </dependency>
72
    <dependency>
73
        <groupId>dom4j</groupId>
74
        <artifactId>dom4j</artifactId>
75
        <version>1.6.1</version>
76
    </dependency>
77
  </dependencies>
72
  </dependencies>
78
</project>
73
</project>
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java (-19 / +11 lines)
Lines 24-34 Link Here
24
import java.util.zip.ZipEntry;
24
import java.util.zip.ZipEntry;
25
import java.util.zip.ZipOutputStream;
25
import java.util.zip.ZipOutputStream;
26
26
27
import org.dom4j.Document;
28
import org.dom4j.DocumentHelper;
29
import org.dom4j.Element;
30
import org.dom4j.Namespace;
31
import org.dom4j.QName;
32
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
27
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
33
import org.apache.poi.openxml4j.opc.PackageNamespaces;
28
import org.apache.poi.openxml4j.opc.PackageNamespaces;
34
import org.apache.poi.openxml4j.opc.PackagePart;
29
import org.apache.poi.openxml4j.opc.PackagePart;
Lines 40-47 Link Here
40
import org.apache.poi.openxml4j.opc.TargetMode;
35
import org.apache.poi.openxml4j.opc.TargetMode;
41
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
36
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
42
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
37
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
38
import org.apache.poi.util.DocumentHelper;
43
import org.apache.poi.util.POILogger;
39
import org.apache.poi.util.POILogger;
44
import org.apache.poi.util.POILogFactory;
40
import org.apache.poi.util.POILogFactory;
41
import org.w3c.dom.Document;
42
import org.w3c.dom.Element;
45
43
46
/**
44
/**
47
 * Zip part marshaller. This marshaller is use to save any part in a zip stream.
45
 * Zip part marshaller. This marshaller is use to save any part in a zip stream.
Lines 122-130 Link Here
122
		Document xmlOutDoc = DocumentHelper.createDocument();
120
		Document xmlOutDoc = DocumentHelper.createDocument();
123
		// make something like <Relationships
121
		// make something like <Relationships
124
		// xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
122
		// xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
125
		Namespace dfNs = Namespace.get("", PackageNamespaces.RELATIONSHIPS);
123
		Element root = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIPS_TAG_NAME);
126
		Element root = xmlOutDoc.addElement(new QName(
124
        xmlOutDoc.appendChild(root);
127
				PackageRelationship.RELATIONSHIPS_TAG_NAME, dfNs));
128
125
129
		// <Relationship
126
		// <Relationship
130
		// TargetMode="External"
127
		// TargetMode="External"
Lines 137-152 Link Here
137
134
138
		for (PackageRelationship rel : rels) {
135
		for (PackageRelationship rel : rels) {
139
			// the relationship element
136
			// the relationship element
140
			Element relElem = root
137
            Element relElem = xmlOutDoc.createElement(PackageRelationship.RELATIONSHIP_TAG_NAME);
141
					.addElement(PackageRelationship.RELATIONSHIP_TAG_NAME);
138
            root.appendChild(relElem);
142
139
143
			// the relationship ID
140
			// the relationship ID
144
			relElem.addAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel
141
			relElem.setAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.getId());
145
					.getId());
146
142
147
			// the relationship Type
143
			// the relationship Type
148
			relElem.addAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel
144
			relElem.setAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel.getRelationshipType());
149
					.getRelationshipType());
150
145
151
			// the relationship Target
146
			// the relationship Target
152
			String targetValue;
147
			String targetValue;
Lines 157-172 Link Here
157
				targetValue = uri.toString();
152
				targetValue = uri.toString();
158
153
159
				// add TargetMode attribute (as it is external link external)
154
				// add TargetMode attribute (as it is external link external)
160
				relElem.addAttribute(
155
				relElem.setAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External");
161
						PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME,
162
						"External");
163
			} else {
156
			} else {
164
                URI targetURI = rel.getTargetURI();
157
                URI targetURI = rel.getTargetURI();
165
                targetValue = PackagingURIHelper.relativizeURI(
158
                targetValue = PackagingURIHelper.relativizeURI(
166
						sourcePartURI, targetURI, true).toString();
159
						sourcePartURI, targetURI, true).toString();
167
			}
160
			}
168
			relElem.addAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME,
161
			relElem.setAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue);
169
					targetValue);
170
		}
162
		}
171
163
172
		xmlOutDoc.normalize();
164
		xmlOutDoc.normalize();
(-)build.xml (-12 lines)
Lines 148-155 Link Here
148
    <property name="main.antlauncher.url" value="${repository.m2}/maven2/org/apache/ant/ant-launcher/1.9.4/ant-launcher-1.9.4.jar"/>
148
    <property name="main.antlauncher.url" value="${repository.m2}/maven2/org/apache/ant/ant-launcher/1.9.4/ant-launcher-1.9.4.jar"/>
149
149
150
    <!-- jars in the lib-ooxml directory, see the fetch-ooxml-jars target-->
150
    <!-- jars in the lib-ooxml directory, see the fetch-ooxml-jars target-->
151
    <property name="ooxml.dom4j.jar" location="${ooxml.lib}/dom4j-1.6.1.jar"/>
152
    <property name="ooxml.dom4j.url" value="${repository.m2}/maven2/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar"/>
153
    <property name="ooxml.xmlbeans23.jar" location="${ooxml.lib}/xmlbeans-2.3.0.jar"/>
151
    <property name="ooxml.xmlbeans23.jar" location="${ooxml.lib}/xmlbeans-2.3.0.jar"/>
154
    <property name="ooxml.xmlbeans23.url"
152
    <property name="ooxml.xmlbeans23.url"
155
              value="${repository.m2}/maven2/org/apache/xmlbeans/xmlbeans/2.3.0/xmlbeans-2.3.0.jar"/>
153
              value="${repository.m2}/maven2/org/apache/xmlbeans/xmlbeans/2.3.0/xmlbeans-2.3.0.jar"/>
Lines 221-227 Link Here
221
    </path>
219
    </path>
222
220
223
    <path id="ooxml.classpath">
221
    <path id="ooxml.classpath">
224
        <pathelement location="${ooxml.dom4j.jar}"/>
225
        <pathelement location="${ooxml.xmlbeans26.jar}"/>
222
        <pathelement location="${ooxml.xmlbeans26.jar}"/>
226
        <pathelement location="${ooxml.xsds.jar}"/>
223
        <pathelement location="${ooxml.xsds.jar}"/>
227
        <path refid="main.classpath"/>
224
        <path refid="main.classpath"/>
Lines 251-257 Link Here
251
    </path>
248
    </path>
252
249
253
    <path id="ooxml-lite.classpath">
250
    <path id="ooxml-lite.classpath">
254
        <pathelement location="${ooxml.dom4j.jar}"/>
255
        <pathelement location="${ooxml.xmlbeans26.jar}"/>
251
        <pathelement location="${ooxml.xmlbeans26.jar}"/>
256
        <pathelement location="build/ooxml-xsds-lite"/> <!-- instead of ooxml-xsds.jar use the filtered classes-->
252
        <pathelement location="build/ooxml-xsds-lite"/> <!-- instead of ooxml-xsds.jar use the filtered classes-->
257
        <path refid="main.classpath"/>
253
        <path refid="main.classpath"/>
Lines 429-435 Link Here
429
        <condition property="ooxml.jars.present">
425
        <condition property="ooxml.jars.present">
430
            <or>
426
            <or>
431
                <and>
427
                <and>
432
                    <available file="${ooxml.dom4j.jar}"/>
433
                    <available file="${ooxml.xmlbeans23.jar}"/>
428
                    <available file="${ooxml.xmlbeans23.jar}"/>
434
                    <available file="${ooxml.xmlbeans26.jar}"/>
429
                    <available file="${ooxml.xmlbeans26.jar}"/>
435
                    <available file="${ooxml.xsds.jar}"/>
430
                    <available file="${ooxml.xsds.jar}"/>
Lines 441-450 Link Here
441
    <target name="fetch-ooxml-jars" depends="check-ooxml-jars" unless="ooxml.jars.present">
436
    <target name="fetch-ooxml-jars" depends="check-ooxml-jars" unless="ooxml.jars.present">
442
        <mkdir dir="${ooxml.lib}"/>
437
        <mkdir dir="${ooxml.lib}"/>
443
        <antcall target="downloadfile">
438
        <antcall target="downloadfile">
444
            <param name="sourcefile" value="${ooxml.dom4j.url}"/>
445
            <param name="destfile" value="${ooxml.dom4j.jar}"/>
446
        </antcall>
447
        <antcall target="downloadfile">
448
            <param name="sourcefile" value="${ooxml.xmlbeans23.url}"/>
439
            <param name="sourcefile" value="${ooxml.xmlbeans23.url}"/>
449
            <param name="destfile" value="${ooxml.xmlbeans23.jar}"/>
440
            <param name="destfile" value="${ooxml.xmlbeans23.jar}"/>
450
        </antcall>
441
        </antcall>
Lines 1288-1294 Link Here
1288
              <include name="log4j-*.jar"/>
1279
              <include name="log4j-*.jar"/>
1289
            </zipfileset>
1280
            </zipfileset>
1290
            <zipfileset dir="${ooxml.lib}" prefix="${zipdir}/ooxml-lib">
1281
            <zipfileset dir="${ooxml.lib}" prefix="${zipdir}/ooxml-lib">
1291
              <include name="dom4j-*.jar"/>
1292
              <include name="xmlbeans-2.6*.jar"/>
1282
              <include name="xmlbeans-2.6*.jar"/>
1293
            </zipfileset>
1283
            </zipfileset>
1294
            <zipfileset dir="${dist.dir}" prefix="${zipdir}">
1284
            <zipfileset dir="${dist.dir}" prefix="${zipdir}">
Lines 1316-1322 Link Here
1316
              <include name="log4j-*.jar"/>
1306
              <include name="log4j-*.jar"/>
1317
            </zipfileset>
1307
            </zipfileset>
1318
            <tarfileset dir="${ooxml.lib}" prefix="${zipdir}/ooxml-lib">
1308
            <tarfileset dir="${ooxml.lib}" prefix="${zipdir}/ooxml-lib">
1319
              <include name="dom4j-*.jar"/>
1320
              <include name="xmlbeans-2.6*.jar"/>
1309
              <include name="xmlbeans-2.6*.jar"/>
1321
            </tarfileset>
1310
            </tarfileset>
1322
            <tarfileset dir="${build.site}" prefix="${zipdir}/docs"/>
1311
            <tarfileset dir="${build.site}" prefix="${zipdir}/docs"/>
Lines 1449-1455 Link Here
1449
			<auxClasspath path="ooxml-lib/ooxml-schemas-1.1.jar" />
1438
			<auxClasspath path="ooxml-lib/ooxml-schemas-1.1.jar" />
1450
			<auxClasspath path="ooxml-lib/ooxml-encryption-1.1.jar" />
1439
			<auxClasspath path="ooxml-lib/ooxml-encryption-1.1.jar" />
1451
			<auxClasspath path="ooxml-lib/xmlbeans-2.6.0.jar" />
1440
			<auxClasspath path="ooxml-lib/xmlbeans-2.6.0.jar" />
1452
			<auxClasspath path="ooxml-lib/dom4j-1.6.1.jar" />
1453
			<auxClasspath path="lib/commons-codec-1.9.jar" />
1441
			<auxClasspath path="lib/commons-codec-1.9.jar" />
1454
			<auxClasspath path="lib/commons-logging-1.1.3.jar" />
1442
			<auxClasspath path="lib/commons-logging-1.1.3.jar" />
1455
			<auxClasspath path="lib/junit-4.11.jar" />
1443
			<auxClasspath path="lib/junit-4.11.jar" />
(-)src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java (-43 / +33 lines)
Lines 27-33 Link Here
27
import java.lang.reflect.Field;
27
import java.lang.reflect.Field;
28
import java.net.URI;
28
import java.net.URI;
29
import java.util.HashMap;
29
import java.util.HashMap;
30
import java.util.Iterator;
31
import java.util.List;
30
import java.util.List;
32
import java.util.TreeMap;
31
import java.util.TreeMap;
33
import java.util.regex.Pattern;
32
import java.util.regex.Pattern;
Lines 40-54 Link Here
40
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
39
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
41
import org.apache.poi.openxml4j.opc.internal.FileHelper;
40
import org.apache.poi.openxml4j.opc.internal.FileHelper;
42
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
41
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
43
import org.apache.poi.util.POILogFactory;
42
import org.apache.poi.util.*;
44
import org.apache.poi.util.POILogger;
43
import org.w3c.dom.Document;
45
import org.apache.poi.util.SAXHelper;
44
import org.w3c.dom.Element;
46
import org.apache.poi.util.TempFile;
45
import org.w3c.dom.NodeList;
47
import org.dom4j.Document;
48
import org.dom4j.DocumentHelper;
49
import org.dom4j.Element;
50
import org.dom4j.Namespace;
51
import org.dom4j.QName;
52
46
53
public final class TestPackage extends TestCase {
47
public final class TestPackage extends TestCase {
54
    private static final POILogger logger = POILogFactory.getLogger(TestPackage.class);
48
    private static final POILogger logger = POILogFactory.getLogger(TestPackage.class);
Lines 127-144 Link Here
127
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
121
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
128
122
129
        Document doc = DocumentHelper.createDocument();
123
        Document doc = DocumentHelper.createDocument();
130
        Namespace nsWordprocessinML = new Namespace("w",
124
        Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document");
131
                "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
125
        doc.appendChild(elDocument);
132
        Element elDocument = doc.addElement(new QName("document",
126
        Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body");
133
                nsWordprocessinML));
127
        elDocument.appendChild(elBody);
134
        Element elBody = elDocument.addElement(new QName("body",
128
        Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p");
135
                nsWordprocessinML));
129
        elBody.appendChild(elParagraph);
136
        Element elParagraph = elBody.addElement(new QName("p",
130
        Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r");
137
                nsWordprocessinML));
131
        elParagraph.appendChild(elRun);
138
        Element elRun = elParagraph
132
        Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t");
139
                .addElement(new QName("r", nsWordprocessinML));
133
        elRun.appendChild(elText);
140
        Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
134
        elText.setTextContent("Hello Open XML !");
141
        elText.setText("Hello Open XML !");
142
135
143
        StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
136
        StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
144
        pkg.close();
137
        pkg.close();
Lines 223-237 Link Here
223
216
224
        Document xmlRelationshipsDoc = SAXHelper.readSAXDocument(relPart.getInputStream());
217
        Document xmlRelationshipsDoc = SAXHelper.readSAXDocument(relPart.getInputStream());
225
218
226
        Element root = xmlRelationshipsDoc.getRootElement();
219
        Element root = xmlRelationshipsDoc.getDocumentElement();
227
        for (Iterator i = root
220
        NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME);
228
                .elementIterator(PackageRelationship.RELATIONSHIP_TAG_NAME); i
221
        int nodeCount = nodeList.getLength();
229
                .hasNext();) {
222
        for (int i = 0; i < nodeCount; i++) {
230
            Element element = (Element) i.next();
223
            Element element = (Element) nodeList.item(i);
231
            String value = element.attribute(
224
            String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
232
                    PackageRelationship.TARGET_ATTRIBUTE_NAME)
225
            assertTrue("Root target must not start with a leading slash ('/'): " + value, value.charAt(0) != '/');
233
                    .getValue();
234
            assertTrue("Root target must not start with a leadng slash ('/'): " + value, value.charAt(0) != '/');
235
        }
226
        }
236
227
237
    }
228
    }
Lines 268-285 Link Here
268
259
269
		// Create a content
260
		// Create a content
270
		Document doc = DocumentHelper.createDocument();
261
		Document doc = DocumentHelper.createDocument();
271
		Namespace nsWordprocessinML = new Namespace("w",
262
        Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document");
272
				"http://schemas.openxmlformats.org/wordprocessingml/2006/main");
263
        doc.appendChild(elDocument);
273
		Element elDocument = doc.addElement(new QName("document",
264
        Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body");
274
				nsWordprocessinML));
265
        elDocument.appendChild(elBody);
275
		Element elBody = elDocument.addElement(new QName("body",
266
        Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p");
276
				nsWordprocessinML));
267
        elBody.appendChild(elParagraph);
277
		Element elParagraph = elBody.addElement(new QName("p",
268
        Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r");
278
				nsWordprocessinML));
269
        elParagraph.appendChild(elRun);
279
		Element elRun = elParagraph
270
        Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t");
280
				.addElement(new QName("r", nsWordprocessinML));
271
        elRun.appendChild(elText);
281
		Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
272
        elText.setTextContent("Hello Open XML !");
282
		elText.setText("Hello Open XML !");
283
273
284
		StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
274
		StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
285
275
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/Configuration.java (-1 / +1 lines)
Lines 21-27 Link Here
21
21
22
/**
22
/**
23
 * Storage class for configuration storage parameters.
23
 * Storage class for configuration storage parameters.
24
 * TODO xml syntax checking is no longer done with DOM4j parser -> remove the schema or do it ?
24
 * TODO xml syntax checking is not done with JAXP by default -> remove the schema or do it ?
25
 *
25
 *
26
 * @author CDubettier, Julen Chable
26
 * @author CDubettier, Julen Chable
27
 * @version 1.0
27
 * @version 1.0
(-)src/ooxml/java/org/apache/poi/util/SAXHelper.java (-25 / +39 lines)
Lines 23-32 Link Here
23
import java.lang.reflect.Method;
23
import java.lang.reflect.Method;
24
24
25
import javax.xml.XMLConstants;
25
import javax.xml.XMLConstants;
26
import javax.xml.parsers.DocumentBuilder;
27
import javax.xml.parsers.DocumentBuilderFactory;
28
import javax.xml.parsers.ParserConfigurationException;
26
29
27
import org.dom4j.Document;
30
import org.w3c.dom.Document;
28
import org.dom4j.DocumentException;
29
import org.dom4j.io.SAXReader;
30
import org.xml.sax.EntityResolver;
31
import org.xml.sax.EntityResolver;
31
import org.xml.sax.InputSource;
32
import org.xml.sax.InputSource;
32
import org.xml.sax.SAXException;
33
import org.xml.sax.SAXException;
Lines 37-67 Link Here
37
 */
38
 */
38
public final class SAXHelper {
39
public final class SAXHelper {
39
    private static POILogger logger = POILogFactory.getLogger(SAXHelper.class);
40
    private static POILogger logger = POILogFactory.getLogger(SAXHelper.class);
40
            
41
41
    /**
42
    private static final EntityResolver IGNORING_ENTITY_RESOLVER = new EntityResolver() {
42
     * Creates a new SAX Reader, with sensible defaults
43
        @Override
43
     */
44
    public static SAXReader getSAXReader() {
45
        SAXReader xmlReader = new SAXReader();
46
        xmlReader.setValidation(false);
47
        xmlReader.setEntityResolver(new EntityResolver() {
48
            public InputSource resolveEntity(String publicId, String systemId)
44
        public InputSource resolveEntity(String publicId, String systemId)
49
                    throws SAXException, IOException {
45
                throws SAXException, IOException {
50
                return new InputSource(new StringReader(""));
46
            return new InputSource(new StringReader(""));
51
            }
47
        }
52
        });
48
    };
53
        trySetSAXFeature(xmlReader, XMLConstants.FEATURE_SECURE_PROCESSING, true);
49
54
        trySetXercesSecurityManager(xmlReader);
50
    private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
55
        return xmlReader;
51
    static {
52
        documentBuilderFactory.setNamespaceAware(true);
53
        documentBuilderFactory.setValidating(false);
54
        trySetSAXFeature(documentBuilderFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
55
        trySetXercesSecurityManager(documentBuilderFactory);
56
    }
56
    }
57
    private static void trySetSAXFeature(SAXReader xmlReader, String feature, boolean enabled) {
57
58
    /**
59
     * Creates a new document builder, with sensible defaults
60
     */
61
    public static DocumentBuilder getDocumentBuilder() {
58
        try {
62
        try {
59
            xmlReader.setFeature(feature, enabled);
63
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
64
            documentBuilder.setEntityResolver(IGNORING_ENTITY_RESOLVER);
65
            return documentBuilder;
66
        } catch (ParserConfigurationException e) {
67
            throw new IllegalStateException("cannot create a DocumentBuilder", e);
68
        }
69
    }
70
71
    private static void trySetSAXFeature(DocumentBuilderFactory documentBuilderFactory, String feature, boolean enabled) {
72
        try {
73
            documentBuilderFactory.setFeature(feature, enabled);
60
        } catch (Exception e) {
74
        } catch (Exception e) {
61
            logger.log(POILogger.INFO, "SAX Feature unsupported", feature, e);
75
            logger.log(POILogger.INFO, "SAX Feature unsupported", feature, e);
62
        }
76
        }
63
    }
77
    }
64
    private static void trySetXercesSecurityManager(SAXReader xmlReader) {
78
    private static void trySetXercesSecurityManager(DocumentBuilderFactory documentBuilderFactory) {
65
        // Try built-in JVM one first, standalone if not
79
        // Try built-in JVM one first, standalone if not
66
        for (String securityManagerClassName : new String[] {
80
        for (String securityManagerClassName : new String[] {
67
                "com.sun.org.apache.xerces.internal.util.SecurityManager",
81
                "com.sun.org.apache.xerces.internal.util.SecurityManager",
Lines 71-77 Link Here
71
                Object mgr = Class.forName(securityManagerClassName).newInstance();
85
                Object mgr = Class.forName(securityManagerClassName).newInstance();
72
                Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE);
86
                Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE);
73
                setLimit.invoke(mgr, 4096);
87
                setLimit.invoke(mgr, 4096);
74
                xmlReader.setProperty("http://apache.org/xml/properties/security-manager", mgr);
88
                documentBuilderFactory.setAttribute("http://apache.org/xml/properties/security-manager", mgr);
75
                // Stop once one can be setup without error
89
                // Stop once one can be setup without error
76
                return;
90
                return;
77
            } catch (Exception e) {
91
            } catch (Exception e) {
Lines 86-92 Link Here
86
     * @param inp Stream to read the XML data from
100
     * @param inp Stream to read the XML data from
87
     * @return the SAX processed Document 
101
     * @return the SAX processed Document 
88
     */
102
     */
89
    public static Document readSAXDocument(InputStream inp) throws DocumentException {
103
    public static Document readSAXDocument(InputStream inp) throws IOException, SAXException {
90
        return getSAXReader().read(inp);
104
        return getDocumentBuilder().parse(inp);
91
    }
105
    }
92
}
106
}
(-).classpath (-1 lines)
Lines 19-25 Link Here
19
	<classpathentry kind="lib" path="lib/commons-codec-1.9.jar"/>
19
	<classpathentry kind="lib" path="lib/commons-codec-1.9.jar"/>
20
	<classpathentry kind="lib" path="lib/commons-logging-1.1.3.jar"/>
20
	<classpathentry kind="lib" path="lib/commons-logging-1.1.3.jar"/>
21
	<classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
21
	<classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
22
	<classpathentry kind="lib" path="ooxml-lib/dom4j-1.6.1.jar"/>
23
	<classpathentry kind="lib" path="ooxml-lib/xmlbeans-2.6.0.jar"/>
22
	<classpathentry kind="lib" path="ooxml-lib/xmlbeans-2.6.0.jar"/>
24
	<classpathentry kind="lib" path="lib/hamcrest-core-1.3.jar"/>
23
	<classpathentry kind="lib" path="lib/hamcrest-core-1.3.jar"/>
25
	<classpathentry kind="lib" path="lib/junit-4.11.jar"/>
24
	<classpathentry kind="lib" path="lib/junit-4.11.jar"/>
(-)src/ooxml/java/org/apache/poi/util/DocumentHelper.java (+42 lines)
Line 0 Link Here
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
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
package org.apache.poi.util;
19
20
import org.w3c.dom.Document;
21
22
import javax.xml.parsers.DocumentBuilder;
23
import javax.xml.parsers.DocumentBuilderFactory;
24
import javax.xml.parsers.ParserConfigurationException;
25
26
public class DocumentHelper {
27
28
    // should only be used without synchronization for creating new empty documents
29
    private static final DocumentBuilder newDocumentBuilder;
30
    static {
31
        try {
32
            newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
33
        } catch (ParserConfigurationException e) {
34
            throw new IllegalStateException("cannot create a DocumentBuilder", e);
35
        }
36
    }
37
38
    public static Document createDocument() {
39
        return newDocumentBuilder.newDocument();
40
    }
41
42
}
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java (-1 / +1 lines)
Lines 30-36 Link Here
30
import org.apache.poi.openxml4j.opc.StreamHelper;
30
import org.apache.poi.openxml4j.opc.StreamHelper;
31
import org.apache.poi.util.POILogFactory;
31
import org.apache.poi.util.POILogFactory;
32
import org.apache.poi.util.POILogger;
32
import org.apache.poi.util.POILogger;
33
import org.dom4j.Document;
33
import org.w3c.dom.Document;
34
34
35
/**
35
/**
36
 * Zip implementation of the ContentTypeManager.
36
 * Zip implementation of the ContentTypeManager.
(-)src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java (-2 lines)
Lines 48-55 Link Here
48
48
49
	public final static String NAMESPACE_DCTERMS_URI = "http://purl.org/dc/terms/";
49
	public final static String NAMESPACE_DCTERMS_URI = "http://purl.org/dc/terms/";
50
50
51
	public final static String NAMESPACE_XSI_URI = "http://www.w3.org/2001/XMLSchema-instance";
52
53
	/**
51
	/**
54
	 * Constructor.
52
	 * Constructor.
55
	 *
53
	 *
(-)src/ooxml/testcases/org/apache/poi/util/TestDocumentBuilders.java (+96 lines)
Line 0 Link Here
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
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
package org.apache.poi.util;
18
19
import junit.framework.TestCase;
20
import org.apache.commons.codec.Charsets;
21
import org.w3c.dom.Document;
22
23
import javax.xml.transform.Transformer;
24
import javax.xml.transform.TransformerFactory;
25
import javax.xml.transform.dom.DOMSource;
26
import javax.xml.transform.stream.StreamResult;
27
import java.io.*;
28
import java.util.ArrayList;
29
import java.util.List;
30
import java.util.concurrent.*;
31
32
public class TestDocumentBuilders extends TestCase {
33
34
    private static final int THREADS = 1000;
35
    private static final int RUNS_PER_THREAD = 10;
36
    private static final int TIMEOUT_SECONDS = 10;
37
38
    private void performTest(final Callable<?> callable) {
39
        List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(THREADS);
40
        for (int thread = 0; thread < THREADS; thread++) {
41
            tasks.add(new Callable<Object>() {
42
                public Object call() throws Exception {
43
                    for (int run = 0; run < RUNS_PER_THREAD; run++) {
44
                        callable.call();
45
                    }
46
                    return null;
47
                }
48
            });
49
        }
50
        ExecutorService exec = Executors.newFixedThreadPool(THREADS);
51
        try {
52
            List<Future<Object>> results = exec.invokeAll(tasks, TIMEOUT_SECONDS, TimeUnit.SECONDS);
53
            for (Future<Object> result : results) {
54
                result.get();
55
            }
56
        } catch (Exception e) {
57
            if (e instanceof RuntimeException)
58
                throw (RuntimeException)e;
59
            if (e.getCause() instanceof Error)
60
                throw (Error)e.getCause();
61
            else
62
                throw new RuntimeException(e);
63
        } finally {
64
            exec.shutdown();
65
        }
66
    }
67
68
    public void testDocumentHelper() {
69
        performTest(new Callable<Document>() {
70
            public Document call() {
71
                return DocumentHelper.createDocument();
72
            }
73
        });
74
    }
75
76
    public void testSAXHelper() {
77
        final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rootElement>Text Content</rootElement>";
78
        final byte[] xmlBytes = xml.getBytes(Charsets.UTF_8);
79
        performTest(new Callable<Object>() {
80
            public Object call() {
81
                InputStream inputStream = new ByteArrayInputStream(xmlBytes);
82
                StringWriter writer = new StringWriter();
83
                try {
84
                    Document result = SAXHelper.readSAXDocument(inputStream);
85
                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
86
                    transformer.transform(new DOMSource(result), new StreamResult(writer));
87
                } catch (Exception e) {
88
                    throw new RuntimeException(e);
89
                }
90
                assertEquals("parsed xml should be equal to source xml", xml, writer.toString());
91
                return null;
92
            }
93
        });
94
    }
95
96
}
(-)legal/LICENSE (-44 lines)
Lines 229-278 Link Here
229
    [5] http://www.ecma-international.org/publications/files/ECMA-ST/Ecma%20PATENT/Patent%20statements%20ok/ECMA-376%20Adobe%20Patent%20Declaration.pdf
229
    [5] http://www.ecma-international.org/publications/files/ECMA-ST/Ecma%20PATENT/Patent%20statements%20ok/ECMA-376%20Adobe%20Patent%20Declaration.pdf
230
230
231
231
232
DOM4J library (dom4j-1.6.1.jar)
233
234
    Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
235
236
    Redistribution and use of this software and associated documentation
237
    ("Software"), with or without modification, are permitted provided
238
    that the following conditions are met:
239
240
    1. Redistributions of source code must retain copyright
241
       statements and notices.  Redistributions must also contain a
242
       copy of this document.
243
244
    2. Redistributions in binary form must reproduce the
245
       above copyright notice, this list of conditions and the
246
       following disclaimer in the documentation and/or other
247
       materials provided with the distribution.
248
249
    3. The name "DOM4J" must not be used to endorse or promote
250
       products derived from this Software without prior written
251
       permission of MetaStuff, Ltd.  For written permission,
252
       please contact dom4j-info@metastuff.com.
253
254
    4. Products derived from this Software may not be called "DOM4J"
255
       nor may "DOM4J" appear in their names without prior written
256
       permission of MetaStuff, Ltd. DOM4J is a registered
257
       trademark of MetaStuff, Ltd.
258
259
    5. Due credit should be given to the DOM4J Project - 
260
       http://www.dom4j.org
261
 
262
    THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
263
    ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
264
    NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
265
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
266
    METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
267
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
268
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
269
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
270
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
271
    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
272
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
273
    OF THE POSSIBILITY OF SUCH DAMAGE.
274
275
276
JUnit test library (junit-4.11.jar)
232
JUnit test library (junit-4.11.jar)
277
233
278
    Common Public License - v 1.0
234
    Common Public License - v 1.0

Return to bug 56814