cleanup of POIXMLDocument constructors and related sub-classes

git-svn-id: https://svn.apache.org/repos/asf/poi/branches/ooxml@706032 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Yegor Kozlov 2008-10-19 15:31:28 +00:00
parent 26ec85202e
commit 82a4bc8cb1
5 changed files with 108 additions and 85 deletions

View File

@ -28,7 +28,7 @@ import org.openxml4j.exceptions.OpenXML4JException;
import org.openxml4j.opc.*; import org.openxml4j.opc.*;
import org.openxml4j.opc.Package; import org.openxml4j.opc.Package;
public class POIXMLDocument extends POIXMLDocumentPart{ public abstract class POIXMLDocument extends POIXMLDocumentPart{
public static final String CORE_PROPERTIES_REL_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; public static final String CORE_PROPERTIES_REL_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
public static final String EXTENDED_PROPERTIES_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; public static final String EXTENDED_PROPERTIES_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
@ -43,33 +43,26 @@ public class POIXMLDocument extends POIXMLDocumentPart{
/** The OPC Package */ /** The OPC Package */
private Package pkg; private Package pkg;
/** The OPC core Package Part */
private PackagePart corePart;
/** /**
* The properties of the OPC package, opened as needed * The properties of the OPC package, opened as needed
*/ */
private POIXMLProperties properties; private POIXMLProperties properties;
/**
* The embedded OLE2 files in the OPC package
*/
protected List<PackagePart> embedds;
protected POIXMLDocument() { protected POIXMLDocument() {
super(null, null); super(null, null);
embedds = new LinkedList<PackagePart>(); try {
Package pkg = newPackage();
initialize(pkg);
} catch (IOException e){
throw new POIXMLException(e);
}
} }
protected POIXMLDocument(Package pkg) throws IOException { protected POIXMLDocument(Package pkg) throws IOException {
this(); super(null, null);
initialize(pkg); initialize(pkg);
} }
protected POIXMLDocument(String path) throws IOException {
this(openPackage(path));
}
/** /**
* Wrapper to open a package, returning an IOException * Wrapper to open a package, returning an IOException
* in the event of a problem. * in the event of a problem.
@ -83,7 +76,7 @@ public class POIXMLDocument extends POIXMLDocumentPart{
} }
} }
protected void initialize(Package pkg) throws IOException { private void initialize(Package pkg) throws IOException {
try { try {
this.pkg = pkg; this.pkg = pkg;
@ -91,10 +84,11 @@ public class POIXMLDocument extends POIXMLDocumentPart{
PackageRelationshipTypes.CORE_DOCUMENT).getRelationship(0); PackageRelationshipTypes.CORE_DOCUMENT).getRelationship(0);
// Get core part // Get core part
this.corePart = super.packagePart = this.pkg.getPart(coreDocRelationship); this.packagePart = this.pkg.getPart(coreDocRelationship);
this.packageRel = coreDocRelationship;
// Verify it's there // Verify it's there
if(corePart == null) { if(this.packagePart == null) {
throw new IllegalArgumentException("No core part found for this document! Nothing with " + coreDocRelationship.getRelationshipType() + " present as a relation."); throw new IllegalArgumentException("No core part found for this document! Nothing with " + coreDocRelationship.getRelationshipType() + " present as a relation.");
} }
} catch (OpenXML4JException e) { } catch (OpenXML4JException e) {
@ -102,12 +96,16 @@ public class POIXMLDocument extends POIXMLDocumentPart{
} }
} }
protected Package newPackage() throws IOException {
throw new POIXMLException("Must be overridden");
}
public Package getPackage() { public Package getPackage() {
return this.pkg; return this.pkg;
} }
protected PackagePart getCorePart() { protected PackagePart getCorePart() {
return this.corePart; return this.packagePart;
} }
/** /**
@ -128,7 +126,7 @@ public class POIXMLDocument extends POIXMLDocumentPart{
* @return The target part * @return The target part
* @throws InvalidFormatException * @throws InvalidFormatException
*/ */
public static PackagePart getTargetPart(Package pkg, PackageRelationship rel) throws InvalidFormatException { protected static PackagePart getTargetPart(Package pkg, PackageRelationship rel) throws InvalidFormatException {
PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
PackagePart part = pkg.getPart(relName); PackagePart part = pkg.getPart(relName);
if (part == null) { if (part == null) {
@ -137,26 +135,6 @@ public class POIXMLDocument extends POIXMLDocumentPart{
return part; return part;
} }
/**
* Fetches the (single) PackagePart which is defined as
* the supplied relation content type of the base
* package/container, or null if none found.
* @param relationType The relation content type to search for
* @throws IllegalArgumentException If we find more than one part of that type
*/
protected PackagePart getSinglePartByRelationType(String relationType) throws IllegalArgumentException, OpenXML4JException {
PackageRelationshipCollection rels =
pkg.getRelationshipsByType(relationType);
if(rels.size() == 0) {
return null;
}
if(rels.size() > 1) {
throw new IllegalArgumentException("Found " + rels.size() + " relations for the type " + relationType + ", should only ever be one!");
}
PackageRelationship rel = rels.getRelationship(0);
return getTargetPart(rel);
}
/** /**
* Retrieves all the PackageParts which are defined as * Retrieves all the PackageParts which are defined as
* relationships of the base document with the * relationships of the base document with the
@ -164,7 +142,7 @@ public class POIXMLDocument extends POIXMLDocumentPart{
*/ */
protected PackagePart[] getRelatedByType(String contentType) throws InvalidFormatException { protected PackagePart[] getRelatedByType(String contentType) throws InvalidFormatException {
PackageRelationshipCollection partsC = PackageRelationshipCollection partsC =
getCorePart().getRelationshipsByType(contentType); getPackagePart().getRelationshipsByType(contentType);
PackagePart[] parts = new PackagePart[partsC.size()]; PackagePart[] parts = new PackagePart[partsC.size()];
int count = 0; int count = 0;
@ -224,8 +202,6 @@ public class POIXMLDocument extends POIXMLDocumentPart{
/** /**
* Get the document's embedded files. * Get the document's embedded files.
*/ */
public List<PackagePart> getAllEmbedds() throws OpenXML4JException public abstract List<PackagePart> getAllEmbedds() throws OpenXML4JException;
{
return embedds;
}
} }

View File

@ -213,14 +213,14 @@ public class POIXMLDocumentPart {
/** /**
* Fired when a new package part is created * Fired when a new package part is created
*/ */
public void onDocumentCreate(){ protected void onDocumentCreate(){
} }
/** /**
* Fired when a package part is read * Fired when a package part is read
*/ */
public void onDocumentRead(){ protected void onDocumentRead(){
} }
} }

View File

@ -17,6 +17,8 @@
package org.apache.poi.xslf; package org.apache.poi.xslf;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import java.util.LinkedList;
import org.apache.poi.POIXMLDocument; import org.apache.poi.POIXMLDocument;
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlException;
@ -61,13 +63,18 @@ public class XSLFSlideShow extends POIXMLDocument {
public static final String COMMENT_RELATION_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; public static final String COMMENT_RELATION_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
private PresentationDocument presentationDoc; private PresentationDocument presentationDoc;
/**
* The embedded OLE2 files in the OPC package
*/
private List<PackagePart> embedds;
public XSLFSlideShow(Package container) throws OpenXML4JException, IOException, XmlException { public XSLFSlideShow(Package container) throws OpenXML4JException, IOException, XmlException {
super(container); super(container);
presentationDoc = presentationDoc =
PresentationDocument.Factory.parse(getCorePart().getInputStream()); PresentationDocument.Factory.parse(getCorePart().getInputStream());
embedds = new LinkedList<PackagePart>();
for (CTSlideIdListEntry ctSlide : getSlideReferences().getSldIdArray()) { for (CTSlideIdListEntry ctSlide : getSlideReferences().getSldIdArray()) {
PackagePart slidePart = PackagePart slidePart =
getTargetPart(getCorePart().getRelationship(ctSlide.getId2())); getTargetPart(getCorePart().getRelationship(ctSlide.getId2()));
@ -224,4 +231,12 @@ public class XSLFSlideShow extends POIXMLDocument {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }
/**
* Get the document's embedded files.
*/
public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
return embedds;
}
} }

View File

@ -38,6 +38,7 @@ import org.apache.poi.POIXMLException;
import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlOptions;
import org.openxml4j.exceptions.OpenXML4JException; import org.openxml4j.exceptions.OpenXML4JException;
import org.openxml4j.exceptions.InvalidFormatException;
import org.openxml4j.opc.*; import org.openxml4j.opc.*;
import org.openxml4j.opc.Package; import org.openxml4j.opc.Package;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*; import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
@ -98,16 +99,17 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
private static POILogger log = POILogFactory.getLogger(XSSFWorkbook.class); private static POILogger log = POILogFactory.getLogger(XSSFWorkbook.class);
/**
* The embedded OLE2 files in the OPC package
*/
private List<PackagePart> embedds;
/** /**
* Create a new SpreadsheetML workbook. * Create a new SpreadsheetML workbook.
*/ */
public XSSFWorkbook() { public XSSFWorkbook() {
super(); super();
try { onDocumentCreate();
newWorkbook();
}catch (Exception e){
throw new POIXMLException(e);
}
} }
/** /**
@ -126,37 +128,38 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
* @param pkg the OpenXML4J <code>Package</code> object. * @param pkg the OpenXML4J <code>Package</code> object.
*/ */
public XSSFWorkbook(Package pkg) throws IOException { public XSSFWorkbook(Package pkg) throws IOException {
super(); super(ensureWriteAccess(pkg));
onDocumentRead();
}
/**
* YK: current implementation of OpenXML4J is funny.
* Packages opened by Package.open(InputStream is) are read-only,
* there is no way to change or even save such an instance in a OutputStream.
* The workaround is to create a copy via a temp file
*/
private static Package ensureWriteAccess(Package pkg) throws IOException {
if(pkg.getPackageAccess() == PackageAccess.READ){ if(pkg.getPackageAccess() == PackageAccess.READ){
//YK: current implementation of OpenXML4J is funny. //YK: current implementation of OpenXML4J is funny.
//Packages opened by Package.open(InputStream is) are read-only,
//there is no way to change or even save such an instance in a OutputStream.
//The workaround is to create a copy via a temp file
try { try {
Package tmp = PackageHelper.clone(pkg); return PackageHelper.clone(pkg);
initialize(tmp);
} catch (OpenXML4JException e){ } catch (OpenXML4JException e){
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} else {
initialize(pkg);
} }
return pkg;
} }
/** /**
* Initialize this workbook from the specified Package * Initialize this workbook from the specified Package
*/ */
@Override @Override
protected void initialize(Package pkg) throws IOException { protected void onDocumentRead() {
super.initialize(pkg);
try { try {
//build the POIXMLDocumentPart tree, this workbook is the root //build the POIXMLDocumentPart tree, this workbook is the root
read(XSSFFactory.getInstance()); read(XSSFFactory.getInstance());
PackagePart corePart = getCorePart(); WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream());
WorkbookDocument doc = WorkbookDocument.Factory.parse(corePart.getInputStream());
this.workbook = doc.getWorkbook(); this.workbook = doc.getWorkbook();
HashMap<String, XSSFSheet> shIdMap = new HashMap<String, XSSFSheet>(); HashMap<String, XSSFSheet> shIdMap = new HashMap<String, XSSFSheet>();
@ -167,8 +170,10 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
shIdMap.put(p.getPackageRelationship().getId(), (XSSFSheet)p); shIdMap.put(p.getPackageRelationship().getId(), (XSSFSheet)p);
} }
} }
// Load individual sheets // Load individual sheets
sheets = new LinkedList<XSSFSheet>(); sheets = new LinkedList<XSSFSheet>();
embedds = new LinkedList<PackagePart>();
for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) { for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) {
String id = ctSheet.getId(); String id = ctSheet.getId();
XSSFSheet sh = shIdMap.get(id); XSSFSheet sh = shIdMap.get(id);
@ -215,22 +220,8 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
} }
} }
/** @Override
* Create a new SpreadsheetML OOXML package and setup the default minimal content protected void onDocumentCreate() {
*/
protected void newWorkbook() throws IOException, OpenXML4JException{
Package pkg = Package.create(PackageHelper.createTempFile());
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName());
// Create main part relationship
pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
// Create main document part
pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType());
pkg.getPackageProperties().setCreatorProperty("Apache POI");
super.initialize(pkg);
workbook = CTWorkbook.Factory.newInstance(); workbook = CTWorkbook.Factory.newInstance();
CTBookViews bvs = workbook.addNewBookViews(); CTBookViews bvs = workbook.addNewBookViews();
CTBookView bv = bvs.addNewWorkbookView(); CTBookView bv = bvs.addNewWorkbookView();
@ -242,6 +233,28 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
namedRanges = new LinkedList<XSSFName>(); namedRanges = new LinkedList<XSSFName>();
sheets = new LinkedList<XSSFSheet>(); sheets = new LinkedList<XSSFSheet>();
embedds = new LinkedList<PackagePart>();
}
/**
* Create a new SpreadsheetML package and setup the default minimal content
*/
protected Package newPackage() throws IOException {
try {
Package pkg = Package.create(PackageHelper.createTempFile());
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName());
// Create main part relationship
pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
// Create main document part
pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType());
pkg.getPackageProperties().setCreatorProperty("Apache POI");
return pkg;
} catch (InvalidFormatException e){
throw new POIXMLException(e);
}
} }
/** /**
@ -709,7 +722,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
* macro enabled workbook (.xlsm)? * macro enabled workbook (.xlsm)?
*/ */
public boolean isMacroEnabled() { public boolean isMacroEnabled() {
return getCorePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType()); return getPackagePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType());
} }
public void removeName(int index) { public void removeName(int index) {
@ -1154,4 +1167,11 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
CTWorkbookPr workbookPr = workbook.getWorkbookPr(); CTWorkbookPr workbookPr = workbook.getWorkbookPr();
return workbookPr != null && workbookPr.getDate1904(); return workbookPr != null && workbookPr.getDate1904();
} }
/**
* Get the document's embedded files.
*/
public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
return embedds;
}
} }

View File

@ -71,7 +71,11 @@ public class XWPFDocument extends POIXMLDocument {
protected List<XWPFHyperlink> hyperlinks; protected List<XWPFHyperlink> hyperlinks;
protected List<XWPFParagraph> paragraphs; protected List<XWPFParagraph> paragraphs;
protected List<XWPFTable> tables; protected List<XWPFTable> tables;
/**
* The embedded OLE2 files in the OPC package
*/
private List<PackagePart> embedds;
/** Handles the joy of different headers/footers for different pages */ /** Handles the joy of different headers/footers for different pages */
private XWPFHeaderFooterPolicy headerFooterPolicy; private XWPFHeaderFooterPolicy headerFooterPolicy;
@ -239,5 +243,13 @@ public class XWPFDocument extends POIXMLDocument {
{ {
return getCorePart().getRelationshipsByType(COMMENT_RELATION_TYPE); return getCorePart().getRelationshipsByType(COMMENT_RELATION_TYPE);
} }
/**
* Get the document's embedded files.
*/
public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
return embedds;
}
} }