diff --git a/build.xml b/build.xml
index 545a8d153..4392d39e1 100644
--- a/build.xml
+++ b/build.xml
@@ -1092,7 +1092,7 @@ under the License.
-
- * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType(); - *- * Be aware that your cell value will be changed to hold the - * result of the formula. If you simply want the formula - * value computed for you, use {@link #evaluateFormulaCellEnum(org.apache.poi.ss.usermodel.Cell)} } - */ + @Override public SXSSFCell evaluateInCell(Cell cell) { - doEvaluateInCell(cell); - return (SXSSFCell)cell; + return (SXSSFCell) super.evaluateInCell(cell); } /** diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java index c6c030b95..780126c3d 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java @@ -28,7 +28,7 @@ import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.util.Internal; +import org.apache.poi.ss.usermodel.RichTextString; /** * Internal POI use only - parent of XSSF and SXSSF formula evaluators @@ -37,6 +37,10 @@ public abstract class BaseXSSFFormulaEvaluator extends BaseFormulaEvaluator { protected BaseXSSFFormulaEvaluator(WorkbookEvaluator bookEvaluator) { super(bookEvaluator); } + @Override + protected RichTextString createRichTextString(String str) { + return new XSSFRichTextString(str); + } public void notifySetFormula(Cell cell) { _bookEvaluator.notifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); @@ -48,78 +52,6 @@ public abstract class BaseXSSFFormulaEvaluator extends BaseFormulaEvaluator { _bookEvaluator.notifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); } - /** - * If cell contains formula, it evaluates the formula, - * and saves the result of the formula. The cell - * remains as a formula cell. - * Else if cell does not contain formula, this method leaves - * the cell unchanged. - * Note that the type of the formula result is returned, - * so you know what kind of value is also stored with - * the formula. - *
- * CellType evaluatedCellType = evaluator.evaluateFormulaCellEnum(cell); - *- * Be aware that your cell will hold both the formula, - * and the result. If you want the cell replaced with - * the result of the formula, use {@link #evaluate(org.apache.poi.ss.usermodel.Cell)} } - * @param cell The cell to evaluate - * @return The type of the formula result (the cell's type remains as CellType.FORMULA however) - * If cell is not a formula cell, returns {@link CellType#_NONE} rather than throwing an exception. - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3. Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Internal(since="POI 3.15 beta 3") - public CellType evaluateFormulaCellEnum(Cell cell) { - if (cell == null || cell.getCellTypeEnum() != CellType.FORMULA) { - return CellType._NONE; - } - CellValue cv = evaluateFormulaCellValue(cell); - // cell remains a formula cell, but the cached value is changed - setCellValue(cell, cv); - return cv.getCellType(); - } - - /** - * If cell contains formula, it evaluates the formula, and - * puts the formula result back into the cell, in place - * of the old formula. - * Else if cell does not contain formula, this method leaves - * the cell unchanged. - */ - protected void doEvaluateInCell(Cell cell) { - if (cell == null) return; - if (cell.getCellTypeEnum() == CellType.FORMULA) { - CellValue cv = evaluateFormulaCellValue(cell); - setCellType(cell, cv); // cell will no longer be a formula cell - setCellValue(cell, cv); - } - } - - private static void setCellValue(Cell cell, CellValue cv) { - CellType cellType = cv.getCellType(); - switch (cellType) { - case BOOLEAN: - cell.setCellValue(cv.getBooleanValue()); - break; - case ERROR: - cell.setCellErrorValue(cv.getErrorValue()); - break; - case NUMERIC: - cell.setCellValue(cv.getNumberValue()); - break; - case STRING: - cell.setCellValue(new XSSFRichTextString(cv.getStringValue())); - break; - case BLANK: - // never happens - blanks eventually get translated to zero - case FORMULA: - // this will never happen, we have already evaluated the formula - default: - throw new IllegalStateException("Unexpected cell value type (" + cellType + ")"); - } - } - /** * Turns a XSSFCell / SXSSFCell into a XSSFEvaluationCell */ diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java index e48fe948e..edea8cda9 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java @@ -35,32 +35,87 @@ public class XSSFBorderFormatting implements BorderFormatting { _border = border; } + /** + * @deprecated POI 3.15. Use {@link #getBorderBottomEnum()}. + * This method will return an BorderStyle enum in the future. + */ @Override - public BorderStyle getBorderBottom() { + public short getBorderBottom() { + return getBorderBottomEnum().getCode(); + } + /** + * @since POI 3.15 + */ + @Override + public BorderStyle getBorderBottomEnum() { STBorderStyle.Enum ptrn = _border.isSetBottom() ? _border.getBottom().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } + /** + * @deprecated POI 3.15. Use {@link #getBorderDiagonalEnum()}. + * This method will return an BorderStyle enum in the future. + */ @Override - public BorderStyle getBorderDiagonal() { + public short getBorderDiagonal() { + return getBorderDiagonalEnum().getCode(); + } + /** + * @since POI 3.15 + */ + @Override + public BorderStyle getBorderDiagonalEnum() { STBorderStyle.Enum ptrn = _border.isSetDiagonal() ? _border.getDiagonal().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } + /** + * @deprecated POI 3.15. Use {@link #getBorderLeftEnum()}. + * This method will return an BorderStyle enum in the future. + */ @Override - public BorderStyle getBorderLeft() { + public short getBorderLeft() { + return getBorderLeftEnum().getCode(); + } + /** + * @since POI 3.15 + */ + @Override + public BorderStyle getBorderLeftEnum() { STBorderStyle.Enum ptrn = _border.isSetLeft() ? _border.getLeft().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } + /** + * @deprecated POI 3.15. Use {@link #getBorderRightEnum()}. + * This method will return an BorderStyle enum in the future. + */ @Override - public BorderStyle getBorderRight() { + public short getBorderRight() { + return getBorderRightEnum().getCode(); + } + /** + * @since POI 3.15 + */ + @Override + public BorderStyle getBorderRightEnum() { STBorderStyle.Enum ptrn = _border.isSetRight() ? _border.getRight().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } + /** + * @deprecated POI 3.15. Use {@link #getBorderTopEnum()}. + * This method will return an BorderStyle enum in the future. + */ @Override - public BorderStyle getBorderTop() { + public short getBorderTop() { + return getBorderTopEnum().getCode(); + } + /** + * @since POI 3.15 + */ + @Override + public BorderStyle getBorderTopEnum() { STBorderStyle.Enum ptrn = _border.isSetTop() ? _border.getTop().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java index 4aa2f037e..c7932d167 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java @@ -668,6 +668,7 @@ public final class XSSFCell implements Cell { * For forwards compatibility, do not hard-code cell type literals in your code. * * @return the cell type + * @deprecated 3.15. Will return a {@link CellType} enum in the future. */ @Override public int getCellType() { @@ -699,6 +700,7 @@ public final class XSSFCell implements Cell { * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending * on the cached value of the formula + * @deprecated 3.15. Will return a {@link CellType} enum in the future. */ @Override public int getCachedFormulaResultType() { @@ -714,7 +716,6 @@ public final class XSSFCell implements Cell { * @deprecated POI 3.15 beta 3 * Will be deleted when we make the CellType enum transition. See bug 59791. */ - @Internal(since="POI 3.15 beta 3") @Override public CellType getCachedFormulaResultTypeEnum() { if (! isFormulaCell()) { @@ -826,7 +827,7 @@ public final class XSSFCell implements Cell { * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} isn't {@link CellType#ERROR} * @see FormulaError */ - public String getErrorCellString() { + public String getErrorCellString() throws IllegalStateException { CellType cellType = getBaseCellType(true); if(cellType != CellType.ERROR) throw typeMismatch(CellType.ERROR, cellType, false); @@ -844,13 +845,16 @@ public final class XSSFCell implements Cell { * @see FormulaError */ @Override - public byte getErrorCellValue() { + public byte getErrorCellValue() throws IllegalStateException { String code = getErrorCellString(); if (code == null) { return 0; } - - return FormulaError.forString(code).getCode(); + try { + return FormulaError.forString(code).getCode(); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException("Unexpected error code", e); + } } /** diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java index 760c21537..9eec21ec6 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java @@ -28,6 +28,7 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.util.Internal; +import org.apache.poi.util.Removal; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.model.ThemesTable; import org.apache.poi.xssf.usermodel.extensions.XSSFCellAlignment; @@ -251,11 +252,13 @@ public class XSSFCellStyle implements CellStyle { /** * Get the type of border to use for the bottom border of the cell + * Will be removed when {@link #getBorderBottom()} returns a BorderStyle enum * * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} + * @since POI 3.15 */ @Override - public BorderStyle getBorderBottom() { + public BorderStyle getBorderBottomEnum() { if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; int idx = (int)_cellXf.getBorderId(); @@ -266,24 +269,26 @@ public class XSSFCellStyle implements CellStyle { } return BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } - /** * Get the type of border to use for the bottom border of the cell + * This will return a BorderStyle enum in the future. * - * @return border type as Java enum - * @deprecated 3.15 beta 2. Use {@link #getBorderBottom} + * @return border type code + * @deprecated 3.15 beta 2. Use {@link #getBorderBottomEnum()} */ - public BorderStyle getBorderBottomEnum() { - return getBorderBottom(); + public short getBorderBottom() { + return getBorderBottomEnum().getCode(); } /** * Get the type of border to use for the left border of the cell + * Will be removed when {@link #getBorderLeft()} returns a BorderStyle enum * * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} + * @since POI 3.15 */ @Override - public BorderStyle getBorderLeft() { + public BorderStyle getBorderLeftEnum() { if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; int idx = (int)_cellXf.getBorderId(); @@ -297,21 +302,24 @@ public class XSSFCellStyle implements CellStyle { /** * Get the type of border to use for the left border of the cell + * This will return a BorderStyle enum in the future. * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @deprecated 3.15 beta 2. Use {@link #getBorderLeft} + * @return border type code + * @deprecated 3.15 beta 2. Use {@link #getBorderLeftEnum()} */ - public BorderStyle getBorderLeftEnum() { - return getBorderLeft(); + public short getBorderLeft() { + return getBorderLeftEnum().getCode(); } /** * Get the type of border to use for the right border of the cell + * Will be removed when {@link #getBorderRight()} returns a BorderStyle enum * * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} + * @since POI 3.15 */ @Override - public BorderStyle getBorderRight() { + public BorderStyle getBorderRightEnum() { if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; int idx = (int)_cellXf.getBorderId(); @@ -322,24 +330,26 @@ public class XSSFCellStyle implements CellStyle { } return BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } - /** * Get the type of border to use for the right border of the cell + * This will return a BorderStyle enum in the future. * * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @deprecated 3.15 beta 2. Use {@link #getBorderRight} + * @deprecated 3.15 beta 2. Use {@link #getBorderRightEnum()} instead */ - public BorderStyle getBorderRightEnum() { - return getBorderRight(); + public short getBorderRight() { + return getBorderRightEnum().getCode(); } /** * Get the type of border to use for the top border of the cell + * Will be removed when {@link #getBorderTop()} returns a BorderStyle enum * * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} + * @since POI 3.15 */ @Override - public BorderStyle getBorderTop() { + public BorderStyle getBorderTopEnum() { if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; int idx = (int)_cellXf.getBorderId(); @@ -350,15 +360,15 @@ public class XSSFCellStyle implements CellStyle { } return BorderStyle.valueOf((short) (ptrn.intValue() - 1)); } - /** * Get the type of border to use for the top border of the cell + * This will return a BorderStyle enum in the future. * * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @deprecated 3.15 beta 2. Use {@link #getBorderTop} + * @deprecated 3.15 beta 2. Use {@link #getBorderTopEnum()} instead. */ - public BorderStyle getBorderTopEnum() { - return getBorderTop(); + public short getBorderTop() { + return getBorderTopEnum().getCode(); } /** @@ -775,6 +785,7 @@ public class XSSFCellStyle implements CellStyle { * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER_SELECTION * @deprecated POI 3.15 beta 3. Use {@link #setAlignment(HorizontalAlignment)} instead. */ + @Removal(version="3.17") @Override public void setAlignment(short align) { setAlignment(HorizontalAlignment.forInt(align)); @@ -796,6 +807,7 @@ public class XSSFCellStyle implements CellStyle { * @param border the type of border to use * @deprecated 3.15 beta 2. Use {@link #setBorderBottom(BorderStyle)} */ + @Removal(version="3.17") @Override public void setBorderBottom(short border) { setBorderBottom(BorderStyle.valueOf(border)); @@ -806,6 +818,7 @@ public class XSSFCellStyle implements CellStyle { * * @param border - type of border to use * @see org.apache.poi.ss.usermodel.BorderStyle + * @since POI 3.15 */ @Override public void setBorderBottom(BorderStyle border) { @@ -825,6 +838,7 @@ public class XSSFCellStyle implements CellStyle { * @param border the type of border to use * @deprecated 3.15 beta 2. Use {@link #setBorderLeft(BorderStyle)} */ + @Removal(version="3.17") @Override public void setBorderLeft(short border) { setBorderLeft(BorderStyle.valueOf(border)); @@ -834,6 +848,7 @@ public class XSSFCellStyle implements CellStyle { * Set the type of border to use for the left border of the cell * * @param border the type of border to use + * @since POI 3.15 */ @Override public void setBorderLeft(BorderStyle border) { @@ -854,6 +869,7 @@ public class XSSFCellStyle implements CellStyle { * @param border the type of border to use * @deprecated 3.15 beta 2. Use {@link #setBorderRight(BorderStyle)} */ + @Removal(version="3.17") @Override public void setBorderRight(short border) { setBorderRight(BorderStyle.valueOf(border)); @@ -863,6 +879,7 @@ public class XSSFCellStyle implements CellStyle { * Set the type of border to use for the right border of the cell * * @param border the type of border to use + * @since POI 3.15 */ @Override public void setBorderRight(BorderStyle border) { @@ -883,6 +900,7 @@ public class XSSFCellStyle implements CellStyle { * @param border the type of border to use * @deprecated 3.15 beta 2. Use {@link #setBorderTop(BorderStyle)} */ + @Removal(version="3.17") @Override public void setBorderTop(short border) { setBorderTop(BorderStyle.valueOf(border)); @@ -892,6 +910,7 @@ public class XSSFCellStyle implements CellStyle { * Set the type of border to use for the top border of the cell * * @param border the type of border to use + * @since POI 3.15 */ @Override public void setBorderTop(BorderStyle border) { @@ -1121,7 +1140,9 @@ public class XSSFCellStyle implements CellStyle { * @see #setFillBackgroundColor(short) * @see #setFillForegroundColor(short) * @param fp fill pattern (set to {@link org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND} to fill w/foreground color) + * @deprecated POI 3.15. Use {@link #setFillPattern(FillPatternType)} instead. */ + @Removal(version="3.17") @Override public void setFillPattern(short fp) { setFillPattern(FillPatternType.forInt(fp)); @@ -1335,6 +1356,7 @@ public class XSSFCellStyle implements CellStyle { * @see org.apache.poi.ss.usermodel.VerticalAlignment * @deprecated POI 3.15 beta 3. Use {@link #setVerticalAlignment(VerticalAlignment)} instead. */ + @Removal(version="3.17") @Override public void setVerticalAlignment(short align) { setVerticalAlignment(VerticalAlignment.forInt(align)); diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java index 8045912ab..df47fc227 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java @@ -19,6 +19,7 @@ package org.apache.poi.xssf.usermodel; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.util.Internal; +import org.apache.poi.util.Removal; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; /** @@ -218,15 +219,28 @@ public final class XSSFClientAnchor extends XSSFAnchor implements ClientAnchor { /** * Sets the anchor type * @param anchorType the anchor type to set + * @since POI 3.14 */ @Override public void setAnchorType( AnchorType anchorType ) { this.anchorType = anchorType; } + /** + * Sets the anchor type + * @param anchorType the anchor type to set + * @deprecated POI 3.15. Use {@link #setAnchorType(AnchorType)} instead + */ + @Removal(version="3.17") + @Override + public void setAnchorType( int anchorType ) + { + this.anchorType = AnchorType.byId(anchorType); + } /** * Gets the anchor type + * Changed from returning an int to an enum in POI 3.14 beta 1. * @return the anchor type */ @Override diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java index 63dc78069..cb11a73b2 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java @@ -20,6 +20,7 @@ import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.util.Internal; +import org.apache.poi.util.Removal; public class XSSFCreationHelper implements CreationHelper { private final XSSFWorkbook workbook; @@ -61,6 +62,7 @@ public class XSSFCreationHelper implements CreationHelper { * @deprecated POI 3.15 beta 3. Use {@link #createHyperlink(HyperlinkType)} instead. */ @Deprecated + @Removal(version="3.17") @Override public XSSFHyperlink createHyperlink(int type) { return new XSSFHyperlink(type); diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java index e85b58017..129052e79 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java @@ -58,6 +58,7 @@ final class XSSFEvaluationCell implements EvaluationCell { * For forwards compatibility, do not hard-code cell type literals in your code. * * @return cell type + * @deprecated 3.15. Will return a {@link CellType} enum in the future. */ @Override public int getCellType() { @@ -68,7 +69,6 @@ final class XSSFEvaluationCell implements EvaluationCell { * @deprecated POI 3.15 beta 3. * Will be deleted when we make the CellType enum transition. See bug 59791. */ - @Internal(since="POI 3.15 beta 3") @Override public CellType getCellTypeEnum() { return _cell.getCellTypeEnum(); diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java index fc456b7e5..e63f47b46 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java @@ -23,6 +23,8 @@ import org.apache.poi.ss.formula.IStabilityClassifier; import org.apache.poi.ss.formula.WorkbookEvaluator; import org.apache.poi.ss.formula.udf.UDFFinder; import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.CellValue; /** * Evaluates formula cells. @@ -55,27 +57,6 @@ public final class XSSFFormulaEvaluator extends BaseXSSFFormulaEvaluator { return new XSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder); } - /** - * If cell contains formula, it evaluates the formula, and - * puts the formula result back into the cell, in place - * of the old formula. - * Else if cell does not contain formula, this method leaves - * the cell unchanged. - * Note that the same instance of XSSFCell is returned to - * allow chained calls like: - *
- * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType(); - *- * Be aware that your cell value will be changed to hold the - * result of the formula. If you simply want the formula - * value computed for you, use {@link #evaluateFormulaCellEnum(org.apache.poi.ss.usermodel.Cell)} } - * @param cell - */ - public XSSFCell evaluateInCell(Cell cell) { - doEvaluateInCell(cell); - return (XSSFCell)cell; - } - /** * Loops over all cells in all sheets of the supplied * workbook. @@ -90,6 +71,12 @@ public final class XSSFFormulaEvaluator extends BaseXSSFFormulaEvaluator { public static void evaluateAllFormulaCells(XSSFWorkbook wb) { BaseFormulaEvaluator.evaluateAllFormulaCells(wb); } + + @Override + public XSSFCell evaluateInCell(Cell cell) { + return (XSSFCell) super.evaluateInCell(cell); + } + /** * Loops over all cells in all sheets of the supplied * workbook. diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java index 1f1c8421f..9d26a6658 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java @@ -168,6 +168,7 @@ public class XSSFHyperlink implements Hyperlink { * @return the type of this hyperlink * @see HyperlinkType#forInt * @deprecated POI 3.15 beta 3. Use {@link #getTypeEnum()} instead. + * getType will return a HyperlinkType enum in the future. */ @Override public int getType() { diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java index 9f6864919..bf85f65de 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java @@ -30,6 +30,7 @@ import javax.xml.namespace.QName; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; +import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.DataConsolidateFunction; @@ -213,24 +214,43 @@ public class XSSFPivotTable extends POIXMLDocumentPart { } protected AreaReference getPivotArea() { - AreaReference pivotArea = new AreaReference(getPivotCacheDefinition(). - getCTPivotCacheDefinition().getCacheSource().getWorksheetSource().getRef()); + AreaReference pivotArea = new AreaReference( + getPivotCacheDefinition() + .getCTPivotCacheDefinition() + .getCacheSource() + .getWorksheetSource() + .getRef(), + SpreadsheetVersion.EXCEL2007); return pivotArea; } + + /** + * Verify column index (relative to first column in pivot area) is within the + * pivot area + * + * @param columnIndex + * @throws IndexOutOfBoundsException + */ + private void checkColumnIndex(int columnIndex) throws IndexOutOfBoundsException { + AreaReference pivotArea = getPivotArea(); + int size = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol() + 1; + + if (columnIndex < 0 || columnIndex >= size) { + throw new IndexOutOfBoundsException("Column Index: " + columnIndex + ", Size: " + size); + } + } /** * Add a row label using data from the given column. - * @param columnIndex the index of the column to be used as row label. + * @param columnIndex the index of the source column to be used as row label. + * {@code columnIndex} is 0-based indexed and relative to the first column in the source. */ @Beta public void addRowLabel(int columnIndex) { + checkColumnIndex(columnIndex); + AreaReference pivotArea = getPivotArea(); - int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow(); - int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol(); - - if(columnIndex > lastColIndex) { - throw new IndexOutOfBoundsException(); - } + final int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow(); CTPivotFields pivotFields = pivotTableDefinition.getPivotFields(); CTPivotField pivotField = CTPivotField.Factory.newInstance(); @@ -238,7 +258,7 @@ public class XSSFPivotTable extends POIXMLDocumentPart { pivotField.setAxis(STAxis.AXIS_ROW); pivotField.setShowAll(false); - for(int i = 0; i <= lastRowIndex; i++) { + for (int i = 0; i <= lastRowIndex; i++) { items.addNewItem().setT(STItemType.DEFAULT); } items.setCount(items.sizeOfItemArray()); @@ -270,7 +290,8 @@ public class XSSFPivotTable extends POIXMLDocumentPart { /** * Add a column label using data from the given column and specified function - * @param columnIndex the index of the column to be used as column label. + * @param columnIndex the index of the source column to be used as column label. + * {@code columnIndex} is 0-based indexed and relative to the first column in the source. * @param function the function to be used on the data * The following functions exists: * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp @@ -278,12 +299,7 @@ public class XSSFPivotTable extends POIXMLDocumentPart { */ @Beta public void addColumnLabel(DataConsolidateFunction function, int columnIndex, String valueFieldName) { - AreaReference pivotArea = getPivotArea(); - int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol(); - - if(columnIndex > lastColIndex && columnIndex < 0) { - throw new IndexOutOfBoundsException(); - } + checkColumnIndex(columnIndex); addDataColumn(columnIndex, true); addDataField(function, columnIndex, valueFieldName); @@ -303,7 +319,8 @@ public class XSSFPivotTable extends POIXMLDocumentPart { /** * Add a column label using data from the given column and specified function - * @param columnIndex the index of the column to be used as column label. + * @param columnIndex the index of the source column to be used as column label + * {@code columnIndex} is 0-based indexed and relative to the first column in the source.. * @param function the function to be used on the data * The following functions exists: * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp @@ -323,12 +340,10 @@ public class XSSFPivotTable extends POIXMLDocumentPart { */ @Beta private void addDataField(DataConsolidateFunction function, int columnIndex, String valueFieldName) { + checkColumnIndex(columnIndex); + AreaReference pivotArea = getPivotArea(); - int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol(); - - if(columnIndex > lastColIndex && columnIndex < 0) { - throw new IndexOutOfBoundsException(); - } + CTDataFields dataFields; if(pivotTableDefinition.getDataFields() != null) { dataFields = pivotTableDefinition.getDataFields(); @@ -352,11 +367,8 @@ public class XSSFPivotTable extends POIXMLDocumentPart { */ @Beta public void addDataColumn(int columnIndex, boolean isDataField) { - AreaReference pivotArea = getPivotArea(); - int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol(); - if(columnIndex > lastColIndex && columnIndex < 0) { - throw new IndexOutOfBoundsException(); - } + checkColumnIndex(columnIndex); + CTPivotFields pivotFields = pivotTableDefinition.getPivotFields(); CTPivotField pivotField = CTPivotField.Factory.newInstance(); @@ -371,13 +383,11 @@ public class XSSFPivotTable extends POIXMLDocumentPart { */ @Beta public void addReportFilter(int columnIndex) { + checkColumnIndex(columnIndex); + AreaReference pivotArea = getPivotArea(); - int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol(); int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow(); - if(columnIndex > lastColIndex && columnIndex < 0) { - throw new IndexOutOfBoundsException(); - } CTPivotFields pivotFields = pivotTableDefinition.getPivotFields(); CTPivotField pivotField = CTPivotField.Factory.newInstance(); diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java index 98711c9dd..d72dca445 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java @@ -4165,9 +4165,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet { * @return The pivot table */ @Beta - public XSSFPivotTable createPivotTable(AreaReference source, CellReference position, Sheet sourceSheet){ - - if(source.getFirstCell().getSheetName() != null && !source.getFirstCell().getSheetName().equals(sourceSheet.getSheetName())) { + public XSSFPivotTable createPivotTable(AreaReference source, CellReference position, Sheet sourceSheet) { + final String sourceSheetName = source.getFirstCell().getSheetName(); + if(sourceSheetName != null && !sourceSheetName.equalsIgnoreCase(sourceSheet.getSheetName())) { throw new IllegalArgumentException("The area is referenced in another sheet than the " + "defined source sheet " + sourceSheet.getSheetName() + "."); } @@ -4193,8 +4193,10 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet { */ @Beta public XSSFPivotTable createPivotTable(AreaReference source, CellReference position){ - if(source.getFirstCell().getSheetName() != null && !source.getFirstCell().getSheetName().equals(this.getSheetName())) { - return createPivotTable(source, position, getWorkbook().getSheet(source.getFirstCell().getSheetName())); + final String sourceSheetName = source.getFirstCell().getSheetName(); + if(sourceSheetName != null && !sourceSheetName.equalsIgnoreCase(this.getSheetName())) { + final XSSFSheet sourceSheet = getWorkbook().getSheet(sourceSheetName); + return createPivotTable(source, position, sourceSheet); } return createPivotTable(source, position, this); } diff --git a/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java b/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java index 0aa022332..9d206f719 100644 --- a/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java +++ b/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java @@ -682,9 +682,12 @@ public class TestExtractorFactory { // Text try { ExtractorFactory.createExtractor(OPCPackage.open(txt.toString())); - fail(); + fail("TestExtractorFactory.testPackage() failed on " + txt.toString()); } catch(UnsupportedFileFormatException e) { // Good + } catch (Exception e) { + System.out.println("TestExtractorFactory.testPackage() failed on " + txt.toString()); + throw e; } } @@ -942,6 +945,7 @@ public class TestExtractorFactory { "openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx", "openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx", "openxml4j/OPCCompliance_DerivedPartNameFAIL.docx", + "openxml4j/invalid.xlsx", "spreadsheet/54764-2.xlsx", // see TestXSSFBugs.bug54764() "spreadsheet/54764.xlsx", // see TestXSSFBugs.bug54764() "spreadsheet/Simple.xlsb", diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java index d84ecab81..5f83bc52d 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java @@ -943,4 +943,22 @@ public final class TestPackage { ZipSecureFile.setMaxTextSize(before); } } + + // bug 60128 + @Test + public void testCorruptFile() throws IOException { + OPCPackage pkg = null; + File file = OpenXML4JTestDataSamples.getSampleFile("invalid.xlsx"); + try { + pkg = OPCPackage.open(file, PackageAccess.READ); + } catch (Exception e) { + System.out.println(e.getClass().getName()); + System.out.println(e.getMessage()); + e.printStackTrace(); + } finally { + if (pkg != null) { + pkg.close(); + } + } + } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java index 7f174e07a..0989d10cb 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java @@ -33,11 +33,14 @@ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; +import org.apache.poi.POIDataSamples; import org.apache.poi.POITextExtractor; import org.apache.poi.POIXMLException; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; +import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; +import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.ss.usermodel.Workbook; @@ -181,6 +184,7 @@ public class TestZipPackage { public void testClosingStreamOnException() throws IOException { InputStream is = OpenXML4JTestDataSamples.openSampleStream("dcterms_bug_56479.zip"); File tmp = File.createTempFile("poi-test-truncated-zip", ""); + // create a corrupted zip file by truncating a valid zip file to the first 100 bytes OutputStream os = new FileOutputStream(tmp); for (int i = 0; i < 100; i++) { os.write(is.read()); @@ -189,11 +193,63 @@ public class TestZipPackage { os.close(); is.close(); + // feed the corrupted zip file to OPCPackage try { OPCPackage.open(tmp, PackageAccess.READ); } catch (Exception e) { + // expected: the zip file is invalid + // this test does not care if open() throws an exception or not. } + // If the stream is not closed on exception, it will keep a file descriptor to tmp, + // and requests to the OS to delete the file will fail. assertTrue("Can't delete tmp file", tmp.delete()); + } + + /** + * If ZipPackage is passed an invalid file, a call to close + * (eg from the OPCPackage open method) should tidy up the + * stream / file the broken file is being read from. + * See bug #60128 for more + */ + @Test + public void testTidyStreamOnInvalidFile() throws Exception { + // Spreadsheet has a good mix of alternate file types + POIDataSamples files = POIDataSamples.getSpreadSheetInstance(); + + File[] notValidF = new File[] { + files.getFile("SampleSS.ods"), files.getFile("SampleSS.txt") + }; + InputStream[] notValidS = new InputStream[] { + files.openResourceAsStream("SampleSS.ods"), files.openResourceAsStream("SampleSS.txt") + }; + for (File notValid : notValidF) { + ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ); + assertNotNull(pkg.getZipArchive()); + assertFalse(pkg.getZipArchive().isClosed()); + try { + pkg.getParts(); + fail("Shouldn't work"); + } catch (ODFNotOfficeXmlFileException e) { + } catch (NotOfficeXmlFileException ne) {} + pkg.close(); + + assertNotNull(pkg.getZipArchive()); + assertTrue(pkg.getZipArchive().isClosed()); + } + for (InputStream notValid : notValidS) { + ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ); + assertNotNull(pkg.getZipArchive()); + assertFalse(pkg.getZipArchive().isClosed()); + try { + pkg.getParts(); + fail("Shouldn't work"); + } catch (ODFNotOfficeXmlFileException e) { + } catch (NotOfficeXmlFileException ne) {} + pkg.close(); + + assertNotNull(pkg.getZipArchive()); + assertTrue(pkg.getZipArchive().isClosed()); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java index 4d4c5df34..868a38227 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java @@ -149,10 +149,12 @@ public class TestSecureTempZip { static class AesZipFileZipEntrySource implements ZipEntrySource { final ZipFile zipFile; final Cipher ci; + boolean closed; AesZipFileZipEntrySource(ZipFile zipFile, Cipher ci) { this.zipFile = zipFile; this.ci = ci; + this.closed = false; } /** @@ -172,6 +174,12 @@ public class TestSecureTempZip { @Override public void close() throws IOException { zipFile.close(); + closed = true; + } + + @Override + public boolean isClosed() { + return closed; } } } diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java b/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java index 4e176257f..b60664ad0 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java +++ b/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java @@ -110,7 +110,7 @@ public class TestStructuredReferences { private static void confirm(FormulaEvaluator fe, Cell cell, double expectedResult) { fe.clearAllCachedResultValues(); CellValue cv = fe.evaluate(cell); - if (cv.getCellType() != CellType.NUMERIC) { + if (cv.getCellTypeEnum() != CellType.NUMERIC) { fail("expected numeric cell type but got " + cv.formatAsString()); } assertEquals(expectedResult, cv.getNumberValue(), 0.0); @@ -119,7 +119,7 @@ public class TestStructuredReferences { private static void confirm(FormulaEvaluator fe, Cell cell, String expectedResult) { fe.clearAllCachedResultValues(); CellValue cv = fe.evaluate(cell); - if (cv.getCellType() != CellType.STRING) { + if (cv.getCellTypeEnum() != CellType.STRING) { fail("expected String cell type but got " + cv.formatAsString()); } assertEquals(expectedResult, cv.getStringValue()); diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java index d86079eca..a24fd8879 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java +++ b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java @@ -96,7 +96,7 @@ public final class TestProper { cell11.setCellFormula(formulaText); evaluator.clearAllCachedResultValues(); CellValue cv = evaluator.evaluate(cell11); - if (cv.getCellType() != CellType.STRING) { + if (cv.getCellTypeEnum() != CellType.STRING) { throw new AssertionFailedError("Wrong result type: " + cv.formatAsString()); } String actualValue = cv.getStringValue(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java index bdd858b06..7b5a67de5 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; @@ -35,6 +36,8 @@ import java.util.Arrays; import org.apache.poi.POIDataSamples; import org.apache.poi.POITestCase; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.ss.usermodel.BaseTestXWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; @@ -536,4 +539,40 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { swb.dispose(); swb.close(); } + + /** + * To avoid accident changes to the template, you should be able + * to create a SXSSFWorkbook from a read-only XSSF one, then + * change + save that (only). See bug #60010 + * TODO Fix this to work! + */ + @Test + @Ignore + public void createFromReadOnlyWorkbook() throws Exception { + File input = XSSFTestDataSamples.getSampleFile("sample.xlsx"); + OPCPackage pkg = OPCPackage.open(input, PackageAccess.READ); + XSSFWorkbook xssf = new XSSFWorkbook(pkg); + SXSSFWorkbook wb = new SXSSFWorkbook(xssf, 2); + + String sheetName = "Test SXSSF"; + Sheet s = wb.createSheet(sheetName); + for (int i=0; i<10; i++) { + Row r = s.createRow(i); + r.createCell(0).setCellValue(true); + r.createCell(1).setCellValue(2.4); + r.createCell(2).setCellValue("Test Row " + i); + } + assertEquals(10, s.getLastRowNum()); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + wb.write(bos); + wb.dispose(); + wb.close(); + + xssf = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray())); + s = xssf.getSheet(sheetName); + assertEquals(10, s.getLastRowNum()); + assertEquals(true, s.getRow(0).getCell(0).getBooleanCellValue()); + assertEquals("Test Row 9", s.getRow(9).getCell(2).getStringCellValue()); + } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java index 96b363283..6ecad0a74 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java @@ -59,7 +59,7 @@ import org.junit.runners.Suite; TestXSSFSheetComments.class, TestColumnHelper.class, TestHeaderFooterHelper.class, - TestXSSFPivotTable.class, + //TestXSSFPivotTable.class, //converted to junit4 TestForkedEvaluator.class }) public final class AllXSSFUsermodelTests { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java index 4cbc7c4e6..ad8b49028 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java @@ -205,14 +205,14 @@ public final class TestFormulaEvaluatorOnXSSF { final CellType expectedCellType = expValue.getCellTypeEnum(); switch (expectedCellType) { case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(msg, CellType.BLANK, actValue.getCellTypeEnum()); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); + assertEquals(msg, CellType.BOOLEAN, actValue.getCellTypeEnum()); assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); + assertEquals(msg, CellType.ERROR, actValue.getCellTypeEnum()); // if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values // assertEquals(msg, expValue.getErrorCellValue(), actValue.getErrorValue()); // } @@ -220,14 +220,14 @@ public final class TestFormulaEvaluatorOnXSSF { case FORMULA: // will never be used, since we will call method after formula evaluation fail("Cannot expect formula as result of formula evaluation: " + msg); case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actValue.getCellType()); + assertEquals(msg, CellType.NUMERIC, actValue.getCellTypeEnum()); TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); // double delta = Math.abs(expValue.getNumericCellValue()-actValue.getNumberValue()); // double pctExpValue = Math.abs(0.00001*expValue.getNumericCellValue()); // assertTrue(msg, delta <= pctExpValue); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); + assertEquals(msg, CellType.STRING, actValue.getCellTypeEnum()); assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); break; default: diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java index f33d96e63..b8926a3cf 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java @@ -188,14 +188,14 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { final CellType expectedCellType = expValue.getCellTypeEnum(); switch (expectedCellType) { case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(msg, CellType.BLANK, actValue.getCellTypeEnum()); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); + assertEquals(msg, CellType.BOOLEAN, actValue.getCellTypeEnum()); assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); + assertEquals(msg, CellType.ERROR, actValue.getCellTypeEnum()); // if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values // assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue()); // } @@ -203,14 +203,14 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { case FORMULA: // will never be used, since we will call method after formula evaluation fail("Cannot expect formula as result of formula evaluation: " + msg); case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actValue.getCellType()); + assertEquals(msg, CellType.NUMERIC, actValue.getCellTypeEnum()); TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); // double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue()); // double pctExpected = Math.abs(0.00001*expected.getNumericCellValue()); // assertTrue(msg, delta <= pctExpected); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); + assertEquals(msg, CellType.STRING, actValue.getCellTypeEnum()); assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); break; default: diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java index 2be21e830..e695f385f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java @@ -304,7 +304,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { if(c.getCellTypeEnum() == CellType.FORMULA) { CellValue cv = eval.evaluate(c); - if(cv.getCellType() == CellType.NUMERIC) { + if(cv.getCellTypeEnum() == CellType.NUMERIC) { // assert that the calculated value agrees with // the cached formula result calculated by Excel String formula = c.getCellFormula(); @@ -2187,7 +2187,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertEquals("E4+E5", cell.getCellFormula()); CellValue value = evaluator.evaluate(cell); - assertEquals(CellType.ERROR, value.getCellType()); + assertEquals(CellType.ERROR, value.getCellTypeEnum()); assertEquals(-60, value.getErrorValue()); assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString()); assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString()); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java index 94e40a3a7..c907d40db 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java @@ -104,11 +104,11 @@ public class TestXSSFCellStyle { @Test public void testGetSetBorderBottom() { //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderBottom()); + assertEquals(BorderStyle.NONE, cellStyle.getBorderBottomEnum()); int num = stylesTable.getBorders().size(); cellStyle.setBorderBottom(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottom()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottomEnum()); //a new border has been added assertEquals(num + 1, stylesTable.getBorders().size()); //id of the created border @@ -122,7 +122,7 @@ public class TestXSSFCellStyle { //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.setBorderBottom(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottom()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottomEnum()); } assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); assertEquals(num, stylesTable.getBorders().size()); @@ -139,11 +139,11 @@ public class TestXSSFCellStyle { @Test public void testGetSetBorderRight() { //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderRight()); + assertEquals(BorderStyle.NONE, cellStyle.getBorderRightEnum()); int num = stylesTable.getBorders().size(); cellStyle.setBorderRight(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRight()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRightEnum()); //a new border has been added assertEquals(num + 1, stylesTable.getBorders().size()); //id of the created border @@ -157,7 +157,7 @@ public class TestXSSFCellStyle { //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.setBorderRight(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRight()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRightEnum()); } assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); assertEquals(num, stylesTable.getBorders().size()); @@ -174,11 +174,11 @@ public class TestXSSFCellStyle { @Test public void testGetSetBorderLeft() { //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderLeft()); + assertEquals(BorderStyle.NONE, cellStyle.getBorderLeftEnum()); int num = stylesTable.getBorders().size(); cellStyle.setBorderLeft(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeft()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeftEnum()); //a new border has been added assertEquals(num + 1, stylesTable.getBorders().size()); //id of the created border @@ -192,7 +192,7 @@ public class TestXSSFCellStyle { //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.setBorderLeft(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeft()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeftEnum()); } assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); assertEquals(num, stylesTable.getBorders().size()); @@ -209,11 +209,11 @@ public class TestXSSFCellStyle { @Test public void testGetSetBorderTop() { //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderTop()); + assertEquals(BorderStyle.NONE, cellStyle.getBorderTopEnum()); int num = stylesTable.getBorders().size(); cellStyle.setBorderTop(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTop()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTopEnum()); //a new border has been added assertEquals(num + 1, stylesTable.getBorders().size()); //id of the created border @@ -227,7 +227,7 @@ public class TestXSSFCellStyle { //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.setBorderTop(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTop()); + assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTopEnum()); } assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); assertEquals(num, stylesTable.getBorders().size()); @@ -243,7 +243,7 @@ public class TestXSSFCellStyle { private void testGetSetBorderXMLBean(BorderStyle border, STBorderStyle.Enum expected) { cellStyle.setBorderTop(border); - assertEquals(border, cellStyle.getBorderTop()); + assertEquals(border, cellStyle.getBorderTopEnum()); int borderId = (int)cellStyle.getCoreXf().getBorderId(); assertTrue(borderId > 0); //check changes in the underlying xml bean @@ -256,7 +256,7 @@ public class TestXSSFCellStyle { @Test public void testGetSetBorderNone() { cellStyle.setBorderTop(BorderStyle.NONE); - assertEquals(BorderStyle.NONE, cellStyle.getBorderTop()); + assertEquals(BorderStyle.NONE, cellStyle.getBorderTopEnum()); int borderId = (int)cellStyle.getCoreXf().getBorderId(); assertTrue(borderId > 0); //check changes in the underlying xml bean @@ -562,10 +562,10 @@ public class TestXSSFCellStyle { assertEquals(style2.getRightBorderColor(), style1.getRightBorderColor()); assertEquals(style2.getBottomBorderColor(), style1.getBottomBorderColor()); - assertEquals(style2.getBorderBottom(), style1.getBorderBottom()); - assertEquals(style2.getBorderLeft(), style1.getBorderLeft()); - assertEquals(style2.getBorderRight(), style1.getBorderRight()); - assertEquals(style2.getBorderTop(), style1.getBorderTop()); + assertEquals(style2.getBorderBottomEnum(), style1.getBorderBottomEnum()); + assertEquals(style2.getBorderLeftEnum(), style1.getBorderLeftEnum()); + assertEquals(style2.getBorderRightEnum(), style1.getBorderRightEnum()); + assertEquals(style2.getBorderTopEnum(), style1.getBorderTopEnum()); wb2.close(); } @@ -999,7 +999,7 @@ public class TestXSSFCellStyle { Workbook copy = XSSFTestDataSamples.writeOutAndReadBack(target); // previously this failed because the border-element was not copied over - copy.getCellStyleAt((short)1).getBorderBottom(); + copy.getCellStyleAt((short)1).getBorderBottomEnum(); copy.close(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java index 6dcaef960..84a4aa680 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java @@ -682,4 +682,15 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { value = evaluator.evaluate(cell); assertEquals(1, value.getNumberValue(), 0.001); } + + @Test + public void evaluateInCellReturnsSameDataType() throws IOException { + XSSFWorkbook wb = new XSSFWorkbook(); + wb.createSheet().createRow(0).createCell(0); + XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); + XSSFCell same = evaluator.evaluateInCell(cell); + assertSame(cell, same); + wb.close(); + } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTable.java index 55fe4a4fa..851ca33d6 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTable.java @@ -16,30 +16,39 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; + import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.DataConsolidateFunction; import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.XSSFITestDataProvider; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageField; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageFields; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFields; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataConsolidateFunction; -import junit.framework.TestCase; - -public class TestXSSFPivotTable extends TestCase { +public class TestXSSFPivotTable { + private static final XSSFITestDataProvider _testDataProvider = XSSFITestDataProvider.instance; + private XSSFWorkbook wb; private XSSFPivotTable pivotTable; private XSSFPivotTable offsetPivotTable; private Cell offsetOuterCell; - @Override + @Before public void setUp(){ - Workbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) wb.createSheet(); + wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet(); Row row1 = sheet.createRow(0); // Create a cell and put a value in it. @@ -72,10 +81,10 @@ public class TestXSSFPivotTable extends TestCase { Cell cell12 = row1.createCell(3); cell12.setCellValue(12.12); - AreaReference source = new AreaReference("A1:C2"); + AreaReference source = new AreaReference("A1:C2", _testDataProvider.getSpreadsheetVersion()); pivotTable = sheet.createPivotTable(source, new CellReference("H5")); - XSSFSheet offsetSheet = (XSSFSheet) wb.createSheet(); + XSSFSheet offsetSheet = wb.createSheet(); Row tableRow_1 = offsetSheet.createRow(1); offsetOuterCell = tableRow_1.createCell(1); @@ -114,11 +123,19 @@ public class TestXSSFPivotTable extends TestCase { AreaReference offsetSource = new AreaReference(new CellReference("C2"), new CellReference("E4")); offsetPivotTable = offsetSheet.createPivotTable(offsetSource, new CellReference("C6")); } + + @After + public void tearDown() throws IOException { + XSSFWorkbook wb2 = _testDataProvider.writeOutAndReadBack(wb); + wb.close(); + wb2.close(); + } /** * Verify that when creating a row label it's created on the correct row * and the count is increased by one. */ + @Test public void testAddRowLabelToPivotTable() { int columnIndex = 0; @@ -141,6 +158,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's not possible to create a row label outside of the referenced area. */ + @Test public void testAddRowLabelOutOfRangeThrowsException() { int columnIndex = 5; @@ -155,6 +173,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that when creating one column label, no col fields are being created. */ + @Test public void testAddOneColumnLabelToPivotTableDoesNotCreateColField() { int columnIndex = 0; @@ -167,6 +186,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's possible to create three column labels with different DataConsolidateFunction */ + @Test public void testAddThreeDifferentColumnLabelsToPivotTable() { int columnOne = 0; int columnTwo = 1; @@ -184,6 +204,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's possible to create three column labels with the same DataConsolidateFunction */ + @Test public void testAddThreeSametColumnLabelsToPivotTable() { int columnOne = 0; int columnTwo = 1; @@ -200,6 +221,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that when creating two column labels, a col field is being created and X is set to -2. */ + @Test public void testAddTwoColumnLabelsToPivotTable() { int columnOne = 0; int columnTwo = 1; @@ -214,6 +236,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that a data field is created when creating a data column */ + @Test public void testColumnLabelCreatesDataField() { int columnIndex = 0; @@ -229,6 +252,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's possible to set a custom name when creating a data column */ + @Test public void testColumnLabelSetCustomName() { int columnIndex = 0; @@ -245,6 +269,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's not possible to create a column label outside of the referenced area. */ + @Test public void testAddColumnLabelOutOfRangeThrowsException() { int columnIndex = 5; @@ -260,6 +285,7 @@ public class TestXSSFPivotTable extends TestCase { * Verify when creating a data column set to a data field, the data field with the corresponding * column index will be set to true. */ + @Test public void testAddDataColumn() { int columnIndex = 0; boolean isDataField = true; @@ -272,6 +298,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's not possible to create a data column outside of the referenced area. */ + @Test public void testAddDataColumnOutOfRangeThrowsException() { int columnIndex = 5; boolean isDataField = true; @@ -301,6 +328,7 @@ public class TestXSSFPivotTable extends TestCase { /** * Verify that it's not possible to create a new filter outside of the referenced area. */ + @Test public void testAddReportFilterOutOfRangeThrowsException() { int columnIndex = 5; try { @@ -315,10 +343,28 @@ public class TestXSSFPivotTable extends TestCase { * Verify that the Pivot Table operates only within the referenced area, even when the * first column of the referenced area is not index 0. */ + @Test public void testAddDataColumnWithOffsetData() { offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1); assertEquals(CellType.NUMERIC, offsetOuterCell.getCellTypeEnum()); offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 0); } + + @Test + public void testPivotTableSheetNamesAreCaseInsensitive() { + wb.setSheetName(0, "original"); + wb.setSheetName(1, "offset"); + XSSFSheet original = wb.getSheet("OriginaL"); + XSSFSheet offset = wb.getSheet("OffseT"); + // assume sheets are accessible via case-insensitive name + assertNotNull(original); + assertNotNull(offset); + + AreaReference source = new AreaReference("ORIGinal!A1:C2", _testDataProvider.getSpreadsheetVersion()); + // create a pivot table on the same sheet, case insensitive + original.createPivotTable(source, new CellReference("W1")); + // create a pivot table on a different sheet, case insensitive + offset.createPivotTable(source, new CellReference("W1")); + } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java index ad0e5aa9a..a17c61143 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java +++ b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java @@ -804,6 +804,7 @@ public final class HSLFSlideShow implements SlideShow
The Apache POI team is pleased to announce the release of ${version.id}. - Featured are a handful of new areas of functionality and numerous bug fixes.
-A summary of changes is available in the - Release Notes. - A full list of changes is available in the change log. - People interested should also follow the dev list - to track progress.
-- The POI source release as well as the pre-built binary deployment packages are listed below. - Pre-built versions of all POI components - are available in the central Maven repository under Group ID "org.apache.poi" and Version - "${version.id}". -
-This class copies a POI file system to a new file and compares the copy - * with the original.
- * - *Property set streams are copied logically, i.e. the application - * establishes a {@link org.apache.poi.hpsf.PropertySet} of an original property - * set, creates a {@link org.apache.poi.hpsf.MutablePropertySet} from the - * {@link org.apache.poi.hpsf.PropertySet} and writes the - * {@link org.apache.poi.hpsf.MutablePropertySet} to the destination POI file - * system. - Streams which are no property set streams are copied bit by - * bit.
- * - *The comparison of the POI file systems is done logically. That means that - * the two disk files containing the POI file systems do not need to be - * exactly identical. However, both POI file systems must contain the same - * files, and most of these files must be bitwise identical. Property set - * streams, however, are compared logically: they must have the same sections - * with the same attributs, and the sections must contain the same properties. - * Details like the ordering of the properties do not matter.
- */ -public class CopyCompare -{ - /** - *Runs the example program. The application expects one or two - * arguments:
- * - *The first argument is the disk file name of the POI filesystem to - * copy.
The second argument is optional. If it is given, it is the name of - * a disk file the copy of the POI filesystem will be written to. If it is - * not given, the copy will be written to a temporary file which will be - * deleted at the end of the program.
Compares two {@link DirectoryEntry} instances of a POI file system. - * The directories must contain the same streams with the same names and - * contents.
- * - * @param d1 The first directory. - * @param d2 The second directory. - * @param msg The method may append human-readable comparison messages to - * this string buffer. - * @returntrue
if the directories are equal, else
- * false
.
- * @exception MarkUnsupportedException if a POI document stream does not
- * support the mark() operation.
- * @exception NoPropertySetStreamException if the application tries to
- * create a property set from a POI document stream that is not a property
- * set stream.
- * @throws UnsupportedEncodingException
- * @exception IOException if any I/O exception occurs.
- */
- private static boolean equal(final DirectoryEntry d1,
- final DirectoryEntry d2,
- final StringBuffer msg)
- throws NoPropertySetStreamException, MarkUnsupportedException,
- UnsupportedEncodingException, IOException
- {
- boolean equal = true;
- /* Iterate over d1 and compare each entry with its counterpart in d2. */
- for (final Entry e1 : d1) {
- final String n1 = e1.getName();
- Entry e2 = null;
- try {
- e2 = d2.getEntry(n1);
- } catch (FileNotFoundException ex) {
- msg.append("Document \"" + e1 + "\" exists, document \"" +
- e2 + "\" does not.\n");
- equal = false;
- break;
- }
-
- if (e1.isDirectoryEntry() && e2.isDirectoryEntry()) {
- equal = equal((DirectoryEntry) e1, (DirectoryEntry) e2, msg);
- } else if (e1.isDocumentEntry() && e2.isDocumentEntry()) {
- equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg);
- } else {
- msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " +
- "document while the other one is a directory.\n");
- equal = false;
- }
- }
-
- /* Iterate over d2 just to make sure that there are no entries in d2
- * that are not in d1. */
- for (final Entry e2 : d2) {
- final String n2 = e2.getName();
- Entry e1 = null;
- try {
- e1 = d1.getEntry(n2);
- } catch (FileNotFoundException ex) {
- msg.append("Document \"" + e2 + "\" exitsts, document \"" +
- e1 + "\" does not.\n");
- equal = false;
- break;
- }
- }
- return equal;
- }
-
-
-
- /**
- * Compares two {@link DocumentEntry} instances of a POI file system. - * Documents that are not property set streams must be bitwise identical. - * Property set streams must be logically equal.
- * - * @param d1 The first document. - * @param d2 The second document. - * @param msg The method may append human-readable comparison messages to - * this string buffer. - * @returntrue
if the documents are equal, else
- * false
.
- * @exception MarkUnsupportedException if a POI document stream does not
- * support the mark() operation.
- * @exception NoPropertySetStreamException if the application tries to
- * create a property set from a POI document stream that is not a property
- * set stream.
- * @throws UnsupportedEncodingException
- * @exception IOException if any I/O exception occurs.
- */
- private static boolean equal(final DocumentEntry d1, final DocumentEntry d2,
- final StringBuffer msg)
- throws NoPropertySetStreamException, MarkUnsupportedException,
- UnsupportedEncodingException, IOException
- {
- boolean equal = true;
- final DocumentInputStream dis1 = new DocumentInputStream(d1);
- final DocumentInputStream dis2 = new DocumentInputStream(d2);
- try {
- if (PropertySet.isPropertySetStream(dis1) &&
- PropertySet.isPropertySetStream(dis2)) {
- final PropertySet ps1 = PropertySetFactory.create(dis1);
- final PropertySet ps2 = PropertySetFactory.create(dis2);
- equal = ps1.equals(ps2);
- if (!equal) {
- msg.append("Property sets are not equal.\n");
- return equal;
- }
- } else {
- int i1;
- int i2;
- do {
- i1 = dis1.read();
- i2 = dis2.read();
- if (i1 != i2) {
- equal = false;
- msg.append("Documents are not equal.\n");
- break;
- }
- } while (equal && i1 == -1);
- }
- } finally {
- dis2.close();
- dis1.close();
- }
- return true;
- }
-
-
-
- /**
- * This class does all the work. Its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each file in - * the original POI file system. Except for property set streams it copies - * everything unmodified to the destination POI filesystem. Property set - * streams are copied by creating a new {@link PropertySet} from the - * original property set by using the {@link - * MutablePropertySet#MutablePropertySet(PropertySet)} constructor.
- */ - static class CopyFile implements POIFSReaderListener { - String dstName; - OutputStream out; - POIFSFileSystem poiFs; - - - /** - *The constructor of a {@link CopyFile} instance creates the target - * POIFS. It also stores the name of the file the POIFS will be written - * to once it is complete.
- * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - public CopyFile(final String dstName) { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } - - - /** - *The method is called by POI's eventing API for each file in the - * origin POIFS.
- */ - public void processPOIFSReaderEvent(final POIFSReaderEvent event) { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); - - Throwable t = null; - - try { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = null; - try { - ps = PropertySetFactory.create(stream); - } catch (NoPropertySetStreamException ex) { - /* This exception will not be thrown because we already - * checked above. */ - } - - /* Copy the property set to the destination POI file - * system. */ - copy(poiFs, path, name, ps); - } else { - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); - } - } catch (MarkUnsupportedException ex) { - t = ex; - } catch (IOException ex) { - t = ex; - } catch (WritingNotSupportedException ex) { - t = ex; - } - - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occured and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) { - throw new HPSFRuntimeException - ("Could not read file \"" + path + "/" + name + - "\". Reason: " + Util.toString(t)); - } - } - - - - /** - *Writes a {@link PropertySet} to a POI filesystem.
- * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - * @throws WritingNotSupportedException - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException { - final DirectoryEntry de = getPath(poiFs, path); - final MutablePropertySet mps = new MutablePropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.
- * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) - throws IOException { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) { - out.write(c); - } - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - *Writes the POI file system to a disk file.
- * - * @throws FileNotFoundException - * @throws IOException - */ - public void close() throws FileNotFoundException, IOException { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final MapEnsures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.
- * - *Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.
- * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) { - try { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) { - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - } else { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); - } - paths.put(s, de); - return de; - } catch (IOException ex) { - /* This exception will be thrown if the directory already - * exists. However, since we have full control about directory - * creation we can ensure that this will never happen. */ - ex.printStackTrace(System.err); - throw new RuntimeException(ex.toString()); - /* FIXME (2): Replace the previous line by the following once we - * no longer need JDK 1.3 compatibility. */ - // throw new RuntimeException(ex); - } - } - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java b/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java deleted file mode 100644 index 81a9594e7..000000000 --- a/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; - -/** - *This is a sample application showing how to easily modify properties in - * the summary information and in the document summary information. The - * application reads the name of a POI filesystem from the command line and - * performs the following actions:
- * - *Open the POI filesystem.
Read the summary information.
Read and print the "author" property.
Change the author to "Rainer Klute".
Read the document summary information.
Read and print the "category" property.
Change the category to "POI example".
Read the custom properties (if available).
Insert a new custom property.
Write the custom properties back to the document summary - * information.
Write the summary information to the POI filesystem.
Write the document summary information to the POI filesystem.
Write the POI filesystem back to the original file.
Main method - see class description.
- * - * @param args The command-line parameters. - * @throws IOException - * @throws MarkUnsupportedException - * @throws NoPropertySetStreamException - * @throws UnexpectedPropertySetTypeException - * @throws WritingNotSupportedException - */ - public static void main(final String[] args) throws IOException, - NoPropertySetStreamException, MarkUnsupportedException, - UnexpectedPropertySetTypeException, WritingNotSupportedException - { - /* Read the name of the POI filesystem to modify from the command line. - * For brevity to boundary check is performed on the command-line - * arguments. */ - File summaryFile = new File(args[0]); - - /* Open the POI filesystem. */ - NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false); - - /* Read the summary information. */ - DirectoryEntry dir = poifs.getRoot(); - SummaryInformation si; - try - { - si = (SummaryInformation)PropertySetFactory.create( - dir, SummaryInformation.DEFAULT_STREAM_NAME); - } - catch (FileNotFoundException ex) - { - // There is no summary information yet. We have to create a new one - si = PropertySetFactory.newSummaryInformation(); - } - - /* Change the author to "Rainer Klute". Any former author value will - * be lost. If there has been no author yet, it will be created. */ - si.setAuthor("Rainer Klute"); - System.out.println("Author changed to " + si.getAuthor() + "."); - - - /* Handling the document summary information is analogous to handling - * the summary information. An additional feature, however, are the - * custom properties. */ - - /* Read the document summary information. */ - DocumentSummaryInformation dsi; - try - { - dsi = (DocumentSummaryInformation)PropertySetFactory.create( - dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - } - catch (FileNotFoundException ex) - { - /* There is no document summary information yet. We have to create a - * new one. */ - dsi = PropertySetFactory.newDocumentSummaryInformation(); - } - - /* Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. */ - dsi.setCategory("POI example"); - System.out.println("Category changed to " + dsi.getCategory() + "."); - - /* Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. */ - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) - customProperties = new CustomProperties(); - - /* Insert some custom properties into the container. */ - customProperties.put("Key 1", "Value 1"); - customProperties.put("Schl\u00fcssel 2", "Wert 2"); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); - customProperties.put("Sample Date", new Date()); - - /* Read a custom property. */ - Object value = customProperties.get("Sample Number"); - System.out.println("Custom Sample Number is now " + value); - - /* Write the custom properties back to the document summary - * information. */ - dsi.setCustomProperties(customProperties); - - /* Write the summary information and the document summary information - * to the POI filesystem. */ - si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME); - dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - /* Write the POI filesystem back to the original file. Please note that - * in production code you should take care when write directly to the - * origin, to make sure you don't loose things on error */ - poifs.writeFilesystem(); - poifs.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java b/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java deleted file mode 100644 index 222fff9ff..000000000 --- a/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.util.HexDump; - -/** - *Sample application showing how to read a document's custom property set. - * Call it with the document's file name as command-line parameter.
- * - *Explanations can be found in the HPSF HOW-TO.
- */ -public class ReadCustomPropertySets -{ - - /** - *Runs the example program.
- * - * @param args Command-line arguments (unused). - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) - throws IOException - { - final String filename = args[0]; - POIFSReader r = new POIFSReader(); - - /* Register a listener for *all* documents. */ - r.registerListener(new MyPOIFSReaderListener()); - r.read(new FileInputStream(filename)); - } - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - PropertySet ps = null; - try - { - ps = PropertySetFactory.create(event.getStream()); - } - catch (NoPropertySetStreamException ex) - { - out("No property set stream: \"" + event.getPath() + - event.getName() + "\""); - return; - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - - /* Print the name of the property set stream: */ - out("Property set stream \"" + event.getPath() + - event.getName() + "\":"); - - /* Print the number of sections: */ - final long sectionCount = ps.getSectionCount(); - out(" No. of sections: " + sectionCount); - - /* Print the list of sections: */ - ListSample application showing how to read a OLE 2 document's - * title. Call it with the document's file name as command line - * parameter.
- * - *Explanations can be found in the HPSF HOW-TO.
- */ -public class ReadTitle -{ - /** - *Runs the example program.
- * - * @param args Command-line arguments. The first command-line argument must - * be the name of a POI filesystem to read. - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) throws IOException - { - final String filename = args[0]; - POIFSReader r = new POIFSReader(); - r.registerListener(new MyPOIFSReaderListener(), - "\005SummaryInformation"); - r.read(new FileInputStream(filename)); - } - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - SummaryInformation si = null; - try - { - si = (SummaryInformation) - PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - final String title = si.getTitle(); - if (title != null) - System.out.println("Title: \"" + title + "\""); - else - System.out.println("Document has no title."); - } - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java b/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java deleted file mode 100644 index 996aa9ff7..000000000 --- a/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java +++ /dev/null @@ -1,419 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hpsf.HPSFRuntimeException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Util; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *This class is a sample application which shows how to write or modify the - * author and title property of an OLE 2 document. This could be done in two - * different ways:
- * - *The first approach is to open the OLE 2 file as a POI filesystem - * (see class {@link POIFSFileSystem}), read the summary information property - * set (see classes {@link SummaryInformation} and {@link PropertySet}), write - * the author and title properties into it and write the property set back into - * the POI filesystem.
The second approach does not modify the original POI filesystem, but - * instead creates a new one. All documents from the original POIFS are copied - * to the destination POIFS, except for the summary information stream. The - * latter is modified by setting the author and title property before writing - * it to the destination POIFS. It there are several summary information streams - * in the original POIFS - e.g. in subordinate directories - they are modified - * just the same.
This sample application takes the second approach. It expects the name of - * the existing POI filesystem's name as its first command-line parameter and - * the name of the output POIFS as the second command-line argument. The - * program then works as described above: It copies nearly all documents - * unmodified from the input POI filesystem to the output POI filesystem. If it - * encounters a summary information stream it reads its properties. Then it sets - * the "author" and "title" properties to new values and writes the modified - * summary information stream into the output file.
- * - *Further explanations can be found in the HPSF HOW-TO.
- */ -public class WriteAuthorAndTitle -{ - /** - *Runs the example program.
- * - * @param args Command-line arguments. The first command-line argument must - * be the name of a POI filesystem to read. - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) throws IOException - { - /* Check whether we have exactly two command-line arguments. */ - if (args.length != 2) - { - System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() + - " originPOIFS destinationPOIFS"); - System.exit(1); - } - - /* Read the names of the origin and destination POI filesystems. */ - final String srcName = args[0]; - final String dstName = args[1]; - - /* Read the origin POIFS using the eventing API. The real work is done - * in the class ModifySICopyTheRest which is registered here as a - * POIFSReader. */ - final POIFSReader r = new POIFSReader(); - final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); - r.registerListener(msrl); - FileInputStream fis = new FileInputStream(srcName); - r.read(fis); - fis.close(); - - /* Write the new POIFS to disk. */ - msrl.close(); - } - - - - /** - *This class does all the work. As its name implies it modifies a - * summary information property set and copies everything else unmodified - * to the destination POI filesystem. Since an instance of it is registered - * as a {@link POIFSReader} its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each document - * in the origin POIFS.
- */ - static class ModifySICopyTheRest implements POIFSReaderListener - { - String dstName; - OutputStream out; - POIFSFileSystem poiFs; - - - /** - *The constructor of a {@link ModifySICopyTheRest} instance creates - * the target POIFS. It also stores the name of the file the POIFS will - * be written to once it is complete.
- * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - public ModifySICopyTheRest(final String dstName) - { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } - - - /** - *The method is called by POI's eventing API for each file in the - * origin POIFS.
- */ - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); - - Throwable t = null; - - try - { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) - { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = null; - try - { - ps = PropertySetFactory.create(stream); - } - catch (NoPropertySetStreamException ex) - { - /* This exception will not be thrown because we already - * checked above. */ - } - - /* Now we know that we really have a property set. The next - * step is to find out whether it is a summary information - * or not. */ - if (ps.isSummaryInformation()) - /* Yes, it is a summary information. We will modify it - * and write the result to the destination POIFS. */ - editSI(poiFs, path, name, ps); - else - /* No, it is not a summary information. We don't care - * about its internals and copy it unmodified to the - * destination POIFS. */ - copy(poiFs, path, name, ps); - } - else - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); - } - catch (MarkUnsupportedException ex) - { - t = ex; - } - catch (IOException ex) - { - t = ex; - } - catch (WritingNotSupportedException ex) - { - t = ex; - } - - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occured and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) - { - throw new HPSFRuntimeException - ("Could not read file \"" + path + "/" + name + - "\". Reason: " + Util.toString(t)); - } - } - - - /** - *Receives a summary information property set modifies (or creates) - * its "author" and "title" properties and writes the result under the - * same path and name as the origin to a destination POI filesystem.
- * - * @param poiFs The POI filesystem to write to. - * @param path The original (and destination) stream's path. - * @param name The original (and destination) stream's name. - * @param si The property set. It should be a summary information - * property set. - * @throws IOException - * @throws WritingNotSupportedException - */ - public void editSI(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet si) - throws WritingNotSupportedException, IOException - - { - /* Get the directory entry for the target stream. */ - final DirectoryEntry de = getPath(poiFs, path); - - /* Create a mutable property set as a copy of the original read-only - * property set. */ - final MutablePropertySet mps = new MutablePropertySet(si); - - /* Retrieve the section containing the properties to modify. A - * summary information property set contains exactly one section. */ - final MutableSection s = - (MutableSection) mps.getSections().get(0); - - /* Set the properties. */ - s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, - "Rainer Klute"); - s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, - "Test"); - - /* Create an input stream containing the bytes the property set - * stream consists of. */ - final InputStream pss = mps.toInputStream(); - - /* Write the property set stream to the POIFS. */ - de.createDocument(name, pss); - } - - - /** - *Writes a {@link PropertySet} to a POI filesystem. This method is - * simpler than {@link #editSI} because the origin property set has just - * to be copied.
- * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - * @throws WritingNotSupportedException - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final MutablePropertySet mps = new MutablePropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.
- * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) throws IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) - out.write(c); - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - *Writes the POI file system to a disk file.
- * - * @throws FileNotFoundException - * @throws IOException - */ - public void close() throws FileNotFoundException, IOException - { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final MapEnsures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.
- * - *Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.
- * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) - { - try - { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - else - { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); - } - paths.put(s, de); - return de; - } - catch (IOException ex) - { - /* This exception will be thrown if the directory already - * exists. However, since we have full control about directory - * creation we can ensure that this will never happen. */ - ex.printStackTrace(System.err); - throw new RuntimeException(ex); - } - } - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java b/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java deleted file mode 100644 index e57ef17b4..000000000 --- a/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hpsf.MutableProperty; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *This class is a simple sample application showing how to create a property - * set and write it to disk.
- */ -public class WriteTitle -{ - /** - *Runs the example program.
- * - * @param args Command-line arguments. The first and only command-line - * argument is the name of the POI file system to create. - * @throws IOException if any I/O exception occurs. - * @throws WritingNotSupportedException if HPSF does not (yet) support - * writing a certain property type. - */ - public static void main(final String[] args) - throws WritingNotSupportedException, IOException - { - /* Check whether we have exactly one command-line argument. */ - if (args.length != 1) - { - System.err.println("Usage: " + WriteTitle.class.getName() + - "destinationPOIFS"); - System.exit(1); - } - - final String fileName = args[0]; - - /* Create a mutable property set. Initially it contains a single section - * with no properties. */ - final MutablePropertySet mps = new MutablePropertySet(); - - /* Retrieve the section the property set already contains. */ - final MutableSection ms = (MutableSection) mps.getSections().get(0); - - /* Turn the property set into a summary information property. This is - * done by setting the format ID of its first section to - * SectionIDMap.SUMMARY_INFORMATION_ID. */ - ms.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID); - - /* Create an empty property. */ - final MutableProperty p = new MutableProperty(); - - /* Fill the property with appropriate settings so that it specifies the - * document's title. */ - p.setID(PropertyIDMap.PID_TITLE); - p.setType(Variant.VT_LPWSTR); - p.setValue("Sample title"); - - /* Place the property into the section. */ - ms.setProperty(p); - - /* Create the POI file system the property set is to be written to. */ - final POIFSFileSystem poiFs = new POIFSFileSystem(); - - /* For writing the property set into a POI file system it has to be - * handed over to the POIFS.createDocument() method as an input stream - * which produces the bytes making out the property set stream. */ - final InputStream is = mps.toInputStream(); - - /* Create the summary information property set in the POI file - * system. It is given the default name most (if not all) summary - * information property sets have. */ - poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME); - - /* Write the whole POI file system to a disk file. */ - poiFs.writeFilesystem(new FileOutputStream(fileName)); - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java deleted file mode 100644 index 578c3a679..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java +++ /dev/null @@ -1,456 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.Rectangle2D; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.sl.draw.DrawTableShape; -import org.apache.poi.sl.draw.SLGraphics; -import org.apache.poi.sl.usermodel.AutoShape; -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.TableCell; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; -import org.apache.poi.sl.usermodel.VerticalAlignment; - -/** - * Presentation for Fast Feather Track on ApacheconEU 2008 - * - * @author Yegor Kozlov - */ -public final class ApacheconEU08 { - - public static void main(String[] args) throws IOException { - SlideShow,?> ppt = new HSLFSlideShow(); - // SlideShow,?> ppt = new XMLSlideShow(); - ppt.setPageSize(new Dimension(720, 540)); - - slide1(ppt); - slide2(ppt); - slide3(ppt); - slide4(ppt); - slide5(ppt); - slide6(ppt); - slide7(ppt); - slide8(ppt); - slide9(ppt); - slide10(ppt); - slide11(ppt); - slide12(ppt); - - String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx"; - FileOutputStream out = new FileOutputStream("apachecon_eu_08."+ext); - ppt.write(out); - out.close(); - ppt.close(); - } - - public static void slide1(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.CENTER_TITLE); - box1.setText("POI-HSLF"); - box1.setAnchor(new Rectangle(54, 78, 612, 115)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.CENTER_BODY); - box2.setText("Java API To Access Microsoft PowerPoint Format Files"); - box2.setAnchor(new Rectangle(108, 204, 504, 138)); - - TextBox,?> box3 = slide.createTextBox(); - box3.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(32d); - box3.setText( - "Yegor Kozlov\r" + - "yegor - apache - org"); - box3.setHorizontalCentered(true); - box3.setAnchor(new Rectangle(206, 348, 310, 84)); - } - - public static void slide2(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("What is HSLF?"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText("HorribleSLideshowFormat is the POI Project's pure Java implementation " + - "of the Powerpoint binary file format. \r" + - "POI sub-project since 2005\r" + - "Started by Nick Burch, Yegor Kozlov joined soon after"); - box2.setAnchor(new Rectangle(36, 126, 648, 356)); - } - - public static void slide3(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in a Nutshell"); - box1.setAnchor(new Rectangle(36, 15, 648, 65)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "HSLF provides a way to read, create and modify MS PowerPoint presentations\r" + - "Pure Java API - you don't need PowerPoint to read and write *.ppt files\r" + - "Comprehensive support of PowerPoint objects\r" + - "Rich text\r" + - "Tables\r" + - "Shapes\r" + - "Pictures\r" + - "Master slides\r" + - "Access to low level data structures" - ); - - List extends TextParagraph,?,?>> tp = box2.getTextParagraphs(); - for (int i : new byte[]{0,1,2,8}) { - tp.get(i).getTextRuns().get(0).setFontSize(28d); - } - for (int i : new byte[]{3,4,5,6,7}) { - tp.get(i).getTextRuns().get(0).setFontSize(24d); - tp.get(i).setIndentLevel(1); - } - box2.setAnchor(new Rectangle(36, 80, 648, 400)); - } - - public static void slide4(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - String[][] txt1 = { - {"Note"}, - {"This presentation was created programmatically using POI HSLF"} - }; - TableShape,?> table1 = slide.createTable(2, 1); - for (int i = 0; i < txt1.length; i++) { - for (int j = 0; j < txt1[i].length; j++) { - TableCell,?> cell = table1.getCell(i, j); - cell.setText(txt1[i][j]); - TextRun rt = cell.getTextParagraphs().get(0).getTextRuns().get(0); - rt.setFontSize(10d); - rt.setFontFamily("Arial"); - rt.setBold(true); - if(i == 0){ - rt.setFontSize(32d); - rt.setFontColor(Color.white); - cell.setFillColor(new Color(0, 153, 204)); - } else { - rt.setFontSize(28d); - cell.setFillColor(new Color(235, 239, 241)); - } - cell.setVerticalAlignment(VerticalAlignment.MIDDLE); - } - } - - DrawTableShape dts = new DrawTableShape(table1); - dts.setAllBorders(1.0, Color.black); - dts.setOutsideBorders(4.0); - - table1.setColumnWidth(0, 450); - table1.setRowHeight(0, 50); - table1.setRowHeight(1, 80); - - Dimension dim = ppt.getPageSize(); - Rectangle2D oldAnchor = table1.getAnchor(); - table1.setAnchor(new Rectangle2D.Double((dim.width-450)/2d, 100, oldAnchor.getWidth(), oldAnchor.getHeight())); - - TextBox,?> box1 = slide.createTextBox(); - box1.setHorizontalCentered(true); - box1.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(24d); - box1.setText("The source code is available at\r" + - "http://people.apache.org/~yegor/apachecon_eu08/"); - box1.setAnchor(new Rectangle(80, 356, 553, 65)); - } - - public static void slide5(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in Action - 1\rData Extraction"); - box1.setAnchor(new Rectangle(36, 21, 648, 100)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "Text from slides and notes\r" + - "Images\r" + - "Shapes and their properties (type, position in the slide, color, font, etc.)"); - box2.setAnchor(new Rectangle(36, 150, 648, 300)); - } - - public static void slide6(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in Action - 2"); - box1.setAnchor(new Rectangle(36, 20, 648, 90)); - - TextBox,?> box2 = slide.createTextBox(); - box2.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(18d); - box2.setText("Creating a simple presentation from scratch"); - box2.setAnchor(new Rectangle(170, 100, 364, 30)); - - TextBox,?> box3 = slide.createTextBox(); - TextRun rt3 = box3.getTextParagraphs().get(0).getTextRuns().get(0); - rt3.setFontFamily("Courier New"); - rt3.setFontSize(8d); - box3.setText( - "SlideShow ppt = new SlideShow();\u000b" + - "Slide slide = ppt.createSlide();\u000b" + - "\u000b" + - "TextBox box2 = new TextBox();\u000b" + - "box2.setHorizontalAlignment(TextBox.AlignCenter);\u000b" + - "box2.setVerticalAlignment(TextBox.AnchorMiddle);\u000b" + - "box2.getTextRun().setText(\"Java Code\");\u000b" + - "box2.getFill().setForegroundColor(new Color(187, 224, 227));\u000b" + - "box2.setLineColor(Color.black);\u000b" + - "box2.setLineWidth(0.75);\u000b" + - "box2.setAnchor(new Rectangle(66, 243, 170, 170));\u000b" + - "slide.addShape(box2);\u000b" + - "\u000b" + - "TextBox box3 = new TextBox();\u000b" + - "box3.setHorizontalAlignment(TextBox.AlignCenter);\u000b" + - "box3.setVerticalAlignment(TextBox.AnchorMiddle);\u000b" + - "box3.getTextRun().setText(\"*.ppt file\");\u000b" + - "box3.setLineWidth(0.75);\u000b" + - "box3.setLineColor(Color.black);\u000b" + - "box3.getFill().setForegroundColor(new Color(187, 224, 227));\u000b" + - "box3.setAnchor(new Rectangle(473, 243, 170, 170));\u000b" + - "slide.addShape(box3);\u000b" + - "\u000b" + - "AutoShape box4 = new AutoShape(ShapeTypes.Arrow);\u000b" + - "box4.getFill().setForegroundColor(new Color(187, 224, 227));\u000b" + - "box4.setLineWidth(0.75);\u000b" + - "box4.setLineColor(Color.black);\u000b" + - "box4.setAnchor(new Rectangle(253, 288, 198, 85));\u000b" + - "slide.addShape(box4);\u000b" + - "\u000b" + - "FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\u000b" + - "ppt.write(out);\u000b" + - "out.close();"); - box3.setAnchor(new Rectangle(30, 150, 618, 411)); - box3.setHorizontalCentered(true); - } - - public static void slide7(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box2 = slide.createTextBox(); - box2.setHorizontalCentered(true); - box2.setVerticalAlignment(VerticalAlignment.MIDDLE); - box2.setText("Java Code"); - box2.setFillColor(new Color(187, 224, 227)); - box2.setStrokeStyle(0.75, Color.black); - box2.setAnchor(new Rectangle(66, 243, 170, 170)); - - TextBox,?> box3 = slide.createTextBox(); - box3.setHorizontalCentered(true); - box3.setVerticalAlignment(VerticalAlignment.MIDDLE); - box3.setText("*.ppt file"); - box3.setFillColor(new Color(187, 224, 227)); - box3.setStrokeStyle(0.75, Color.black); - box3.setAnchor(new Rectangle(473, 243, 170, 170)); - - AutoShape,?> box4 = slide.createAutoShape(); - box4.setShapeType(ShapeType.RIGHT_ARROW); - box4.setFillColor(new Color(187, 224, 227)); - box4.setStrokeStyle(0.75, Color.black); - box4.setAnchor(new Rectangle(253, 288, 198, 85)); - } - - public static void slide8(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("Wait, there is more!"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "Rich text\r" + - "Tables\r" + - "Pictures (JPEG, PNG, BMP, WMF, PICT)\r" + - "Comprehensive formatting features"); - box2.setAnchor(new Rectangle(36, 126, 648, 356)); - } - - public static void slide9(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in Action - 3"); - box1.setAnchor(new Rectangle(36, 20, 648, 50)); - - TextBox,?> box2 = slide.createTextBox(); - box2.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(18d); - box2.setText("PPGraphics2D: PowerPoint Graphics2D driver"); - box2.setAnchor(new Rectangle(178, 70, 387, 30)); - - TextBox,?> box3 = slide.createTextBox(); - TextRun rt3 = box3.getTextParagraphs().get(0).getTextRuns().get(0); - rt3.setFontFamily("Courier New"); - rt3.setFontSize(8d); - box3.setText( - "//bar chart data. The first value is the bar color, the second is the width\u000b" + - "Object[] def = new Object[]{\u000b" + - " Color.yellow, new Integer(100),\u000b" + - " Color.green, new Integer(150),\u000b" + - " Color.gray, new Integer(75),\u000b" + - " Color.red, new Integer(200),\u000b" + - "};\u000b" + - "\u000b" + - "SlideShow ppt = new SlideShow();\u000b" + - "Slide slide = ppt.createSlide();\u000b" + - "\u000b" + - "ShapeGroup group = new ShapeGroup();\u000b" + - "//define position of the drawing in the slide\u000b" + - "Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300);\u000b" + - "group.setAnchor(bounds);\u000b" + - "slide.addShape(group);\u000b" + - "Graphics2D graphics = new PPGraphics2D(group);\u000b" + - "\u000b" + - "//draw a simple bar graph\u000b" + - "int x = bounds.x + 50, y = bounds.y + 50;\u000b" + - "graphics.setFont(new Font(\"Arial\", Font.BOLD, 10));\u000b" + - "for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {\u000b" + - " graphics.setColor(Color.black);\u000b" + - " int width = ((Integer)def[i+1]).intValue();\u000b" + - " graphics.drawString(\"Q\" + idx, x-20, y+20);\u000b" + - " graphics.drawString(width + \"%\", x + width + 10, y + 20);\u000b" + - " graphics.setColor((Color)def[i]);\u000b" + - " graphics.fill(new Rectangle(x, y, width, 30));\u000b" + - " y += 40;\u000b" + - "}\u000b" + - "graphics.setColor(Color.black);\u000b" + - "graphics.setFont(new Font(\"Arial\", Font.BOLD, 14));\u000b" + - "graphics.draw(bounds);\u000b" + - "graphics.drawString(\"Performance\", x + 70, y + 40);\u000b" + - "\u000b" + - "FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\u000b" + - "ppt.write(out);\u000b" + - "out.close();"); - box3.setAnchor(new Rectangle(96, 110, 499, 378)); - box3.setHorizontalCentered(true); - } - - public static void slide10(SlideShow,?> ppt) throws IOException { - //bar chart data. The first value is the bar color, the second is the width - Object[] def = new Object[]{ - Color.yellow, 100, - Color.green, 150, - Color.gray, 75, - Color.red, 200, - }; - - Slide,?> slide = ppt.createSlide(); - - GroupShape,?> group = slide.createGroup(); - //define position of the drawing in the slide - Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); - group.setAnchor(bounds); - Graphics2D graphics = new SLGraphics(group); - - //draw a simple bar graph - int x = bounds.x + 50, y = bounds.y + 50; - graphics.setFont(new Font("Arial", Font.BOLD, 10)); - for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { - graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); - graphics.drawString("Q" + idx, x-20, y+20); - graphics.drawString(width + "%", x + width + 10, y + 20); - graphics.setColor((Color)def[i]); - graphics.fill(new Rectangle(x, y, width, 30)); - y += 40; - } - graphics.setColor(Color.black); - graphics.setFont(new Font("Arial", Font.BOLD, 14)); - graphics.draw(bounds); - graphics.drawString("Performance", x + 70, y + 40); - - } - - public static void slide11(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF Development Plans"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "Support for more PowerPoint functionality\r" + - "Rendering slides into java.awt.Graphics2D\r" + - "A way to export slides into images or other formats\r" + - "Integration with Apache FOP - Formatting Objects Processor\r" + - "Transformation of XSL-FO into PPT\r" + - "PPT2PDF transcoder" - ); - - List extends TextParagraph,?,?>> tp = box2.getTextParagraphs(); - for (int i : new byte[]{0,1,3}) { - tp.get(i).getTextRuns().get(0).setFontSize(28d); - } - for (int i : new byte[]{2,4,5}) { - tp.get(i).getTextRuns().get(0).setFontSize(24d); - tp.get(i).setIndentLevel(1); - } - - box2.setAnchor(new Rectangle(36, 126, 648, 400)); - } - - public static void slide12(SlideShow,?> ppt) throws IOException { - Slide,?> slide = ppt.createSlide(); - - TextBox,?> box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.CENTER_TITLE); - box1.setText("Questions?"); - box1.setAnchor(new Rectangle(54, 167, 612, 115)); - - TextBox,?> box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.CENTER_BODY); - box2.setText( - "http://poi.apache.org/hslf/\r" + - "http://people.apache.org/~yegor"); - box2.setAnchor(new Rectangle(108, 306, 504, 138)); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java deleted file mode 100644 index 3c706e3e7..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextBox; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; - -/** - * How to create a single-level bulleted list - * and change some of the bullet attributes - * - * @author Yegor Kozlov - */ -public final class BulletsDemo { - - public static void main(String[] args) throws Exception { - - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - - HSLFTextBox shape = new HSLFTextBox(); - HSLFTextParagraph rt = shape.getTextParagraphs().get(0); - rt.getTextRuns().get(0).setFontSize(42d); - rt.setBullet(true); - rt.setIndent(0d); //bullet offset - rt.setLeftMargin(50d); //text offset (should be greater than bullet offset) - rt.setBulletChar('\u263A'); //bullet character - shape.setText( - "January\r" + - "February\r" + - "March\r" + - "April"); - slide.addShape(shape); - - shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide - slide.addShape(shape); - - FileOutputStream out = new FileOutputStream("bullets.ppt"); - ppt.write(out); - out.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java deleted file mode 100644 index fc25afae5..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hslf.usermodel.HSLFHyperlink; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextBox; - -/** - * Demonstrates how to create hyperlinks in PowerPoint presentations - */ -public abstract class CreateHyperlink { - - public static void main(String[] args) throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slideA = ppt.createSlide(); - ppt.createSlide(); - HSLFSlide slideC = ppt.createSlide(); - - // link to a URL - HSLFTextBox textBox1 = slideA.createTextBox(); - textBox1.setText("Apache POI"); - textBox1.setAnchor(new Rectangle(100, 100, 200, 50)); - - HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink(); - link1.linkToUrl("http://www.apache.org"); - link1.setLabel(textBox1.getText()); - - // link to another slide - HSLFTextBox textBox2 = slideA.createTextBox(); - textBox2.setText("Go to slide #3"); - textBox2.setAnchor(new Rectangle(100, 300, 200, 50)); - - HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink(); - link2.linkToSlide(slideC); - - FileOutputStream out = new FileOutputStream("hyperlink.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java deleted file mode 100644 index 514c01ba0..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; - -import org.apache.poi.hslf.model.OLEShape; -import org.apache.poi.hslf.usermodel.HSLFObjectData; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFPictureShape; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSoundData; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Range; - -/** - * Demonstrates how you can extract misc embedded data from a ppt file - * - * @author Yegor Kozlov - */ -public final class DataExtraction { - - public static void main(String args[]) throws Exception { - - if (args.length == 0) { - usage(); - return; - } - - FileInputStream is = new FileInputStream(args[0]); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - //extract all sound files embedded in this presentation - HSLFSoundData[] sound = ppt.getSoundData(); - for (int i = 0; i < sound.length; i++) { - String type = sound[i].getSoundType(); //*.wav - String name = sound[i].getSoundName(); //typically file name - byte[] data = sound[i].getData(); //raw bytes - - //save the sound on disk - FileOutputStream out = new FileOutputStream(name + type); - out.write(data); - out.close(); - } - - int oleIdx=-1, picIdx=-1; - for (HSLFSlide slide : ppt.getSlides()) { - //extract embedded OLE documents - for (HSLFShape shape : slide.getShapes()) { - if (shape instanceof OLEShape) { - oleIdx++; - OLEShape ole = (OLEShape) shape; - HSLFObjectData data = ole.getObjectData(); - String name = ole.getInstanceName(); - if ("Worksheet".equals(name)) { - - //read xls - @SuppressWarnings({ "unused", "resource" }) - HSSFWorkbook wb = new HSSFWorkbook(data.getData()); - - } else if ("Document".equals(name)) { - HWPFDocument doc = new HWPFDocument(data.getData()); - //read the word document - Range r = doc.getRange(); - for(int k = 0; k < r.numParagraphs(); k++) { - Paragraph p = r.getParagraph(k); - System.out.println(p.text()); - } - - //save on disk - FileOutputStream out = new FileOutputStream(name + "-("+(oleIdx)+").doc"); - doc.write(out); - out.close(); - } else { - FileOutputStream out = new FileOutputStream(ole.getProgID() + "-"+(oleIdx+1)+".dat"); - InputStream dis = data.getData(); - byte[] chunk = new byte[2048]; - int count; - while ((count = dis.read(chunk)) >= 0) { - out.write(chunk,0,count); - } - is.close(); - out.close(); - } - } - - //Pictures - else if (shape instanceof HSLFPictureShape) { - picIdx++; - HSLFPictureShape p = (HSLFPictureShape) shape; - HSLFPictureData data = p.getPictureData(); - String ext = data.getType().extension; - FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext); - out.write(data.getData()); - out.close(); - } - } - - } - } - - private static void usage(){ - System.out.println("Usage: DataExtraction ppt"); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java deleted file mode 100644 index 53cd53edc..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.io.FileOutputStream; - -import org.apache.poi.hslf.model.PPGraphics2D; -import org.apache.poi.hslf.usermodel.HSLFGroupShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; - -/** - * Demonstrates how to draw into a slide using the HSLF Graphics2D driver. - * - * @author Yegor Kozlov - */ -public final class Graphics2DDemo { - - /** - * A simple bar chart demo - */ - public static void main(String[] args) throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(); - - //bar chart data. The first value is the bar color, the second is the width - Object[] def = new Object[]{ - Color.yellow, 40, - Color.green, 60, - Color.gray, 30, - Color.red, 80, - }; - - HSLFSlide slide = ppt.createSlide(); - - HSLFGroupShape group = new HSLFGroupShape(); - //define position of the drawing in the slide - Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); - group.setAnchor(bounds); - group.setInteriorAnchor(new java.awt.Rectangle(0, 0, 100, 100)); - slide.addShape(group); - Graphics2D graphics = new PPGraphics2D(group); - - //draw a simple bar graph - int x = 10, y = 10; - graphics.setFont(new Font("Arial", Font.BOLD, 10)); - for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { - graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); - graphics.drawString("Q" + idx, x-5, y+10); - graphics.drawString(width + "%", x + width+3, y + 10); - graphics.setColor((Color)def[i]); - graphics.fill(new Rectangle(x, y, width, 10)); - y += 15; - } - graphics.setColor(Color.black); - graphics.setFont(new Font("Arial", Font.BOLD, 14)); - graphics.draw(group.getInteriorAnchor()); - graphics.drawString("Performance", x + 30, y + 10); - - FileOutputStream out = new FileOutputStream("hslf-graphics.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java deleted file mode 100644 index b37aed2df..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; - -/** - * Demonstrates how to set headers / footers - */ -public abstract class HeadersFootersDemo { - public static void main(String[] args) throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); - slideHeaders.setFootersText("Created by POI-HSLF"); - slideHeaders.setSlideNumberVisible(true); - slideHeaders.setDateTimeText("custom date time"); - - HeadersFooters notesHeaders = ppt.getNotesHeadersFooters(); - notesHeaders.setFootersText("My notes footers"); - notesHeaders.setHeaderText("My notes header"); - - ppt.createSlide(); - - FileOutputStream out = new FileOutputStream("headers_footers.ppt"); - ppt.write(out); - out.close(); - - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java b/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java deleted file mode 100644 index 812429295..000000000 --- a/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.io.FileInputStream; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hslf.usermodel.HSLFHyperlink; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSimpleShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.hslf.usermodel.HSLFTextRun; - -/** - * Demonstrates how to read hyperlinks from a presentation - * - * @author Yegor Kozlov - */ -public final class Hyperlinks { - - public static void main(String[] args) throws Exception { - for (int i = 0; i < args.length; i++) { - FileInputStream is = new FileInputStream(args[i]); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - for (HSLFSlide slide : ppt.getSlides()) { - System.out.println("\nslide " + slide.getSlideNumber()); - - // read hyperlinks from the slide's text runs - System.out.println("- reading hyperlinks from the text runs"); - for (List- * Excel comment is a kind of a text shape, - * so inserting a comment is very similar to placing a text box in a worksheet - *
- * - * @author Yegor Kozlov - */ -public class CellComments { - - public static void main(String[] args) throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF"); - - // Create the drawing patriarch. This is the top level container for all shapes including cell comments. - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - - //create a cell in row 3 - HSSFCell cell1 = sheet.createRow(3).createCell(1); - cell1.setCellValue(new HSSFRichTextString("Hello, World")); - - //anchor defines size and position of the comment in worksheet - HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5)); - - // set text in the comment - comment1.setString(new HSSFRichTextString("We can set comments in POI")); - - //set comment author. - //you can see it in the status bar when moving mouse over the commented cell - comment1.setAuthor("Apache Software Foundation"); - - // The first way to assign comment to a cell is via HSSFCell.setCellComment method - cell1.setCellComment(comment1); - - //create another cell in row 6 - HSSFCell cell2 = sheet.createRow(6).createCell(1); - cell2.setCellValue(36.6); - - - HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11)); - //modify background color of the comment - comment2.setFillColor(204, 236, 255); - - HSSFRichTextString string = new HSSFRichTextString("Normal body temperature"); - - //apply custom font to the text in the comment - HSSFFont font = wb.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short)10); - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - font.setColor(HSSFColor.RED.index); - string.applyFont(font); - - comment2.setString(string); - comment2.setVisible(true); //by default comments are hidden. This one is always visible. - - comment2.setAuthor("Bill Gates"); - - /** - * The second way to assign comment to a cell is to implicitly specify its row and column. - * Note, it is possible to set row and column of a non-existing cell. - * It works, the comment is visible. - */ - comment2.setRow(6); - comment2.setColumn(1); - - FileOutputStream out = new FileOutputStream("poi_comment.xls"); - wb.write(out); - out.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java b/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java deleted file mode 100644 index 3e31d11f2..000000000 --- a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; - -public class CellTypes { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(2); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(new Date()); - row.createCell(2).setCellValue("a string"); - row.createCell(3).setCellValue(true); - row.createCell(4).setCellType(CellType.ERROR); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java b/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java deleted file mode 100644 index d2141b050..000000000 --- a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Illustrates how to create cell values. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class CreateCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(0); - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(0); - cell.setCellValue(1); - - // Or do it on one line. - row.createCell(1).setCellValue(1.2); - row.createCell(2).setCellValue("This is a string"); - row.createCell(3).setCellValue(true); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java b/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java deleted file mode 100644 index 746fd536b..000000000 --- a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -/** - * An example on how to cells with dates. The important thing to note - * about dates is that they are really normal numeric cells that are - * formatted specially. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class CreateDateCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(0); - - // Create a cell and put a date value in it. The first cell is not styled as a date. - HSSFCell cell = row.createCell(0); - cell.setCellValue(new Date()); - - // we style the second cell as a date (and time). It is important to create a new cell style from the workbook - // otherwise you can end up modifying the built in style and effecting not only this cell but other cells. - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); - cell = row.createCell(1); - cell.setCellValue(new Date()); - cell.setCellStyle(cellStyle); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmeddedObjects.java b/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmeddedObjects.java deleted file mode 100644 index 9af41063e..000000000 --- a/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmeddedObjects.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileInputStream; -import java.util.Iterator; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.hssf.usermodel.HSSFObjectData; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * Demonstrates how you can extract embedded data from a .xls file - */ -public class EmeddedObjects { - @SuppressWarnings("unused") - public static void main(String[] args) throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0])); - HSSFWorkbook workbook = new HSSFWorkbook(fs); - for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) { - //the OLE2 Class Name of the object - String oleName = obj.getOLE2ClassName(); - if (oleName.equals("Worksheet")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false); - //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets()); - embeddedWorkbook.close(); - } else if (oleName.equals("Document")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HWPFDocument embeddedWordDocument = new HWPFDocument(dn); - //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text()); - } else if (oleName.equals("Presentation")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HSLFSlideShow embeddedPowerPointDocument = new HSLFSlideShow(new HSLFSlideShowImpl(dn)); - //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length); - } else { - if(obj.hasDirectoryEntry()){ - // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - for (Iterator"); - } - - public void closeParagraph () - throws IOException - { - _out.write ("
"); - } - - public void openSource () - throws IOException - { - _out.write (""); - } - - - public static void main(String[] args) throws IOException { - InputStream is = new FileInputStream(args[0]); - OutputStream out = new FileOutputStream("test.xml"); - try { - new Word2Forrest(new HWPFDocument(is), out); - } finally { - out.close(); - is.close(); - } - } -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java deleted file mode 100644 index 247684d1b..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.*; -import org.apache.poi.poifs.filesystem.*; - -/** - *Describes the most important (whatever that is) features of a - * {@link POIFSDocument}.
- */ -public class DocumentDescriptor -{ - String name; - POIFSDocumentPath path; - DocumentInputStream stream; - - int size; - byte[] bytes; - - - /** - *Creates a {@link DocumentDescriptor}.
- * - * @param name The stream's name. - * - * @param path The stream's path in the POI filesystem hierarchy. - * - * @param stream The stream. - * - * @param nrOfBytes The maximum number of bytes to display in a - * dump starting at the beginning of the stream. - */ - public DocumentDescriptor(final String name, - final POIFSDocumentPath path, - final DocumentInputStream stream, - final int nrOfBytes) - { - this.name = name; - this.path = path; - this.stream = stream; - try - { - size = stream.available(); - if (stream.markSupported()) - { - stream.mark(nrOfBytes); - final byte[] b = new byte[nrOfBytes]; - final int read = stream.read(b, 0, Math.min(size, b.length)); - bytes = new byte[read]; - System.arraycopy(b, 0, bytes, 0, read); - stream.reset(); - } - } - catch (IOException ex) - { - System.out.println(ex); - } - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java deleted file mode 100644 index 698aab35e..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; -import javax.swing.tree.*; - -import org.apache.poi.util.HexDump; - -/** - *{@link TreeCellRenderer} for a {@link DocumentDescriptor}. The - * renderer is extremly rudimentary since displays only the document's - * name, its size and its fist few bytes.
- */ -public class DocumentDescriptorRenderer extends DefaultTreeCellRenderer -{ - - public Component getTreeCellRendererComponent(final JTree tree, - final Object value, - final boolean selectedCell, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasCellFocus) - { - final DocumentDescriptor d = (DocumentDescriptor) - ((DefaultMutableTreeNode) value).getUserObject(); - final JPanel p = new JPanel(); - final JTextArea text = new JTextArea(); - text.append(renderAsString(d)); - text.setFont(new Font("Monospaced", Font.PLAIN, 10)); - p.add(text); - if (selectedCell) { - Util.invert(text); - } - return p; - } - - - /** - *Renders {@link DocumentDescriptor} as a string.
- */ - protected String renderAsString(final DocumentDescriptor d) - { - final StringBuilder b = new StringBuilder(); - b.append("Name: "); - b.append(d.name); - b.append(" "); - b.append(HexDump.toHex(d.name)); - b.append("\n"); - - b.append("Size: "); - b.append(d.size); - b.append(" bytes\n"); - - b.append("First bytes: "); - b.append(HexDump.toHex(d.bytes)); - - return b.toString(); - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java deleted file mode 100644 index 917c0b057..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java +++ /dev/null @@ -1,142 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; -import javax.swing.tree.*; -import java.util.*; - -/** - *This is a {@link TreeCellRenderer} implementation which is able - * to render arbitrary objects. The {@link ExtendableTreeCellRenderer} - * does not do the rendering itself but instead dispatches to - * class-specific renderers. A class/renderer pair must be registered - * using the {@link #register} method. If a class has no registered - * renderer, the renderer of its closest superclass is used. Since the - * {@link ExtendableTreeCellRenderer} always has a default renderer - * for the {@link Object} class, rendering is always possible. The - * default {@link Object} renderer can be replaced by another renderer - * but it cannot be unregistered.
- */ -public class ExtendableTreeCellRenderer implements TreeCellRenderer -{ - - /** - *Maps classes to renderers.
- */ - protected MapRegisters a renderer for a class.
- **/ - public void register(final Class> c, final TreeCellRenderer renderer) - { - renderers.put(c, renderer); - } - - - - /** - *Unregisters a renderer for a class. The renderer for the - * {@link Object} class cannot be unregistered.
- */ - public void unregister(final Class> c) - { - if (c == Object.class) - throw new IllegalArgumentException - ("Renderer for Object cannot be unregistered."); - renderers.put(c, null); - } - - - - /** - *Renders an object in a tree cell depending of the object's - * class.
- * - * @see TreeCellRenderer#getTreeCellRendererComponent - */ - public Component getTreeCellRendererComponent - (final JTree tree, final Object value, final boolean selected, - final boolean expanded, final boolean leaf, final int row, - final boolean hasFocus) - { - final String NULL = "null"; - TreeCellRenderer r; - Object userObject; - if (value == null) - userObject = NULL; - else - { - userObject = ((DefaultMutableTreeNode) value).getUserObject(); - if (userObject == null) - userObject = NULL; - } - r = findRenderer(userObject.getClass()); - return r.getTreeCellRendererComponent - (tree, value, selected, expanded, leaf, row, - hasFocus); - } - - - - /** - *Find the renderer for the specified class.
- */ - protected TreeCellRenderer findRenderer(final Class> c) - { - final TreeCellRenderer r = renderers.get(c); - if (r != null) - /* The class has a renderer. */ - return r; - - /* The class has no renderer, try the superclass, if any. */ - final Class> superclass = c.getSuperclass(); - if (superclass != null) { - return findRenderer(superclass); - } - return null; - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java deleted file mode 100644 index d1fa1727c..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.FileInputStream; -import java.io.IOException; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.MutableTreeNode; - -import org.apache.poi.poifs.eventfilesystem.POIFSReader; - -/** - *The main class of the POI Browser. It shows the structure of POI - * filesystems (Microsoft Office documents) in a {@link - * JTree}. Specify their filenames on the command line!
- * - * @see POIFSReader - */ -@SuppressWarnings("serial") -public class POIBrowser extends JFrame -{ - - /** - *The tree's root node must be visible to all methods.
- */ - protected MutableTreeNode rootNode; - - - - /** - *Takes a bunch of file names as command line parameters, - * opens each of them as a POI filesystem and displays their - * internal structures in a {@link JTree}.
- */ - public static void main(String[] args) - { - new POIBrowser().run(args); - } - - - - protected void run(String[] args) - { - addWindowListener(new WindowAdapter() - { - public void windowClosing(WindowEvent e) - { - System.exit(0); - } - }); - - /* Create the tree model with a root node. The latter is - * invisible but it must be present because a tree model - * always needs a root. */ - rootNode = new DefaultMutableTreeNode("POI Filesystems"); - DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); - - /* Create the tree UI element. */ - final JTree treeUI = new JTree(treeModel); - getContentPane().add(new JScrollPane(treeUI)); - - /* Add the POI filesystems to the tree. */ - int displayedFiles = 0; - for (int i = 0; i < args.length; i++) - { - final String filename = args[i]; - try { - FileInputStream fis = new FileInputStream(filename); - POIFSReader r = new POIFSReader(); - r.registerListener(new TreeReaderListener(filename, rootNode)); - r.read(fis); - fis.close(); - displayedFiles++; - } catch (IOException ex) { - System.err.println(filename + ": " + ex); - } catch (Exception t) { - System.err.println("Unexpected exception while reading \"" + - filename + "\":"); - t.printStackTrace(System.err); - } - } - - /* Exit if there is no file to display (none specified or only - * files with problems). */ - if (displayedFiles == 0) - { - System.out.println("No POI filesystem(s) to display."); - System.exit(0); - } - - /* Make the tree UI element visible. */ - treeUI.setRootVisible(true); - treeUI.setShowsRootHandles(true); - ExtendableTreeCellRenderer etcr = new ExtendableTreeCellRenderer(); - etcr.register(DocumentDescriptor.class, - new DocumentDescriptorRenderer()); - etcr.register(PropertySetDescriptor.class, - new PropertySetDescriptorRenderer()); - treeUI.setCellRenderer(etcr); - setSize(600, 450); - setTitle("POI Browser 0.09"); - setVisible(true); - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java deleted file mode 100644 index f9658ae03..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *Describes the most important (whatever that is) features of a - * stream containing a {@link PropertySet}.
- */ -public class PropertySetDescriptor extends DocumentDescriptor -{ - - protected PropertySet propertySet; - - /** - *Returns this {@link PropertySetDescriptor}'s {@link - * PropertySet}.
- */ - public PropertySet getPropertySet() - { - return propertySet; - } - - - - /** - *Creates a {@link PropertySetDescriptor} by reading a {@link - * PropertySet} from a {@link DocumentInputStream}.
- * - * @param name The stream's name. - * - * @param path The stream's path in the POI filesystem hierarchy. - * - * @param stream The stream. - * - * @param nrOfBytesToDump The maximum number of bytes to display in a - * dump starting at the beginning of the stream. - */ - public PropertySetDescriptor(final String name, - final POIFSDocumentPath path, - final DocumentInputStream stream, - final int nrOfBytesToDump) - throws NoPropertySetStreamException, - MarkUnsupportedException, UnsupportedEncodingException, - IOException - { - super(name, path, stream, nrOfBytesToDump); - propertySet = PropertySetFactory.create(stream); - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java deleted file mode 100644 index 085f2db6d..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.Iterator; -import java.util.List; - -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; - -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.util.HexDump; - -/** - *Renders a {@link PropertySetDescriptor} by more or less dumping - * the stuff into a {@link JTextArea}.
- */ -public class PropertySetDescriptorRenderer extends DocumentDescriptorRenderer -{ - - public Component getTreeCellRendererComponent(final JTree tree, - final Object value, - final boolean selectedCell, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasCellFocus) - { - final PropertySetDescriptor d = (PropertySetDescriptor) - ((DefaultMutableTreeNode) value).getUserObject(); - final PropertySet ps = d.getPropertySet(); - final JPanel p = new JPanel(); - final JTextArea text = new JTextArea(); - text.setBackground(new Color(200, 255, 200)); - text.setFont(new Font("Monospaced", Font.PLAIN, 10)); - text.append(renderAsString(d)); - text.append("\nByte order: "); - text.append(HexDump.toHex((short) ps.getByteOrder())); - text.append("\nFormat: "); - text.append(HexDump.toHex((short) ps.getFormat())); - text.append("\nOS version: "); - text.append(HexDump.toHex(ps.getOSVersion())); - text.append("\nClass ID: "); - text.append(HexDump.toHex(ps.getClassID().getBytes())); - text.append("\nSection count: " + ps.getSectionCount()); - text.append(sectionsToString(ps.getSections())); - p.add(text); - - if (ps instanceof SummaryInformation) - { - /* Use the convenience methods. */ - final SummaryInformation si = (SummaryInformation) ps; - text.append("\n"); - text.append("\nTitle: " + si.getTitle()); - text.append("\nSubject: " + si.getSubject()); - text.append("\nAuthor: " + si.getAuthor()); - text.append("\nKeywords: " + si.getKeywords()); - text.append("\nComments: " + si.getComments()); - text.append("\nTemplate: " + si.getTemplate()); - text.append("\nLast Author: " + si.getLastAuthor()); - text.append("\nRev. Number: " + si.getRevNumber()); - text.append("\nEdit Time: " + si.getEditTime()); - text.append("\nLast Printed: " + si.getLastPrinted()); - text.append("\nCreate Date/Time: " + si.getCreateDateTime()); - text.append("\nLast Save Date/Time: " + si.getLastSaveDateTime()); - text.append("\nPage Count: " + si.getPageCount()); - text.append("\nWord Count: " + si.getWordCount()); - text.append("\nChar Count: " + si.getCharCount()); - // text.append("\nThumbnail: " + si.getThumbnail()); - text.append("\nApplication Name: " + si.getApplicationName()); - text.append("\nSecurity: " + si.getSecurity()); - } - - if (selectedCell) - Util.invert(text); - return p; - } - - - - /** - *Returns a string representation of a list of {@link - * Section}s.
- */ - protected String sectionsToString(final ListReturns a string representation of a {@link Section}.
- * @param s the section - * @param name the section's name - * @return a string representation of the {@link Section} - */ - protected String toString(final Section s, final String name) - { - final StringBuffer b = new StringBuffer(); - b.append("\n" + name + " Format ID: "); - b.append(HexDump.toHex(s.getFormatID().getBytes())); - b.append("\n" + name + " Offset: " + s.getOffset()); - b.append("\n" + name + " Section size: " + s.getSize()); - b.append("\n" + name + " Property count: " + s.getPropertyCount()); - - final Property[] properties = s.getProperties(); - for (int i = 0; i < properties.length; i++) - { - final Property p = properties[i]; - final long id = p.getID(); - final long type = p.getType(); - final Object value = p.getValue(); - b.append('\n'); - b.append(name); - b.append(", Name: "); - b.append(id); - b.append(" ("); - b.append(s.getPIDString(id)); - b.append("), Type: "); - b.append(type); - b.append(", Value: "); - if (value instanceof byte[]) { - byte[] buf = new byte[4]; - System.arraycopy(value, 0, buf, 0, 4); - b.append(HexDump.toHex(buf)); - b.append(' '); - System.arraycopy(value, ((byte[])value).length - 4, buf, 0, 4); - } else if (value != null) { - b.append(value.toString()); - } else { - b.append("null"); - } - } - return b.toString(); - } - -} diff --git a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java b/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java deleted file mode 100644 index 3174610ca..000000000 --- a/trunk/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java +++ /dev/null @@ -1,216 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.util.HashMap; -import java.util.Map; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.MutableTreeNode; - -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *Organizes document information in a tree model in order to be - * e.g. displayed in a Swing {@link javax.swing.JTree}. An instance of this - * class is created with a root tree node ({@link MutableTreeNode}) and - * registered as a {@link POIFSReaderListener} with a {@link - * org.apache.poi.poifs.eventfilesystem.POIFSReader}. While the latter processes - * a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for - * each document it has been registered for. This method appends the document it - * processes at the appropriate position into the tree rooted at the - * above mentioned root tree node.
- * - *The root tree node should be the root tree node of a {@link - * javax.swing.tree.TreeModel}.
- * - *A top-level element in the tree model, i.e. an immediate child - * node of the root node, describes a POI filesystem as such. It is - * suggested to use the file's name (as seen by the operating system) - * but it could be any other string.
- * - *The value of a tree node is a {@link DocumentDescriptor}. Unlike - * a {@link org.apache.poi.poifs.filesystem.POIFSDocument} which may be as heavy - * as many megabytes, an instance of {@link DocumentDescriptor} is a - * light-weight object and contains only some meta-information about a - * document.
- */ -public class TreeReaderListener implements POIFSReaderListener -{ - - /** - *The tree's root node. POI filesystems get attached to this - * node as children.
- */ - protected MutableTreeNode rootNode; - - /** - *Maps filenames and POI document paths to their associated - * tree nodes.
- */ - protected Map