some changes to allow shared string table to be subclassed

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1822404 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
PJ Fanning 2018-01-27 13:30:52 +00:00
parent 47a21a80d4
commit 42ffb63210
3 changed files with 133 additions and 102 deletions

View File

@ -20,6 +20,7 @@ package org.apache.poi.xssf.model;
import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@ -61,7 +62,7 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.SstDocument;
* properties, and phonetic properties (for East Asian languages). * properties, and phonetic properties (for East Asian languages).
* </p> * </p>
*/ */
public class SharedStringsTable extends POIXMLDocumentPart { public class SharedStringsTable extends POIXMLDocumentPart implements Closeable {
/** /**
* Array of individual string items in the Shared String table. * Array of individual string items in the Shared String table.
@ -77,22 +78,22 @@ public class SharedStringsTable extends POIXMLDocumentPart {
* An integer representing the total count of strings in the workbook. This count does not * An integer representing the total count of strings in the workbook. This count does not
* include any numbers, it counts only the total of text strings in the workbook. * include any numbers, it counts only the total of text strings in the workbook.
*/ */
private int count; protected int count;
/** /**
* An integer representing the total count of unique strings in the Shared String Table. * An integer representing the total count of unique strings in the Shared String Table.
* A string is unique even if it is a copy of another string, but has different formatting applied * A string is unique even if it is a copy of another string, but has different formatting applied
* at the character level. * at the character level.
*/ */
private int uniqueCount; protected int uniqueCount;
private SstDocument _sstDoc; private SstDocument _sstDoc;
private static final XmlOptions options = new XmlOptions(); private static final XmlOptions options = new XmlOptions();
static { static {
options.put( XmlOptions.SAVE_INNER ); options.put( XmlOptions.SAVE_INNER );
options.put( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES ); options.put( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES );
options.put( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE ); options.put( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE );
options.setSaveImplicitNamespaces(Collections.singletonMap("", NS_SPREADSHEETML)); options.setSaveImplicitNamespaces(Collections.singletonMap("", NS_SPREADSHEETML));
} }
@ -125,7 +126,7 @@ public class SharedStringsTable extends POIXMLDocumentPart {
uniqueCount = (int)sst.getUniqueCount(); uniqueCount = (int)sst.getUniqueCount();
//noinspection deprecation //noinspection deprecation
for (CTRst st : sst.getSiArray()) { for (CTRst st : sst.getSiArray()) {
stmap.put(getKey(st), cnt); stmap.put(xmlText(st), cnt);
strings.add(st); strings.add(st);
cnt++; cnt++;
} }
@ -134,7 +135,7 @@ public class SharedStringsTable extends POIXMLDocumentPart {
} }
} }
private String getKey(CTRst st) { protected String xmlText(CTRst st) {
return st.xmlText(options); return st.xmlText(options);
} }
@ -195,7 +196,7 @@ public class SharedStringsTable extends POIXMLDocumentPart {
*/ */
@Removal(version = "4.2") //make private in 4.2 @Removal(version = "4.2") //make private in 4.2
public int addEntry(CTRst st) { public int addEntry(CTRst st) {
String s = getKey(st); String s = xmlText(st);
count++; count++;
if (stmap.containsKey(s)) { if (stmap.containsKey(s)) {
return stmap.get(s); return stmap.get(s);
@ -282,4 +283,16 @@ public class SharedStringsTable extends POIXMLDocumentPart {
writeTo(out); writeTo(out);
} }
} }
/**
* Close any open resources, like temp files. This method is called by <code>XSSFWorkbook#close()</code>.
* <p>
* This implementation is empty but subclasses may need to implement some logic.
* </p>
*
* @since 4.0.0
* @throws IOException if an error occurs while closing.
*/
@Override
public void close() throws IOException {}
} }

View File

@ -27,8 +27,8 @@ import org.apache.poi.POIXMLRelation;
/** /**
* Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type
*/ */
public final class XSSFFactory extends POIXMLFactory { public class XSSFFactory extends POIXMLFactory {
private XSSFFactory() { protected XSSFFactory() {
} }
private static final XSSFFactory inst = new XSSFFactory(); private static final XSSFFactory inst = new XSSFFactory();
@ -50,8 +50,8 @@ public final class XSSFFactory extends POIXMLFactory {
*/ */
@Override @Override
protected POIXMLDocumentPart createDocumentPart protected POIXMLDocumentPart createDocumentPart
(Class<? extends POIXMLDocumentPart> cls, Class<?>[] classes, Object[] values) (Class<? extends POIXMLDocumentPart> cls, Class<?>[] classes, Object[] values)
throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(classes); Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(classes);
return constructor.newInstance(values); return constructor.newInstance(values);
} }

View File

@ -127,7 +127,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* @deprecated POI 3.17 beta 1 * @deprecated POI 3.17 beta 1
* @see Units#DEFAULT_CHARACTER_WIDTH * @see Units#DEFAULT_CHARACTER_WIDTH
*/ */
@Removal(version="3.19") @Removal(version="4.1")
public static final float DEFAULT_CHARACTER_WIDTH = Units.DEFAULT_CHARACTER_WIDTH; public static final float DEFAULT_CHARACTER_WIDTH = Units.DEFAULT_CHARACTER_WIDTH;
/** /**
@ -236,6 +236,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
private List<XSSFPivotTable> pivotTables; private List<XSSFPivotTable> pivotTables;
private List<CTPivotCache> pivotCaches; private List<CTPivotCache> pivotCaches;
private final XSSFFactory xssfFactory;
/** /**
* Create a new SpreadsheetML workbook. * Create a new SpreadsheetML workbook.
@ -244,12 +245,22 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
this(XSSFWorkbookType.XLSX); this(XSSFWorkbookType.XLSX);
} }
@Internal
public XSSFWorkbook(XSSFFactory factory) {
this(XSSFWorkbookType.XLSX, factory);
}
/** /**
* Create a new SpreadsheetML workbook. * Create a new SpreadsheetML workbook.
* @param workbookType The type of workbook to make (.xlsx or .xlsm). * @param workbookType The type of workbook to make (.xlsx or .xlsm).
*/ */
public XSSFWorkbook(XSSFWorkbookType workbookType) { public XSSFWorkbook(XSSFWorkbookType workbookType) {
this(workbookType, null);
}
private XSSFWorkbook(XSSFWorkbookType workbookType, XSSFFactory factory) {
super(newPackage(workbookType)); super(newPackage(workbookType));
this.xssfFactory = (factory == null) ? XSSFFactory.getInstance() : factory;
onWorkbookCreate(); onWorkbookCreate();
} }
@ -268,11 +279,12 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/ */
public XSSFWorkbook(OPCPackage pkg) throws IOException { public XSSFWorkbook(OPCPackage pkg) throws IOException {
super(pkg); super(pkg);
this.xssfFactory = XSSFFactory.getInstance();
beforeDocumentRead(); beforeDocumentRead();
// Build a tree of POIXMLDocumentParts, this workbook being the root // Build a tree of POIXMLDocumentParts, this workbook being the root
load(XSSFFactory.getInstance()); load(this.xssfFactory);
// some broken Workbooks miss this... // some broken Workbooks miss this...
setBookViewsIfMissing(); setBookViewsIfMissing();
@ -383,7 +395,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
if (packageReadOnly) { if (packageReadOnly) {
stylesSource = new StylesTable(); stylesSource = new StylesTable();
} else { } else {
stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, XSSFFactory.getInstance()); stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, this.xssfFactory);
} }
} }
stylesSource.setWorkbook(this); stylesSource.setWorkbook(this);
@ -394,7 +406,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
if (packageReadOnly) { if (packageReadOnly) {
sharedStringSource = new SharedStringsTable(); sharedStringSource = new SharedStringsTable();
} else { } else {
sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance()); sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, this.xssfFactory);
} }
} }
@ -458,8 +470,8 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties(); POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR); expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance()); sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, this.xssfFactory);
stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, XSSFFactory.getInstance()); stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, this.xssfFactory);
stylesSource.setWorkbook(this); stylesSource.setWorkbook(this);
namedRanges = new ArrayList<>(); namedRanges = new ArrayList<>();
@ -525,7 +537,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
@Override @Override
public int addPicture(byte[] pictureData, int format) { public int addPicture(byte[] pictureData, int format) {
int imageNumber = getAllPictures().size() + 1; int imageNumber = getAllPictures().size() + 1;
XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true).getDocumentPart(); XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], this.xssfFactory, imageNumber, true).getDocumentPart();
try (OutputStream out = img.getPackagePart().getOutputStream()) { try (OutputStream out = img.getPackagePart().getOutputStream()) {
out.write(pictureData); out.write(pictureData);
} catch (IOException e){ } catch (IOException e){
@ -552,7 +564,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/ */
public int addPicture(InputStream is, int format) throws IOException { public int addPicture(InputStream is, int format) throws IOException {
int imageNumber = getAllPictures().size() + 1; int imageNumber = getAllPictures().size() + 1;
XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true).getDocumentPart(); XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], this.xssfFactory, imageNumber, true).getDocumentPart();
try (OutputStream out = img.getPackagePart().getOutputStream()) { try (OutputStream out = img.getPackagePart().getOutputStream()) {
IOUtils.copy(is, out); IOUtils.copy(is, out);
} }
@ -574,6 +586,12 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
return cloneSheet(sheetNum, null); return cloneSheet(sheetNum, null);
} }
@Override
public void close() throws IOException {
super.close();
sharedStringSource.close();
}
/** /**
* Create an XSSFSheet from an existing sheet in the XSSFWorkbook. * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
* The cloned sheet is a deep copy of the original but with a new given * The cloned sheet is a deep copy of the original but with a new given
@ -618,7 +636,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
for(PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) { for(PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) {
if (pr.getTargetMode() == TargetMode.EXTERNAL) { if (pr.getTargetMode() == TargetMode.EXTERNAL) {
clonedSheet.getPackagePart().addExternalRelationship clonedSheet.getPackagePart().addExternalRelationship
(pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId()); (pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId());
} }
} }
} catch (InvalidFormatException e) { } catch (InvalidFormatException e) {
@ -675,7 +693,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
PackageRelationship rel = rp.getRelationship(); PackageRelationship rel = rp.getRelationship();
if (rel.getTargetMode() == TargetMode.EXTERNAL) { if (rel.getTargetMode() == TargetMode.EXTERNAL) {
target.getPackagePart().addRelationship( target.getPackagePart().addRelationship(
rel.getTargetURI(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId()); rel.getTargetURI(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId());
} else { } else {
XSSFRelation xssfRel = XSSFRelation.getInstance(rel.getRelationshipType()); XSSFRelation xssfRel = XSSFRelation.getInstance(rel.getRelationshipType());
if (xssfRel == null) { if (xssfRel == null) {
@ -876,7 +894,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
break; break;
} }
RelationPart rp = createRelationship(XSSFRelation.WORKSHEET, XSSFFactory.getInstance(), sheetNumber, false); RelationPart rp = createRelationship(XSSFRelation.WORKSHEET, this.xssfFactory, sheetNumber, false);
XSSFSheet wrapper = rp.getDocumentPart(); XSSFSheet wrapper = rp.getDocumentPart();
wrapper.sheet = sheet; wrapper.sheet = sheet;
sheet.setId(rp.getRelationship().getId()); sheet.setId(rp.getRelationship().getId());
@ -1445,7 +1463,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* @param index the index to validate * @param index the index to validate
* @throws IllegalArgumentException if the index is out of range (index * @throws IllegalArgumentException if the index is out of range (index
* &lt; 0 || index &gt;= getNumberOfSheets()). * &lt; 0 || index &gt;= getNumberOfSheets()).
*/ */
private void validateSheetIndex(int index) { private void validateSheetIndex(int index) {
int lastSheetIx = sheets.size() - 1; int lastSheetIx = sheets.size() - 1;
if (index < 0 || index > lastSheetIx) { if (index < 0 || index > lastSheetIx) {
@ -1855,7 +1873,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
} }
for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation())) { for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation())) {
embedds.add( sheet.getPackagePart().getRelatedPart(rel) ); embedds.add( sheet.getPackagePart().getRelatedPart(rel) );
} }
} }
return embedds; return embedds;
@ -2298,7 +2316,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
OPCPackage opc = getPackage(); OPCPackage opc = getPackage();
OutputStream outputStream; OutputStream outputStream;
if (!opc.containPart(ppName)) { if (!opc.containPart(ppName)) {
POIXMLDocumentPart relationship = createRelationship(XSSFRelation.VBA_MACROS, XSSFFactory.getInstance()); POIXMLDocumentPart relationship = createRelationship(XSSFRelation.VBA_MACROS, this.xssfFactory);
outputStream = relationship.getPackagePart().getOutputStream(); outputStream = relationship.getPackagePart().getOutputStream();
} else { } else {
PackagePart part = opc.getPart(ppName); PackagePart part = opc.getPart(ppName);
@ -2359,7 +2377,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
@Override @Override
public int addOlePackage(byte[] oleData, String label, String fileName, String command) public int addOlePackage(byte[] oleData, String label, String fileName, String command)
throws IOException { throws IOException {
// find an unused part name // find an unused part name
OPCPackage opc = getPackage(); OPCPackage opc = getPackage();
PackagePartName pnOLE; PackagePartName pnOLE;