fix eclipse warnings - close resources / type generics

cleanup sources - add parenthesis to statements

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1778955 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2017-01-15 23:08:47 +00:00
parent e436060f24
commit a7706b3fdf
38 changed files with 703 additions and 541 deletions

View File

@ -269,7 +269,7 @@ public class AddDimensionedImage {
* to the resizeBehaviour * to the resizeBehaviour
* parameter. * parameter.
*/ */
public void addImageToSheet(String cellNumber, Sheet sheet, Drawing drawing, public void addImageToSheet(String cellNumber, Sheet sheet, Drawing<?> drawing,
URL imageFile, double reqImageWidthMM, double reqImageHeightMM, URL imageFile, double reqImageWidthMM, double reqImageHeightMM,
int resizeBehaviour) throws IOException, IllegalArgumentException { int resizeBehaviour) throws IOException, IllegalArgumentException {
// Convert the String into column and row indices then chain the // Convert the String into column and row indices then chain the
@ -329,7 +329,7 @@ public class AddDimensionedImage {
* it is of a type that cannot * it is of a type that cannot
* currently be added to the worksheet. * currently be added to the worksheet.
*/ */
public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing, public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing<?> drawing,
URL imageFile, double reqImageWidthMM, double reqImageHeightMM, URL imageFile, double reqImageWidthMM, double reqImageHeightMM,
int resizeBehaviour) throws IOException, int resizeBehaviour) throws IOException,
IllegalArgumentException { IllegalArgumentException {

View File

@ -16,13 +16,22 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.ss.usermodel.*; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.FileOutputStream;
/** /**
* Demonstrates how to work with excel cell comments. * Demonstrates how to work with excel cell comments.
* *
@ -44,7 +53,7 @@ public class CellComments {
Cell cell1 = sheet.createRow(3).createCell(5); Cell cell1 = sheet.createRow(3).createCell(5);
cell1.setCellValue("F4"); cell1.setCellValue("F4");
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = factory.createClientAnchor(); ClientAnchor anchor = factory.createClientAnchor();
@ -63,7 +72,7 @@ public class CellComments {
Font font = wb.createFont(); Font font = wb.createFont();
font.setFontName("Arial"); font.setFontName("Arial");
font.setFontHeightInPoints((short)14); font.setFontHeightInPoints((short)14);
font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setBold(true);
font.setColor(IndexedColors.RED.getIndex()); font.setColor(IndexedColors.RED.getIndex());
str2.applyFont(font); str2.applyFont(font);

View File

@ -17,20 +17,23 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* Demonstrates how to insert pictures in a SpreadsheetML document * Demonstrates how to insert pictures in a SpreadsheetML document
*
* @author Yegor Kozlov
*/ */
public class WorkingWithPictures { public class WorkingWithPictures {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
@ -50,7 +53,7 @@ public class WorkingWithPictures {
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
//create drawing //create drawing
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
//add a picture shape //add a picture shape
ClientAnchor anchor = helper.createClientAnchor(); ClientAnchor anchor = helper.createClientAnchor();
@ -63,7 +66,10 @@ public class WorkingWithPictures {
//save workbook //save workbook
String file = "picture.xls"; String file = "picture.xls";
if(wb instanceof XSSFWorkbook) file += "x"; // NOSONAR if(wb instanceof XSSFWorkbook)
{
file += "x"; // NOSONAR
}
OutputStream fileOut = new FileOutputStream(file); OutputStream fileOut = new FileOutputStream(file);
try { try {
wb.write(fileOut); wb.write(fileOut);

View File

@ -21,6 +21,7 @@ import static org.junit.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.hdgf.HDGFDiagram; import org.apache.poi.hdgf.HDGFDiagram;
@ -32,7 +33,7 @@ import org.junit.Test;
public class HDGFFileHandler extends POIFSFileHandler { public class HDGFFileHandler extends POIFSFileHandler {
@Override @Override
public void handleFile(InputStream stream) throws Exception { public void handleFile(InputStream stream) throws IOException {
POIFSFileSystem poifs = new POIFSFileSystem(stream); POIFSFileSystem poifs = new POIFSFileSystem(stream);
HDGFDiagram diagram = new HDGFDiagram(poifs); HDGFDiagram diagram = new HDGFDiagram(poifs);
Stream[] topLevelStreams = diagram.getTopLevelStreams(); Stream[] topLevelStreams = diagram.getTopLevelStreams();
@ -44,7 +45,7 @@ public class HDGFFileHandler extends POIFSFileHandler {
TrailerStream trailerStream = diagram.getTrailerStream(); TrailerStream trailerStream = diagram.getTrailerStream();
assertNotNull(trailerStream); assertNotNull(trailerStream);
assertTrue(trailerStream.getPointer().getLength() >= 0); assertTrue(trailerStream.getPointer().getLength() >= 0);
diagram.close();
poifs.close(); poifs.close();
// writing is not yet implemented... handlePOIDocument(diagram); // writing is not yet implemented... handlePOIDocument(diagram);

View File

@ -161,7 +161,7 @@ public class OldExcelExtractor implements Closeable {
prepare(); prepare();
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
if (args.length < 1) { if (args.length < 1) {
System.err.println("Use:"); System.err.println("Use:");
System.err.println(" OldExcelExtractor <filename>"); System.err.println(" OldExcelExtractor <filename>");
@ -173,8 +173,9 @@ public class OldExcelExtractor implements Closeable {
} }
private void prepare() { private void prepare() {
if (! ris.hasNextRecord()) if (! ris.hasNextRecord()) {
throw new IllegalArgumentException("File contains no records!"); throw new IllegalArgumentException("File contains no records!");
}
ris.nextRecord(); ris.nextRecord();
// Work out what version we're dealing with // Work out what version we're dealing with

View File

@ -19,11 +19,11 @@ package org.apache.poi.ss.usermodel;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.Map;
import org.apache.poi.ss.formula.FormulaParseException; import org.apache.poi.ss.formula.FormulaParseException;
import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Internal;
import org.apache.poi.util.Removal; import org.apache.poi.util.Removal;
/** /**
@ -47,6 +47,7 @@ public interface Cell {
* @see #getCellType() * @see #getCellType()
* @deprecated POI 3.15 beta 3. Use {@link CellType#NUMERIC} instead. * @deprecated POI 3.15 beta 3. Use {@link CellType#NUMERIC} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
int CELL_TYPE_NUMERIC = 0; //CellType.NUMERIC.getCode(); int CELL_TYPE_NUMERIC = 0; //CellType.NUMERIC.getCode();
@ -56,6 +57,7 @@ public interface Cell {
* @see #getCellType() * @see #getCellType()
* @deprecated POI 3.15 beta 3. Use {@link CellType#STRING} instead. * @deprecated POI 3.15 beta 3. Use {@link CellType#STRING} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
int CELL_TYPE_STRING = 1; //CellType.STRING.getCode(); int CELL_TYPE_STRING = 1; //CellType.STRING.getCode();
@ -65,6 +67,7 @@ public interface Cell {
* @see #getCellType() * @see #getCellType()
* @deprecated POI 3.15 beta 3. Use {@link CellType#FORMULA} instead. * @deprecated POI 3.15 beta 3. Use {@link CellType#FORMULA} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
int CELL_TYPE_FORMULA = 2; //CellType.FORMULA.getCode(); int CELL_TYPE_FORMULA = 2; //CellType.FORMULA.getCode();
@ -74,6 +77,7 @@ public interface Cell {
* @see #getCellType() * @see #getCellType()
* @deprecated POI 3.15 beta 3. Use {@link CellType#BLANK} instead. * @deprecated POI 3.15 beta 3. Use {@link CellType#BLANK} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
int CELL_TYPE_BLANK = 3; //CellType.BLANK.getCode(); int CELL_TYPE_BLANK = 3; //CellType.BLANK.getCode();
@ -83,6 +87,7 @@ public interface Cell {
* @see #getCellType() * @see #getCellType()
* @deprecated POI 3.15 beta 3. Use {@link CellType#BOOLEAN} instead. * @deprecated POI 3.15 beta 3. Use {@link CellType#BOOLEAN} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
int CELL_TYPE_BOOLEAN = 4; //CellType.BOOLEAN.getCode(); int CELL_TYPE_BOOLEAN = 4; //CellType.BOOLEAN.getCode();
@ -92,6 +97,7 @@ public interface Cell {
* @see #getCellType() * @see #getCellType()
* @deprecated POI 3.15 beta 3. Use {@link CellType#ERROR} instead. * @deprecated POI 3.15 beta 3. Use {@link CellType#ERROR} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
int CELL_TYPE_ERROR = 5; //CellType.ERROR.getCode(); int CELL_TYPE_ERROR = 5; //CellType.ERROR.getCode();
@ -143,6 +149,7 @@ public interface Cell {
* @see CellType#ERROR * @see CellType#ERROR
* @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead. * @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead.
*/ */
@Deprecated
@Removal(version="4.0") @Removal(version="4.0")
void setCellType(int cellType); void setCellType(int cellType);
/** /**
@ -169,6 +176,7 @@ public interface Cell {
* @return the cell type * @return the cell type
* @deprecated POI 3.15. Will return a {@link CellType} enum in the future. * @deprecated POI 3.15. Will return a {@link CellType} enum in the future.
*/ */
@Deprecated
int getCellType(); int getCellType();
/** /**
@ -192,6 +200,7 @@ public interface Cell {
* on the cached value of the formula * on the cached value of the formula
* @deprecated 3.15. Will return a {@link CellType} enum in the future. * @deprecated 3.15. Will return a {@link CellType} enum in the future.
*/ */
@Deprecated
int getCachedFormulaResultType(); int getCachedFormulaResultType();
/** /**

View File

@ -972,7 +972,7 @@ public interface Sheet extends Iterable<Row> {
* *
* @return a SpreadsheetML drawing * @return a SpreadsheetML drawing
*/ */
Drawing getDrawingPatriarch(); Drawing<?> getDrawingPatriarch();
/** /**
* Creates the top-level drawing patriarch. * Creates the top-level drawing patriarch.
@ -982,7 +982,7 @@ public interface Sheet extends Iterable<Row> {
* *
* @return The new drawing patriarch. * @return The new drawing patriarch.
*/ */
Drawing createDrawingPatriarch(); Drawing<?> createDrawingPatriarch();
/** /**

View File

@ -33,7 +33,6 @@ import org.apache.poi.ss.usermodel.CellRange;
import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataValidation; import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationHelper; import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Footer; import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.Header; import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.PrintSetup;
@ -51,6 +50,7 @@ import org.apache.poi.util.Removal;
import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFComment; import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFDataValidation; import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFHyperlink; import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetFormatPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetFormatPr;
@ -207,8 +207,9 @@ public class SXSSFSheet implements Sheet
@Override @Override
public int getFirstRowNum() public int getFirstRowNum()
{ {
if(_writer.getNumberOfFlushedRows() > 0) if(_writer.getNumberOfFlushedRows() > 0) {
return _writer.getLowestIndexOfFlushedRows(); return _writer.getLowestIndexOfFlushedRows();
}
return _rows.size() == 0 ? 0 : _rows.firstKey(); return _rows.size() == 0 ? 0 : _rows.firstKey();
} }
@ -875,6 +876,7 @@ public class SXSSFSheet implements Sheet
* @param denominator The denominator for the zoom magnification. * @param denominator The denominator for the zoom magnification.
* @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead. * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead.
*/ */
@Deprecated
@Removal(version="3.16") @Removal(version="3.16")
@Override @Override
public void setZoom(int numerator, int denominator) public void setZoom(int numerator, int denominator)
@ -1293,7 +1295,9 @@ public class SXSSFSheet implements Sheet
int level = row.getOutlineLevel() + 1; int level = row.getOutlineLevel() + 1;
row.setOutlineLevel(level); row.setOutlineLevel(level);
if(level > outlineLevelRow) outlineLevelRow = level; if(level > outlineLevelRow) {
outlineLevelRow = level;
}
} }
setWorksheetOutlineLevelRow(); setWorksheetOutlineLevelRow();
@ -1328,7 +1332,9 @@ public class SXSSFSheet implements Sheet
CTSheetFormatPr pr = ct.isSetSheetFormatPr() ? CTSheetFormatPr pr = ct.isSetSheetFormatPr() ?
ct.getSheetFormatPr() : ct.getSheetFormatPr() :
ct.addNewSheetFormatPr(); ct.addNewSheetFormatPr();
if(outlineLevelRow > 0) pr.setOutlineLevelRow((short)outlineLevelRow); if(outlineLevelRow > 0) {
pr.setOutlineLevelRow((short)outlineLevelRow);
}
} }
/** /**
@ -1397,8 +1403,9 @@ public class SXSSFSheet implements Sheet
} }
int currentRow = rowIndex; int currentRow = rowIndex;
while (getRow(currentRow) != null) { while (getRow(currentRow) != null) {
if (getRow(currentRow).getOutlineLevel() < level) if (getRow(currentRow).getOutlineLevel() < level) {
return currentRow + 1; return currentRow + 1;
}
currentRow--; currentRow--;
} }
return currentRow + 1; return currentRow + 1;
@ -1626,6 +1633,8 @@ public class SXSSFSheet implements Sheet
* @return cell comment or <code>null</code> if not found * @return cell comment or <code>null</code> if not found
* @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead. * @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead.
*/ */
@Deprecated
@Removal(version="3.16")
@Override @Override
public XSSFComment getCellComment(int row, int column) public XSSFComment getCellComment(int row, int column)
{ {
@ -1691,7 +1700,7 @@ public class SXSSFSheet implements Sheet
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Drawing getDrawingPatriarch() public XSSFDrawing getDrawingPatriarch()
{ {
return _sh.getDrawingPatriarch(); return _sh.getDrawingPatriarch();
} }
@ -1702,9 +1711,9 @@ public class SXSSFSheet implements Sheet
* @return The new drawing patriarch. * @return The new drawing patriarch.
*/ */
@Override @Override
public Drawing createDrawingPatriarch() public SXSSFDrawing createDrawingPatriarch()
{ {
return new SXSSFDrawing((SXSSFWorkbook)getWorkbook(), _sh.createDrawingPatriarch()); return new SXSSFDrawing(getWorkbook(), _sh.createDrawingPatriarch());
} }
@ -1868,8 +1877,12 @@ public class SXSSFSheet implements Sheet
*/ */
public void flushRows(int remaining) throws IOException public void flushRows(int remaining) throws IOException
{ {
while(_rows.size() > remaining) flushOneRow(); while(_rows.size() > remaining) {
if (remaining == 0) allFlushed = true; flushOneRow();
}
if (remaining == 0) {
allFlushed = true;
}
} }
/** /**
@ -1907,9 +1920,10 @@ public class SXSSFSheet implements Sheet
for(Iterator<Map.Entry<Integer,SXSSFRow>> iter=_rows.entrySet().iterator();iter.hasNext();) for(Iterator<Map.Entry<Integer,SXSSFRow>> iter=_rows.entrySet().iterator();iter.hasNext();)
{ {
Map.Entry<Integer,SXSSFRow> entry=iter.next(); Map.Entry<Integer,SXSSFRow> entry=iter.next();
if(entry.getValue()==row) if(entry.getValue()==row) {
return entry.getKey().intValue(); return entry.getKey().intValue();
} }
}
return -1; return -1;
} }
@ -1918,7 +1932,9 @@ public class SXSSFSheet implements Sheet
* @return true if the file was deleted, false if it wasn't. * @return true if the file was deleted, false if it wasn't.
*/ */
boolean dispose() throws IOException { boolean dispose() throws IOException {
if (!allFlushed) flushRows(); if (!allFlushed) {
flushRows();
}
return _writer.dispose(); return _writer.dispose();
} }

View File

@ -144,7 +144,7 @@ public class TestCommentsTable {
Cell c1r2s2 = r2s2.createCell(1); Cell c1r2s2 = r2s2.createCell(1);
assertNull(c1r2s2.getCellComment()); assertNull(c1r2s2.getCellComment());
Drawing dg = sheet2.createDrawingPatriarch(); Drawing<?> dg = sheet2.createDrawingPatriarch();
Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); Comment cc2 = dg.createCellComment(new XSSFClientAnchor());
cc2.setAuthor("Also POI"); cc2.setAuthor("Also POI");
cc2.setString(new XSSFRichTextString("A new comment")); cc2.setString(new XSSFRichTextString("A new comment"));
@ -256,7 +256,7 @@ public class TestCommentsTable {
// NOTE - only occurs if a comment is placed in A1 first // NOTE - only occurs if a comment is placed in A1 first
Cell A1 = getCell(sheet, 0, 0); Cell A1 = getCell(sheet, 0, 0);
//Cell A1 = getCell(sheet, 2, 2); //Cell A1 = getCell(sheet, 2, 2);
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
setComment(sheet, A1, drawing, "for A1", helper, anchor); setComment(sheet, A1, drawing, "for A1", helper, anchor);
// find comment in A1 before we set the comment in B2 // find comment in A1 before we set the comment in B2
@ -282,7 +282,7 @@ public class TestCommentsTable {
// Set the comment on a sheet // Set the comment on a sheet
// //
private static void setComment(Sheet sheet, Cell cell, Drawing drawing, String commentText, CreationHelper helper, ClientAnchor anchor) { private static void setComment(Sheet sheet, Cell cell, Drawing<?> drawing, String commentText, CreationHelper helper, ClientAnchor anchor) {
System.out.println("Setting col: " + cell.getColumnIndex() + " and row " + cell.getRowIndex()); System.out.println("Setting col: " + cell.getColumnIndex() + " and row " + cell.getRowIndex());
anchor.setCol1(cell.getColumnIndex()); anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex()); anchor.setCol2(cell.getColumnIndex());

View File

@ -25,7 +25,14 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.*; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
@ -57,6 +64,7 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.util.ZipSecureFile; import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.formula.WorkbookEvaluator; import org.apache.poi.ss.formula.WorkbookEvaluator;
import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.NumberEval;
@ -1277,7 +1285,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
// Try to add comments to Sheet 1 // Try to add comments to Sheet 1
CreationHelper factory = wb1.getCreationHelper(); CreationHelper factory = wb1.getCreationHelper();
Drawing drawing = sh1.createDrawingPatriarch(); Drawing<?> drawing = sh1.createDrawingPatriarch();
ClientAnchor anchor = factory.createClientAnchor(); ClientAnchor anchor = factory.createClientAnchor();
anchor.setCol1(0); anchor.setCol1(0);
@ -1336,8 +1344,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
Name name = wb.getName("Intekon.ProdCodes"); Name name = wb.getName("Intekon.ProdCodes");
assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula()); assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula());
@SuppressWarnings("deprecation") AreaReference ref = new AreaReference(name.getRefersToFormula(), SpreadsheetVersion.EXCEL2007);
AreaReference ref = new AreaReference(name.getRefersToFormula());
assertEquals(0, ref.getFirstCell().getRow()); assertEquals(0, ref.getFirstCell().getRow());
assertEquals(0, ref.getFirstCell().getCol()); assertEquals(0, ref.getFirstCell().getCol());
assertEquals(1, ref.getLastCell().getRow()); assertEquals(1, ref.getLastCell().getRow());
@ -2312,7 +2319,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
assertNotNull(orig); assertNotNull(orig);
Sheet sheet = wb.cloneSheet(0); Sheet sheet = wb.cloneSheet(0);
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) { for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) {
if (shape instanceof XSSFPicture) { if (shape instanceof XSSFPicture) {
XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData(); XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData();
@ -2991,7 +2998,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
XSSFColor color = new XSSFColor(java.awt.Color.RED); XSSFColor color = new XSSFColor(java.awt.Color.RED);
XSSFCellStyle style = workbook.createCellStyle(); XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(color); style.setFillForegroundColor(color);
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style); cell.setCellStyle(style);
// Everything is fine at this point, cell is red // Everything is fine at this point, cell is red

View File

@ -18,9 +18,15 @@
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.io.*; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.BaseTestCellComment; import org.apache.poi.ss.usermodel.BaseTestCellComment;
@ -48,9 +54,6 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt;
import com.microsoft.schemas.vml.CTShape; import com.microsoft.schemas.vml.CTShape;
/**
* @author Yegor Kozlov
*/
public final class TestXSSFComment extends BaseTestCellComment { public final class TestXSSFComment extends BaseTestCellComment {
private static final String TEST_RICHTEXTSTRING = "test richtextstring"; private static final String TEST_RICHTEXTSTRING = "test richtextstring";
@ -274,7 +277,7 @@ public final class TestXSSFComment extends BaseTestCellComment {
cell.setCellValue("F4"); cell.setCellValue("F4");
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();

View File

@ -1955,7 +1955,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
} }
private void addComments(CreationHelper helper, Sheet sheet) { private void addComments(CreationHelper helper, Sheet sheet) {
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
ClientAnchor anchor = helper.createClientAnchor(); ClientAnchor anchor = helper.createClientAnchor();
@ -1968,11 +1968,13 @@ public final class TestXSSFSheet extends BaseTestXSheet {
comment.setString(helper.createRichTextString("BugTesting")); comment.setString(helper.createRichTextString("BugTesting"));
Row row = sheet.getRow(0 + i); Row row = sheet.getRow(0 + i);
if (row == null) if (row == null) {
row = sheet.createRow(0 + i); row = sheet.createRow(0 + i);
}
Cell cell = row.getCell(0); Cell cell = row.getCell(0);
if (cell == null) if (cell == null) {
cell = row.createCell(0); cell = row.createCell(0);
}
cell.setCellComment(comment); cell.setCellComment(comment);
} }

View File

@ -17,38 +17,47 @@
package org.apache.poi.xssf.usermodel.charts; package org.apache.poi.xssf.usermodel.charts;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.poi.ss.usermodel.*; import java.io.IOException;
import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.charts.ChartLegend; import org.apache.poi.ss.usermodel.charts.ChartLegend;
import org.apache.poi.ss.usermodel.charts.LegendPosition; import org.apache.poi.ss.usermodel.charts.LegendPosition;
import org.apache.poi.xssf.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
/** /**
* Tests ChartLegend * Tests ChartLegend
*
* @author Martin Andersson
* @author Cedric dot Walter at gmail dot com
*/ */
public final class TestXSSFChartLegend extends TestCase { public final class TestXSSFChartLegend {
@Test
public void testLegendPositionAccessMethods() throws Exception { public void testLegendPositionAccessMethods() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend(); ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT); legend.setPosition(LegendPosition.TOP_RIGHT);
assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition());
wb.close();
} }
public void test_setOverlay_defaultChartLegend_expectOverlayInitialValueSetToFalse() { @Test
public void test_setOverlay_defaultChartLegend_expectOverlayInitialValueSetToFalse() throws IOException {
// Arrange // Arrange
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend(); ChartLegend legend = chart.getOrCreateLegend();
@ -57,13 +66,16 @@ public final class TestXSSFChartLegend extends TestCase {
// Assert // Assert
assertFalse(legend.isOverlay()); assertFalse(legend.isOverlay());
wb.close();
} }
public void test_setOverlay_chartLegendSetToTrue_expectOverlayInitialValueSetToTrue() { @Test
public void test_setOverlay_chartLegendSetToTrue_expectOverlayInitialValueSetToTrue() throws IOException {
// Arrange // Arrange
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend(); ChartLegend legend = chart.getOrCreateLegend();
@ -73,5 +85,7 @@ public final class TestXSSFChartLegend extends TestCase {
// Assert // Assert
assertTrue(legend.isOverlay()); assertTrue(legend.isOverlay());
wb.close();
} }
} }

View File

@ -17,19 +17,43 @@
package org.apache.poi.xssf.usermodel.charts; package org.apache.poi.xssf.usermodel.charts;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import org.apache.poi.ss.usermodel.*; import static org.junit.Assert.assertFalse;
import org.apache.poi.ss.usermodel.charts.*; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.charts.AxisCrosses;
import org.apache.poi.ss.usermodel.charts.AxisPosition;
import org.apache.poi.ss.usermodel.charts.ChartAxis;
import org.apache.poi.ss.usermodel.charts.ChartDataSource;
import org.apache.poi.ss.usermodel.charts.ChartLegend;
import org.apache.poi.ss.usermodel.charts.DataSources;
import org.apache.poi.ss.usermodel.charts.LegendPosition;
import org.apache.poi.ss.usermodel.charts.LineChartData;
import org.apache.poi.ss.usermodel.charts.ValueAxis;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFChart;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import java.util.List; import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
/** /**
* Test get/set chart title. * Test get/set chart title.
*/ */
public class TestXSSFChartTitle extends TestCase { public class TestXSSFChartTitle {
private Workbook createWorkbookWithChart() { private Workbook createWorkbookWithChart() {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("linechart"); Sheet sheet = wb.createSheet("linechart");
@ -47,7 +71,7 @@ public class TestXSSFChartTitle extends TestCase {
} }
} }
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
@ -91,7 +115,8 @@ public class TestXSSFChartTitle extends TestCase {
return null; return null;
} }
public void testNewChart() { @Test
public void testNewChart() throws IOException {
Workbook wb = createWorkbookWithChart(); Workbook wb = createWorkbookWithChart();
XSSFChart chart = getChartFromWorkbook(wb, "linechart"); XSSFChart chart = getChartFromWorkbook(wb, "linechart");
assertNotNull(chart); assertNotNull(chart);
@ -101,9 +126,11 @@ public class TestXSSFChartTitle extends TestCase {
XSSFRichTextString queryTitle = chart.getTitle(); XSSFRichTextString queryTitle = chart.getTitle();
assertNotNull(queryTitle); assertNotNull(queryTitle);
assertEquals(myTitle, queryTitle.toString()); assertEquals(myTitle, queryTitle.toString());
wb.close();
} }
public void testExistingChartWithTitle() { @Test
public void testExistingChartWithTitle() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx");
XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); XSSFChart chart = getChartFromWorkbook(wb, "Sheet1");
assertNotNull(chart); assertNotNull(chart);
@ -115,9 +142,11 @@ public class TestXSSFChartTitle extends TestCase {
XSSFRichTextString queryTitle = chart.getTitle(); XSSFRichTextString queryTitle = chart.getTitle();
assertNotNull(queryTitle); assertNotNull(queryTitle);
assertEquals(myTitle, queryTitle.toString()); assertEquals(myTitle, queryTitle.toString());
wb.close();
} }
public void testExistingChartNoTitle() { @Test
public void testExistingChartNoTitle() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_noTitle.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_noTitle.xlsx");
XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); XSSFChart chart = getChartFromWorkbook(wb, "Sheet1");
assertNotNull(chart); assertNotNull(chart);
@ -127,6 +156,6 @@ public class TestXSSFChartTitle extends TestCase {
XSSFRichTextString queryTitle = chart.getTitle(); XSSFRichTextString queryTitle = chart.getTitle();
assertNotNull(queryTitle); assertNotNull(queryTitle);
assertEquals(myTitle, queryTitle.toString()); assertEquals(myTitle, queryTitle.toString());
wb.close();
} }
} }

View File

@ -16,7 +16,11 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.xssf.usermodel.charts; package org.apache.poi.xssf.usermodel.charts;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Chart; import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.ClientAnchor;
@ -32,21 +36,23 @@ import org.apache.poi.ss.usermodel.charts.LineChartSeries;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.SheetBuilder; import org.apache.poi.ss.util.SheetBuilder;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
/** /**
* Tests for XSSF Line Charts * Tests for XSSF Line Charts
*/ */
public class TestXSSFLineChartData extends TestCase { public class TestXSSFLineChartData {
private static final Object[][] plotData = { private static final Object[][] plotData = {
{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"},
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
}; };
public void testOneSeriePlot() throws Exception { @Test
public void testOneSeriePlot() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = new SheetBuilder(wb, plotData).build(); Sheet sheet = new SheetBuilder(wb, plotData).build();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
@ -65,5 +71,6 @@ public class TestXSSFLineChartData extends TestCase {
assertTrue(lineChartData.getSeries().contains(series)); assertTrue(lineChartData.getSeries().contains(series));
chart.plot(lineChartData, bottomAxis, leftAxis); chart.plot(lineChartData, bottomAxis, leftAxis);
wb.close();
} }
} }

View File

@ -17,29 +17,57 @@
package org.apache.poi.xssf.usermodel.charts; package org.apache.poi.xssf.usermodel.charts;
import junit.framework.TestCase; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.poi.ss.usermodel.*; import java.io.IOException;
import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.charts.ChartLegend; import org.apache.poi.ss.usermodel.charts.ChartLegend;
import org.apache.poi.ss.usermodel.charts.ManualLayout;
import org.apache.poi.ss.usermodel.charts.LayoutMode; import org.apache.poi.ss.usermodel.charts.LayoutMode;
import org.apache.poi.ss.usermodel.charts.LayoutTarget; import org.apache.poi.ss.usermodel.charts.LayoutTarget;
import org.apache.poi.xssf.usermodel.*; import org.apache.poi.ss.usermodel.charts.ManualLayout;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public final class TestXSSFManualLayout extends TestCase { public final class TestXSSFManualLayout {
private Workbook wb;
private ManualLayout layout;
@Before
public void createEmptyLayout() {
wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
layout = legend.getManualLayout();
}
@After
public void closeWB() throws IOException {
wb.close();
}
/* /*
* Accessor methods are not trivial. They use lazy underlying bean * Accessor methods are not trivial. They use lazy underlying bean
* initialization so there can be some errors (NPE, for example). * initialization so there can be some errors (NPE, for example).
*/ */
public void testAccessorMethods() throws Exception { @Test
public void testAccessorMethods() {
final double newRatio = 1.1; final double newRatio = 1.1;
final double newCoordinate = 0.3; final double newCoordinate = 0.3;
final LayoutMode nonDefaultMode = LayoutMode.FACTOR; final LayoutMode nonDefaultMode = LayoutMode.FACTOR;
final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER;
ManualLayout layout = getEmptyLayout();
layout.setWidthRatio(newRatio); layout.setWidthRatio(newRatio);
assertTrue(layout.getWidthRatio() == newRatio); assertTrue(layout.getWidthRatio() == newRatio);
@ -73,9 +101,8 @@ public final class TestXSSFManualLayout extends TestCase {
* Layout must have reasonable default values and must not throw * Layout must have reasonable default values and must not throw
* any exceptions. * any exceptions.
*/ */
public void testDefaultValues() throws Exception { @Test
ManualLayout layout = getEmptyLayout(); public void testDefaultValues() {
assertNotNull(layout.getTarget()); assertNotNull(layout.getTarget());
assertNotNull(layout.getXMode()); assertNotNull(layout.getXMode());
assertNotNull(layout.getYMode()); assertNotNull(layout.getYMode());
@ -90,14 +117,4 @@ public final class TestXSSFManualLayout extends TestCase {
assertTrue(layout.getWidthRatio() == 0.0); assertTrue(layout.getWidthRatio() == 0.0);
assertTrue(layout.getHeightRatio() == 0.0); assertTrue(layout.getHeightRatio() == 0.0);
} }
private ManualLayout getEmptyLayout() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
return legend.getManualLayout();
}
} }

View File

@ -17,7 +17,11 @@
package org.apache.poi.xssf.usermodel.charts; package org.apache.poi.xssf.usermodel.charts;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Chart; import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.ClientAnchor;
@ -33,21 +37,23 @@ import org.apache.poi.ss.usermodel.charts.ScatterChartSeries;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.SheetBuilder; import org.apache.poi.ss.util.SheetBuilder;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
/** /**
* Tests for XSSFScatterChartData. * Tests for XSSFScatterChartData.
*/ */
public final class TestXSSFScatterChartData extends TestCase { public final class TestXSSFScatterChartData {
private static final Object[][] plotData = { private static final Object[][] plotData = {
{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"},
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
}; };
public void testOneSeriePlot() throws Exception { @Test
public void testOneSeriePlot() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = new SheetBuilder(wb, plotData).build(); Sheet sheet = new SheetBuilder(wb, plotData).build();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
@ -66,5 +72,6 @@ public final class TestXSSFScatterChartData extends TestCase {
assertTrue(scatterChartData.getSeries().contains(series)); assertTrue(scatterChartData.getSeries().contains(series));
chart.plot(scatterChartData, bottomAxis, leftAxis); chart.plot(scatterChartData, bottomAxis, leftAxis);
wb.close();
} }
} }

View File

@ -23,6 +23,7 @@ import static org.junit.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.poifs.crypt.CryptoFunctions; import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.HashAlgorithm;
@ -35,48 +36,53 @@ import org.junit.Test;
public class TestDocumentProtection { public class TestDocumentProtection {
@Test @Test
public void testShouldReadEnforcementProperties() throws Exception { public void testShouldReadEnforcementProperties() throws IOException {
XWPFDocument documentWithoutDocumentProtectionTag = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); XWPFDocument documentWithoutDocumentProtectionTag = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx");
assertFalse(documentWithoutDocumentProtectionTag.isEnforcedReadonlyProtection()); assertFalse(documentWithoutDocumentProtectionTag.isEnforcedReadonlyProtection());
assertFalse(documentWithoutDocumentProtectionTag.isEnforcedFillingFormsProtection()); assertFalse(documentWithoutDocumentProtectionTag.isEnforcedFillingFormsProtection());
assertFalse(documentWithoutDocumentProtectionTag.isEnforcedCommentsProtection()); assertFalse(documentWithoutDocumentProtectionTag.isEnforcedCommentsProtection());
assertFalse(documentWithoutDocumentProtectionTag.isEnforcedTrackedChangesProtection()); assertFalse(documentWithoutDocumentProtectionTag.isEnforcedTrackedChangesProtection());
documentWithoutDocumentProtectionTag.close();
XWPFDocument documentWithoutEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection_tag_existing.docx"); XWPFDocument documentWithoutEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection_tag_existing.docx");
assertFalse(documentWithoutEnforcement.isEnforcedReadonlyProtection()); assertFalse(documentWithoutEnforcement.isEnforcedReadonlyProtection());
assertFalse(documentWithoutEnforcement.isEnforcedFillingFormsProtection()); assertFalse(documentWithoutEnforcement.isEnforcedFillingFormsProtection());
assertFalse(documentWithoutEnforcement.isEnforcedCommentsProtection()); assertFalse(documentWithoutEnforcement.isEnforcedCommentsProtection());
assertFalse(documentWithoutEnforcement.isEnforcedTrackedChangesProtection()); assertFalse(documentWithoutEnforcement.isEnforcedTrackedChangesProtection());
documentWithoutEnforcement.close();
XWPFDocument documentWithReadonlyEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx"); XWPFDocument documentWithReadonlyEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx");
assertTrue(documentWithReadonlyEnforcement.isEnforcedReadonlyProtection()); assertTrue(documentWithReadonlyEnforcement.isEnforcedReadonlyProtection());
assertFalse(documentWithReadonlyEnforcement.isEnforcedFillingFormsProtection()); assertFalse(documentWithReadonlyEnforcement.isEnforcedFillingFormsProtection());
assertFalse(documentWithReadonlyEnforcement.isEnforcedCommentsProtection()); assertFalse(documentWithReadonlyEnforcement.isEnforcedCommentsProtection());
assertFalse(documentWithReadonlyEnforcement.isEnforcedTrackedChangesProtection()); assertFalse(documentWithReadonlyEnforcement.isEnforcedTrackedChangesProtection());
documentWithReadonlyEnforcement.close();
XWPFDocument documentWithFillingFormsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_forms_no_password.docx"); XWPFDocument documentWithFillingFormsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_forms_no_password.docx");
assertTrue(documentWithFillingFormsEnforcement.isEnforcedFillingFormsProtection()); assertTrue(documentWithFillingFormsEnforcement.isEnforcedFillingFormsProtection());
assertFalse(documentWithFillingFormsEnforcement.isEnforcedReadonlyProtection()); assertFalse(documentWithFillingFormsEnforcement.isEnforcedReadonlyProtection());
assertFalse(documentWithFillingFormsEnforcement.isEnforcedCommentsProtection()); assertFalse(documentWithFillingFormsEnforcement.isEnforcedCommentsProtection());
assertFalse(documentWithFillingFormsEnforcement.isEnforcedTrackedChangesProtection()); assertFalse(documentWithFillingFormsEnforcement.isEnforcedTrackedChangesProtection());
documentWithFillingFormsEnforcement.close();
XWPFDocument documentWithCommentsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_comments_no_password.docx"); XWPFDocument documentWithCommentsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_comments_no_password.docx");
assertFalse(documentWithCommentsEnforcement.isEnforcedFillingFormsProtection()); assertFalse(documentWithCommentsEnforcement.isEnforcedFillingFormsProtection());
assertFalse(documentWithCommentsEnforcement.isEnforcedReadonlyProtection()); assertFalse(documentWithCommentsEnforcement.isEnforcedReadonlyProtection());
assertTrue(documentWithCommentsEnforcement.isEnforcedCommentsProtection()); assertTrue(documentWithCommentsEnforcement.isEnforcedCommentsProtection());
assertFalse(documentWithCommentsEnforcement.isEnforcedTrackedChangesProtection()); assertFalse(documentWithCommentsEnforcement.isEnforcedTrackedChangesProtection());
documentWithCommentsEnforcement.close();
XWPFDocument documentWithTrackedChangesEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_trackedChanges_no_password.docx"); XWPFDocument documentWithTrackedChangesEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_trackedChanges_no_password.docx");
assertFalse(documentWithTrackedChangesEnforcement.isEnforcedFillingFormsProtection()); assertFalse(documentWithTrackedChangesEnforcement.isEnforcedFillingFormsProtection());
assertFalse(documentWithTrackedChangesEnforcement.isEnforcedReadonlyProtection()); assertFalse(documentWithTrackedChangesEnforcement.isEnforcedReadonlyProtection());
assertFalse(documentWithTrackedChangesEnforcement.isEnforcedCommentsProtection()); assertFalse(documentWithTrackedChangesEnforcement.isEnforcedCommentsProtection());
assertTrue(documentWithTrackedChangesEnforcement.isEnforcedTrackedChangesProtection()); assertTrue(documentWithTrackedChangesEnforcement.isEnforcedTrackedChangesProtection());
documentWithTrackedChangesEnforcement.close();
} }
@Test @Test
public void testShouldEnforceForReadOnly() throws Exception { public void testShouldEnforceForReadOnly() throws IOException {
// XWPFDocument document = createDocumentFromSampleFile("test-data/document/documentProtection_no_protection.docx"); // XWPFDocument document = createDocumentFromSampleFile("test-data/document/documentProtection_no_protection.docx");
XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx");
assertFalse(document.isEnforcedReadonlyProtection()); assertFalse(document.isEnforcedReadonlyProtection());
@ -84,81 +90,89 @@ public class TestDocumentProtection {
document.enforceReadonlyProtection(); document.enforceReadonlyProtection();
assertTrue(document.isEnforcedReadonlyProtection()); assertTrue(document.isEnforcedReadonlyProtection());
document.close();
} }
@Test @Test
public void testShouldEnforceForFillingForms() throws Exception { public void testShouldEnforceForFillingForms() throws IOException {
XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx");
assertFalse(document.isEnforcedFillingFormsProtection()); assertFalse(document.isEnforcedFillingFormsProtection());
document.enforceFillingFormsProtection(); document.enforceFillingFormsProtection();
assertTrue(document.isEnforcedFillingFormsProtection()); assertTrue(document.isEnforcedFillingFormsProtection());
document.close();
} }
@Test @Test
public void testShouldEnforceForComments() throws Exception { public void testShouldEnforceForComments() throws IOException {
XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx");
assertFalse(document.isEnforcedCommentsProtection()); assertFalse(document.isEnforcedCommentsProtection());
document.enforceCommentsProtection(); document.enforceCommentsProtection();
assertTrue(document.isEnforcedCommentsProtection()); assertTrue(document.isEnforcedCommentsProtection());
document.close();
} }
@Test @Test
public void testShouldEnforceForTrackedChanges() throws Exception { public void testShouldEnforceForTrackedChanges() throws IOException {
XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx");
assertFalse(document.isEnforcedTrackedChangesProtection()); assertFalse(document.isEnforcedTrackedChangesProtection());
document.enforceTrackedChangesProtection(); document.enforceTrackedChangesProtection();
assertTrue(document.isEnforcedTrackedChangesProtection()); assertTrue(document.isEnforcedTrackedChangesProtection());
document.close();
} }
@Test @Test
public void testShouldUnsetEnforcement() throws Exception { public void testShouldUnsetEnforcement() throws IOException {
XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx");
assertTrue(document.isEnforcedReadonlyProtection()); assertTrue(document.isEnforcedReadonlyProtection());
document.removeProtectionEnforcement(); document.removeProtectionEnforcement();
assertFalse(document.isEnforcedReadonlyProtection()); assertFalse(document.isEnforcedReadonlyProtection());
document.close();
} }
@Test @Test
public void testIntegration() throws Exception { public void testIntegration() throws IOException {
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc1 = new XWPFDocument();
XWPFParagraph p1 = doc.createParagraph(); XWPFParagraph p1 = doc1.createParagraph();
XWPFRun r1 = p1.createRun(); XWPFRun r1 = p1.createRun();
r1.setText("Lorem ipsum dolor sit amet."); r1.setText("Lorem ipsum dolor sit amet.");
doc.enforceCommentsProtection(); doc1.enforceCommentsProtection();
File tempFile = TempFile.createTempFile("documentProtectionFile", ".docx"); File tempFile = TempFile.createTempFile("documentProtectionFile", ".docx");
FileOutputStream out = new FileOutputStream(tempFile); FileOutputStream out = new FileOutputStream(tempFile);
doc.write(out); doc1.write(out);
out.close(); out.close();
FileInputStream inputStream = new FileInputStream(tempFile); FileInputStream inputStream = new FileInputStream(tempFile);
XWPFDocument document = new XWPFDocument(inputStream); XWPFDocument doc2 = new XWPFDocument(inputStream);
inputStream.close(); inputStream.close();
assertTrue(document.isEnforcedCommentsProtection()); assertTrue(doc2.isEnforcedCommentsProtection());
doc2.close();
doc1.close();
} }
@Test @Test
public void testUpdateFields() throws Exception { public void testUpdateFields() throws IOException {
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
assertFalse(doc.isEnforcedUpdateFields()); assertFalse(doc.isEnforcedUpdateFields());
doc.enforceUpdateFields(); doc.enforceUpdateFields();
assertTrue(doc.isEnforcedUpdateFields()); assertTrue(doc.isEnforcedUpdateFields());
doc.close();
} }
@Test @Test
public void bug56076_read() throws Exception { public void bug56076_read() throws IOException {
// test legacy xored-hashed password // test legacy xored-hashed password
assertEquals("64CEED7E", CryptoFunctions.xorHashPassword("Example")); assertEquals("64CEED7E", CryptoFunctions.xorHashPassword("Example"));
// check leading 0 // check leading 0
@ -168,15 +182,18 @@ public class TestDocumentProtection {
XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56076.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56076.docx");
boolean isValid = document.validateProtectionPassword("Example"); boolean isValid = document.validateProtectionPassword("Example");
assertTrue(isValid); assertTrue(isValid);
document.close();
} }
@Test @Test
public void bug56076_write() throws Exception { public void bug56076_write() throws IOException {
// test document write protection with password // test document write protection with password
XWPFDocument document = new XWPFDocument(); XWPFDocument doc1 = new XWPFDocument();
document.enforceCommentsProtection("Example", HashAlgorithm.sha512); doc1.enforceCommentsProtection("Example", HashAlgorithm.sha512);
document = XWPFTestDataSamples.writeOutAndReadBack(document); XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc1);
boolean isValid = document.validateProtectionPassword("Example"); doc1.close();
boolean isValid = doc2.validateProtectionPassword("Example");
assertTrue(isValid); assertTrue(isValid);
doc2.close();
} }
} }

View File

@ -54,7 +54,6 @@ import org.apache.poi.util.POILogger;
public final class PowerPointExtractor extends POIOLE2TextExtractor { public final class PowerPointExtractor extends POIOLE2TextExtractor {
private static final POILogger LOG = POILogFactory.getLogger(PowerPointExtractor.class); private static final POILogger LOG = POILogFactory.getLogger(PowerPointExtractor.class);
private final HSLFSlideShowImpl _hslfshow;
private final HSLFSlideShow _show; private final HSLFSlideShow _show;
private final List<HSLFSlide> _slides; private final List<HSLFSlide> _slides;
@ -147,8 +146,7 @@ public final class PowerPointExtractor extends POIOLE2TextExtractor {
*/ */
public PowerPointExtractor(HSLFSlideShowImpl ss) { public PowerPointExtractor(HSLFSlideShowImpl ss) {
super(ss); super(ss);
_hslfshow = ss; _show = new HSLFSlideShow(ss);
_show = new HSLFSlideShow(_hslfshow);
_slides = _show.getSlides(); _slides = _show.getSlides();
} }
@ -184,6 +182,7 @@ public final class PowerPointExtractor extends POIOLE2TextExtractor {
* Fetches all the slide text from the slideshow, but not the notes, unless * Fetches all the slide text from the slideshow, but not the notes, unless
* you've called setSlidesByDefault() and setNotesByDefault() to change this * you've called setSlidesByDefault() and setNotesByDefault() to change this
*/ */
@Override
public String getText() { public String getText() {
return getText(_slidesByDefault, _notesByDefault, _commentsByDefault, _masterByDefault); return getText(_slidesByDefault, _notesByDefault, _commentsByDefault, _masterByDefault);
} }

View File

@ -17,12 +17,13 @@
package org.apache.poi.hdgf.streams; package org.apache.poi.hdgf.streams;
import static org.apache.poi.hdgf.pointers.PointerV6.getNumPointersOffsetV6;
import static org.apache.poi.hdgf.pointers.PointerV6.getNumPointersV6;
import static org.apache.poi.hdgf.pointers.PointerV6.getPostNumPointersSkipV6;
import org.apache.poi.hdgf.pointers.Pointer; import org.apache.poi.hdgf.pointers.Pointer;
import static org.apache.poi.hdgf.pointers.PointerV6.*;
import junit.framework.TestCase; public abstract class StreamTest {
public abstract class StreamTest extends TestCase {
public static class TestPointer extends Pointer { public static class TestPointer extends Pointer {
private final boolean compressed; private final boolean compressed;
protected boolean hasPointers = false; protected boolean hasPointers = false;

View File

@ -17,73 +17,45 @@
package org.apache.poi.hdgf.streams; package org.apache.poi.hdgf.streams;
import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.poi.hdgf.pointers.Pointer; import org.apache.poi.hdgf.pointers.Pointer;
import org.junit.BeforeClass;
import org.junit.Test;
public final class TestStreamBasics extends StreamTest { public final class TestStreamBasics extends StreamTest {
/** The header from when compressedStream is decompressed */ private static byte[] compressedStream, uncompressedStream;
public static final byte[] compressedStreamDCHeader = new byte[] {
-60, 2, 0, 0
};
public static final byte[] compressedStream = new byte[] {
123, -60, 2, -21, -16, 1, 0, 0, -72, -13, -16, 78, -32, -5, 1,
0, 3, -21, -16, 10, 5, 4, -21, -16, 21, 9, -21, -16, 103, -21,
-16, 34, -36, -1, 52, 15, 70, 15, 120, 88, 15, -7, -2, -28, -9,
-123, 21, 0, 44, -122, 1, -4, 104, 15, -24, -13, 40, -98, 32,
78, 102, -67, -1, -2, -30, 64, 40, -67, -113, -73, 116, -98,
-85, 2, 66, 123, 9, 109, -85, 2, -89, 14, -56, -69, -83, -79,
-34, -3, 120, 110, 75, -9, -10, 20, -6, -25, -12, 22, -21, -16,
-12, -81, 67, 1, -128, -70, -21, -16, 84, -21, -16, 70, 0, 23,
-21, -16, 76, 47, -40, 79, 1, -44, -21, -16, 32, 3, 18, 12, 17,
-43, -68, 17, 16, -8, 21, 22, -1, -21, -16, -84, -1, -35, 79,
-9, -10, 96, 0, 46, -21, -16, 44, -39, -41, 79, 1, 119, -13,
-16, -106, -13, -16, 84, 0, 125, 26, -21, -16, 68, -38, 79, 1,
17, 10, 0, -97, 50, 10, 0, 0, -42, -108, 15, 118, 31, 0, -3, 29,
-21, -16, -100, -25, 79, 1, -18, 97, -36, 76, 16, -21, -16, 86,
0, 36, -5, 1, -5, 79, 63, 1, -124, 98, 0, 0, 28, 3, 20, -34, -3,
125, 33, -21, -16, 100, -4, 79, 1, -92, -91, 16, -22, 24, 19, 41,
-21, -16, -44, -59, 16, 108, 100, 0, -21, 0, 71, -105, 18, 39, 85,
17, -3, 79, 1, 95, -108, 113, 0, 0, 104, 3, 18, 49, 49, 17, -1, 64,
85, 1, 0, 114, 0, 0, -93, -36, -21, -16, 100, 31, 0, 0, -40, -21,
-16, -92, 66, 127, 85, 1, 98, 119, 0, 0, -48, 79, 18, -3, 50, -17,
1, 67, 85, 1, 81, -127, 0, -41, 0, 14, 6, 4, 17, 63, -63, 17, 68,
85, -65, 1, 30, -120, 0, 0, 42, 79, 18, 68, 126, -21, -16, -76, 69,
85, 1, 102, -119, 72, 37, 0, 97, 33 };
public static final byte[] uncompressedStream = new byte[] {
0, 1, 0, 0, -72, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0,
0, 9, 0, 0, 0, 103, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-123, 21, 0, 44, -123, 21, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, -98, 32, 78, 102, -67,
-2, -30, 64, 40, -67, -113, -73, 116, -67, -2, -30, 64, 40, 66,
123, 9, 109, -67, -2, -30, 64, 40, -98, 32, 78, 102, -67, -2, -30,
64, 40, -67, -113, -73, 116, -67, -2, -30, 64, -56, -83, -79, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 110, 75, 1, 0, 0, 0,
0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, -12, -81, 67,
1, -128, 0, 0, 0, 84, 0, 0, 0, 70, 0, 23, 0, 0, 0, 76, -40, 79, 1,
-44, 0, 0, 0, 32, 0, 0, 0, 84, 0, 23, 0, 0, 0, -68, -40, 79, 1, -8,
0, 0, 0, 32, 0, 0, 0, 84, 0, -1, 0, 0, 0, -84, -1, 79, 1, 0, 0, 0,
0, 0, 0, 0, 0, 96, 0, 46, 0, 0, 0, 44, -39, 79, 1, 119, 1, 0, 0,
-106, 1, 0, 0, 84, 0, 26, 0, 0, 0, 68, -38, 79, 1, 17, 3, 0, 0,
50, 10, 0, 0, -42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
29, 0, 0, 0, -100, -25, 79, 1, -18, 97, 0, 0, -106, 0, 0, 0, 86, 0,
36, 0, 0, 0, -12, -5, 79, 1, -124, 98, 0, 0, 28, 0, 0, 0, 84, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, 0, 100,
-4, 79, 1, -92, 98, 0, 0, 32, 0, 0, 0, 84, 0, 41, 0, 0, 0, -44, -4,
79, 1, 108, 100, 0, 0, 71, 0, 0, 0, 86, 0, 39, 0, 0, 0, 68, -3, 79,
1, -108, 113, 0, 0, 104, 0, 0, 0, 84, 0, 49, 0, 0, 0, -84, 64, 85,
1, 0, 114, 0, 0, -93, 0, 0, 0, -42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, -40, 0, 0, 0, -92, 66, 85, 1, 98, 119,
0, 0, -48, 1, 0, 0, 84, 0, 50, 0, 0, 0, 20, 67, 85, 1, 81, -127,
0, 0, 14, 6, 0, 0, 84, 0, 63, 0, 0, 0, 100, 68, 85, 1, 30, -120,
0, 0, 42, 1, 0, 0, 84, 0, 68, 0, 0, 0, -76, 69, 85, 1, 102, -119,
0, 0, 42, 1, 0, 0, 84, 0, 0, 0, 0, 0
};
@BeforeClass
public static void init() throws IOException {
compressedStream = decompress(
"H4sIAAAAAAAAAAFTAaz+e8QC6/ABAAC48/BO4PsBAAPr8AoFBOvwFQnr8Gfr8CLc/zQPRg94WA/5/u"+
"T3hRUALIYB/GgP6PMoniBOZr3//uJAKL2Pt3SeqwJCewltqwKnDsi7rbHe/XhuS/f2FPrn9Bbr8PSv"+
"QwGAuuvwVOvwRgAX6/BML9hPAdTr8CADEgwR1bwREPgVFv/r8Kz/3U/39mAALuvwLNnXTwF38/CW8/"+
"BUAH0a6/BE2k8BEQoAnzIKAADWlA92HwD9HevwnOdPAe5h3EwQ6/BWACT7AftPPwGEYgAAHAMU3v19"+
"IevwZPxPAaSlEOoYEynr8NTFEGxkAOsAR5cSJ1UR/U8BX5RxAABoAxIxMRH/QFUBAHIAAKPc6/BkHw"+
"AA2OvwpEJ/VQFidwAA0E8S/TLvAUNVAVGBANcADgYEET/BEURVvwEeiAAAKk8SRH7r8LRFVQFmiUgl"+
"AGEhwtTYaVMBAAA="
);
uncompressedStream = decompress(
"H4sIAAAAAAAAAGNgZGDYAcSogJGBGUjCMAsQcwJxOhAroSulEkB2Qqsogw4I41KrMU/BL23vv0cOGn"+
"v7t5eAGU7VnLlgBobUibUb0fVX5HnDrROB0mJA/GW9M2MDkA4BYjcGcSDpc8Of8QqQVgCLgkT2AEV+"+
"wEX+A8k1//3hpiUw6AFJnZv+jOVAsWmMIDVSQBGXW/6MgsCgNOJiYLhGVHjIAvGc5/6M7xKB5gDZYQ"+
"wqIBf+9mdsSWJgkIG6Eh0oAnHKH3/GJUkwF2oCyStAkZwUBgZ3sDnqIPf89WecUsjAkAFWYwjyhUMo"+
"I0MRA8NiBuwuvAHES5xCGZPKGRgugP1lBAo951DGwEYGBj42kIg9yHaXUEa5DgYGLbAaF6DIFtdQxr"+
"ROmAgIAAD6SJPAdAIAAA=="
);
}
@Test
public void testCompressedStream() { public void testCompressedStream() {
// Create a fake pointer // Create a fake pointer
Pointer ptr = new TestPointer(true, 0, compressedStream.length, -1, (short)-1); Pointer ptr = new TestPointer(true, 0, compressedStream.length, -1, (short)-1);
@ -93,7 +65,6 @@ public final class TestStreamBasics extends StreamTest {
// Check // Check
assertNotNull(stream.getPointer()); assertNotNull(stream.getPointer());
assertNotNull(stream.getStore()); assertNotNull(stream.getStore());
assertTrue(stream.getStore() instanceof StreamStore);
assertTrue(stream.getStore() instanceof CompressedStreamStore); assertTrue(stream.getStore() instanceof CompressedStreamStore);
assertTrue(stream instanceof UnknownStream); assertTrue(stream instanceof UnknownStream);
@ -108,6 +79,7 @@ public final class TestStreamBasics extends StreamTest {
} }
} }
@Test
public void testUncompressedStream() { public void testUncompressedStream() {
// Create a fake pointer // Create a fake pointer
Pointer ptr = new TestPointer(false, 0, uncompressedStream.length, -1, (short)-1); Pointer ptr = new TestPointer(false, 0, uncompressedStream.length, -1, (short)-1);
@ -117,7 +89,6 @@ public final class TestStreamBasics extends StreamTest {
// Check // Check
assertNotNull(stream.getPointer()); assertNotNull(stream.getPointer());
assertNotNull(stream.getStore()); assertNotNull(stream.getStore());
assertTrue(stream.getStore() instanceof StreamStore);
assertFalse(stream.getStore() instanceof CompressedStreamStore); assertFalse(stream.getStore() instanceof CompressedStreamStore);
assertTrue(stream instanceof UnknownStream); assertTrue(stream instanceof UnknownStream);
} }

View File

@ -17,15 +17,18 @@
package org.apache.poi.hdgf.streams; package org.apache.poi.hdgf.streams;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hdgf.HDGFDiagram; import org.apache.poi.hdgf.HDGFDiagram;
import org.apache.poi.hdgf.chunks.ChunkFactory; import org.apache.poi.hdgf.chunks.ChunkFactory;
import org.apache.poi.hdgf.pointers.Pointer; import org.apache.poi.hdgf.pointers.Pointer;
import org.apache.poi.hdgf.pointers.PointerFactory; import org.apache.poi.hdgf.pointers.PointerFactory;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils;
import org.junit.Before;
import org.junit.Test;
/** /**
* Tests for bugs with streams * Tests for bugs with streams
@ -36,32 +39,34 @@ public final class TestStreamBugs extends StreamTest {
private PointerFactory ptrFactory; private PointerFactory ptrFactory;
private POIFSFileSystem filesystem; private POIFSFileSystem filesystem;
@Override @Before
protected void setUp() throws Exception { public void setUp() throws IOException {
ptrFactory = new PointerFactory(11); ptrFactory = new PointerFactory(11);
chunkFactory = new ChunkFactory(11); chunkFactory = new ChunkFactory(11);
InputStream is = POIDataSamples.getDiagramInstance().openResourceAsStream("44594.vsd"); InputStream is = POIDataSamples.getDiagramInstance().openResourceAsStream("44594.vsd");
filesystem = new POIFSFileSystem(is); filesystem = new POIFSFileSystem(is);
is.close();
DocumentEntry docProps =
(DocumentEntry)filesystem.getRoot().getEntry("VisioDocument");
// Grab the document stream // Grab the document stream
contents = new byte[docProps.getSize()]; InputStream is2 = filesystem.createDocumentInputStream("VisioDocument");
filesystem.createDocumentInputStream("VisioDocument").read(contents); contents = IOUtils.toByteArray(is2);
is2.close();
} }
@Test
public void testGetTrailer() { public void testGetTrailer() {
Pointer trailerPointer = ptrFactory.createPointer(contents, 0x24); Pointer trailerPointer = ptrFactory.createPointer(contents, 0x24);
Stream.createStream(trailerPointer, contents, chunkFactory, ptrFactory); Stream.createStream(trailerPointer, contents, chunkFactory, ptrFactory);
} }
@SuppressWarnings("unused")
public void TOIMPLEMENTtestGetCertainChunks() { public void TOIMPLEMENTtestGetCertainChunks() {
int offsetA = 3708; int offsetA = 3708;
int offsetB = 3744; int offsetB = 3744;
} }
@Test
public void testGetChildren() { public void testGetChildren() {
Pointer trailerPointer = ptrFactory.createPointer(contents, 0x24); Pointer trailerPointer = ptrFactory.createPointer(contents, 0x24);
TrailerStream trailer = (TrailerStream) TrailerStream trailer = (TrailerStream)
@ -97,7 +102,8 @@ public final class TestStreamBugs extends StreamTest {
trailer.findChildren(contents); trailer.findChildren(contents);
} }
public void testOpen() throws Exception { @Test
HDGFDiagram dg = new HDGFDiagram(filesystem); public void testOpen() throws IOException {
new HDGFDiagram(filesystem).close();
} }
} }

View File

@ -17,15 +17,24 @@
package org.apache.poi.hdgf.streams; package org.apache.poi.hdgf.streams;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hdgf.chunks.Chunk; import org.apache.poi.hdgf.chunks.Chunk;
import org.apache.poi.hdgf.chunks.ChunkFactory; import org.apache.poi.hdgf.chunks.ChunkFactory;
import org.apache.poi.hdgf.pointers.Pointer; import org.apache.poi.hdgf.pointers.Pointer;
import org.apache.poi.hdgf.pointers.PointerFactory; import org.apache.poi.hdgf.pointers.PointerFactory;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils;
import org.junit.Before;
import org.junit.Test;
public final class TestStreamComplex extends StreamTest { public final class TestStreamComplex extends StreamTest {
private byte[] contents; private byte[] contents;
@ -34,25 +43,27 @@ public final class TestStreamComplex extends StreamTest {
private ChunkFactory chunkFactory; private ChunkFactory chunkFactory;
private PointerFactory ptrFactory; private PointerFactory ptrFactory;
@Override @Before
protected void setUp() throws Exception { public void setUp() throws IOException {
ptrFactory = new PointerFactory(11); ptrFactory = new PointerFactory(11);
chunkFactory = new ChunkFactory(11); chunkFactory = new ChunkFactory(11);
InputStream is = POIDataSamples.getDiagramInstance().openResourceAsStream("Test_Visio-Some_Random_Text.vsd"); InputStream is = POIDataSamples.getDiagramInstance().openResourceAsStream("Test_Visio-Some_Random_Text.vsd");
POIFSFileSystem filesystem = new POIFSFileSystem(is); POIFSFileSystem filesystem = new POIFSFileSystem(is);
is.close();
DocumentEntry docProps =
(DocumentEntry)filesystem.getRoot().getEntry("VisioDocument");
// Grab the document stream // Grab the document stream
contents = new byte[docProps.getSize()]; InputStream is2 = filesystem.createDocumentInputStream("VisioDocument");
filesystem.createDocumentInputStream("VisioDocument").read(contents); contents = IOUtils.toByteArray(is2);
is2.close();
filesystem.close();
} }
/** /**
* Test creating the trailer, but not looking for children * Test creating the trailer, but not looking for children
*/ */
@Test
public void testTrailer() { public void testTrailer() {
// Find the trailer // Find the trailer
Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt); Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt);
@ -74,6 +85,7 @@ public final class TestStreamComplex extends StreamTest {
assertEquals(0xff, ts.getChildPointers()[3].getType()); assertEquals(0xff, ts.getChildPointers()[3].getType());
} }
@Test
public void testChunks() { public void testChunks() {
Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt); Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt);
TrailerStream ts = (TrailerStream) TrailerStream ts = (TrailerStream)
@ -94,6 +106,7 @@ public final class TestStreamComplex extends StreamTest {
cs.findChunks(); cs.findChunks();
} }
@Test
public void testStrings() { public void testStrings() {
Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt); Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt);
TrailerStream ts = (TrailerStream) TrailerStream ts = (TrailerStream)
@ -110,6 +123,7 @@ public final class TestStreamComplex extends StreamTest {
assertTrue(stream instanceof StringsStream); assertTrue(stream instanceof StringsStream);
} }
@Test
public void testPointerToStrings() { public void testPointerToStrings() {
// The stream at 0x347f has strings // The stream at 0x347f has strings
// The stream at 0x4312 has a pointer to 0x347f // The stream at 0x4312 has a pointer to 0x347f
@ -154,6 +168,7 @@ public final class TestStreamComplex extends StreamTest {
assertTrue(s4312.getPointedToStreams()[1] instanceof StringsStream); assertTrue(s4312.getPointedToStreams()[1] instanceof StringsStream);
} }
@Test
public void testTrailerContents() { public void testTrailerContents() {
Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt); Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt);
TrailerStream ts = (TrailerStream) TrailerStream ts = (TrailerStream)
@ -205,6 +220,7 @@ public final class TestStreamComplex extends StreamTest {
assertTrue(s8451.getPointedToStreams()[1] instanceof StringsStream); assertTrue(s8451.getPointedToStreams()[1] instanceof StringsStream);
} }
@Test
public void testChunkWithText() { public void testChunkWithText() {
// Parent ChunkStream is at 0x7194 // Parent ChunkStream is at 0x7194
// This is one of the last children of the trailer // This is one of the last children of the trailer

View File

@ -17,18 +17,24 @@
package org.apache.poi.hpbf.model; package org.apache.poi.hpbf.model;
import org.apache.poi.hpbf.HPBFDocument; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hpbf.HPBFDocument;
import org.junit.Test;
import junit.framework.TestCase; public final class TestEscherParts {
public final class TestEscherParts extends TestCase {
private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance();
public void testBasics() throws Exception { @Test
HPBFDocument doc = new HPBFDocument( public void testBasics() throws IOException {
_samples.openResourceAsStream("Sample.pub") InputStream is = _samples.openResourceAsStream("Sample.pub");
); HPBFDocument doc = new HPBFDocument(is);
is.close();
EscherStm es = doc.getEscherStm(); EscherStm es = doc.getEscherStm();
EscherDelayStm eds = doc.getEscherDelayStm(); EscherDelayStm eds = doc.getEscherDelayStm();
@ -40,15 +46,17 @@ public final class TestEscherParts extends TestCase {
assertEquals(0, eds.getEscherRecords().length); assertEquals(0, eds.getEscherRecords().length);
// TODO - check the contents // TODO - check the contents
doc.close();
} }
@Test
public void testComplex() throws Exception { public void testComplex() throws Exception {
HPBFDocument doc = new HPBFDocument( InputStream is = _samples.openResourceAsStream("SampleBrochure.pub");
_samples.openResourceAsStream("SampleBrochure.pub") HPBFDocument doc1 = new HPBFDocument(is);
); is.close();
EscherStm es = doc.getEscherStm(); EscherStm es = doc1.getEscherStm();
EscherDelayStm eds = doc.getEscherDelayStm(); EscherDelayStm eds = doc1.getEscherDelayStm();
assertNotNull(es); assertNotNull(es);
assertNotNull(eds); assertNotNull(eds);
@ -57,20 +65,21 @@ public final class TestEscherParts extends TestCase {
assertEquals(19, eds.getEscherRecords().length); assertEquals(19, eds.getEscherRecords().length);
// TODO - check contents // TODO - check contents
doc1.close();
// Now do another complex file // Now do another complex file
doc = new HPBFDocument( InputStream is2 = _samples.openResourceAsStream("SampleNewsletter.pub");
_samples.openResourceAsStream("SampleNewsletter.pub") HPBFDocument doc2 = new HPBFDocument(is2);
); is2.close();
es = doc.getEscherStm(); es = doc2.getEscherStm();
eds = doc.getEscherDelayStm(); eds = doc2.getEscherDelayStm();
assertNotNull(es); assertNotNull(es);
assertNotNull(eds); assertNotNull(eds);
assertEquals(51, es.getEscherRecords().length); assertEquals(51, es.getEscherRecords().length);
assertEquals(92, eds.getEscherRecords().length); assertEquals(92, eds.getEscherRecords().length);
doc2.close();
} }
} }

View File

@ -25,6 +25,9 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
@ -36,10 +39,9 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
/** /**
@ -49,13 +51,11 @@ public final class TestExtractor {
/** /**
* Extractor primed on the 2 page basic test data * Extractor primed on the 2 page basic test data
*/ */
private PowerPointExtractor ppe;
private static final String expectText = "This is a test title\nThis is a test subtitle\nThis is on page 1\nThis is the title on page 2\nThis is page two\nIt has several blocks of text\nNone of them have formatting\n"; private static final String expectText = "This is a test title\nThis is a test subtitle\nThis is on page 1\nThis is the title on page 2\nThis is page two\nIt has several blocks of text\nNone of them have formatting\n";
/** /**
* Extractor primed on the 1 page but text-box'd test data * Extractor primed on the 1 page but text-box'd test data
*/ */
private PowerPointExtractor ppe2;
private static final String expectText2 = "Hello, World!!!\nI am just a poor boy\nThis is Times New Roman\nPlain Text \n"; private static final String expectText2 = "Hello, World!!!\nI am just a poor boy\nThis is Times New Roman\nPlain Text \n";
/** /**
@ -63,49 +63,59 @@ public final class TestExtractor {
*/ */
private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
@Before // @Before
public void setUp() throws Exception { // public void setUp() throws Exception {
ppe = new PowerPointExtractor(slTests.getFile("basic_test_ppt_file.ppt").getCanonicalPath()); // ppe = new PowerPointExtractor(slTests.getFile("basic_test_ppt_file.ppt").getCanonicalPath());
ppe2 = new PowerPointExtractor(slTests.getFile("with_textbox.ppt").getCanonicalPath()); // ppe2 = new PowerPointExtractor(slTests.getFile("with_textbox.ppt").getCanonicalPath());
} // }
@After // @After
public void closeResources() throws Exception { // public void closeResources() throws Exception {
ppe2.close(); // ppe2.close();
ppe.close(); // ppe.close();
// }
private PowerPointExtractor openExtractor(String fileName) throws IOException {
InputStream is = slTests.openResourceAsStream(fileName);
try {
return new PowerPointExtractor(is);
} finally {
is.close();
}
} }
@Test @Test
public void testReadSheetText() { public void testReadSheetText() throws IOException {
// Basic 2 page example // Basic 2 page example
String sheetText = ppe.getText(); PowerPointExtractor ppe = openExtractor("basic_test_ppt_file.ppt");
ensureTwoStringsTheSame(expectText, ppe.getText());
ensureTwoStringsTheSame(expectText, sheetText); ppe.close();
// 1 page example with text boxes // 1 page example with text boxes
sheetText = ppe2.getText(); PowerPointExtractor ppe2 = openExtractor("with_textbox.ppt");
ensureTwoStringsTheSame(expectText2, ppe2.getText());
ensureTwoStringsTheSame(expectText2, sheetText); ppe2.close();
} }
@Test @Test
public void testReadNoteText() { public void testReadNoteText() throws IOException {
// Basic 2 page example // Basic 2 page example
PowerPointExtractor ppe = openExtractor("basic_test_ppt_file.ppt");
String notesText = ppe.getNotes(); String notesText = ppe.getNotes();
String expText = "These are the notes for page 1\nThese are the notes on page two, again lacking formatting\n"; String expText = "These are the notes for page 1\nThese are the notes on page two, again lacking formatting\n";
ensureTwoStringsTheSame(expText, notesText); ensureTwoStringsTheSame(expText, notesText);
ppe.close();
// Other one doesn't have notes // Other one doesn't have notes
PowerPointExtractor ppe2 = openExtractor("with_textbox.ppt");
notesText = ppe2.getNotes(); notesText = ppe2.getNotes();
expText = ""; expText = "";
ensureTwoStringsTheSame(expText, notesText); ensureTwoStringsTheSame(expText, notesText);
ppe2.close();
} }
@Test @Test
public void testReadBoth() { public void testReadBoth() throws IOException {
String[] slText = new String[]{ String[] slText = new String[]{
"This is a test title\nThis is a test subtitle\nThis is on page 1\n", "This is a test title\nThis is a test subtitle\nThis is on page 1\n",
"This is the title on page 2\nThis is page two\nIt has several blocks of text\nNone of them have formatting\n" "This is the title on page 2\nThis is page two\nIt has several blocks of text\nNone of them have formatting\n"
@ -115,6 +125,7 @@ public final class TestExtractor {
"These are the notes on page two, again lacking formatting\n" "These are the notes on page two, again lacking formatting\n"
}; };
PowerPointExtractor ppe = openExtractor("basic_test_ppt_file.ppt");
ppe.setSlidesByDefault(true); ppe.setSlidesByDefault(true);
ppe.setNotesByDefault(false); ppe.setNotesByDefault(false);
assertEquals(slText[0] + slText[1], ppe.getText()); assertEquals(slText[0] + slText[1], ppe.getText());
@ -126,6 +137,7 @@ public final class TestExtractor {
ppe.setSlidesByDefault(true); ppe.setSlidesByDefault(true);
ppe.setNotesByDefault(true); ppe.setNotesByDefault(true);
assertEquals(slText[0] + slText[1] + "\n" + ntText[0] + ntText[1], ppe.getText()); assertEquals(slText[0] + slText[1] + "\n" + ntText[0] + ntText[1], ppe.getText());
ppe.close();
} }
/** /**
@ -135,9 +147,8 @@ public final class TestExtractor {
* @throws Exception * @throws Exception
*/ */
@Test @Test
public void testMissingCoreRecords() throws Exception { public void testMissingCoreRecords() throws IOException {
ppe.close(); PowerPointExtractor ppe = openExtractor("missing_core_records.ppt");
ppe = new PowerPointExtractor(slTests.openResourceAsStream("missing_core_records.ppt"));
String text = ppe.getText(true, false); String text = ppe.getText(true, false);
String nText = ppe.getNotes(); String nText = ppe.getNotes();
@ -150,6 +161,8 @@ public final class TestExtractor {
// Slide records were fine // Slide records were fine
assertTrue(text.startsWith("Using Disease Surveillance and Response")); assertTrue(text.startsWith("Using Disease Surveillance and Response"));
ppe.close();
} }
private void ensureTwoStringsTheSame(String exp, String act) { private void ensureTwoStringsTheSame(String exp, String act) {
@ -163,49 +176,37 @@ public final class TestExtractor {
} }
@Test @Test
public void testExtractFromEmbeded() throws Exception { public void testExtractFromEmbeded() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem( InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("excel_with_embeded.xls");
POIDataSamples.getSpreadSheetInstance().openResourceAsStream("excel_with_embeded.xls") POIFSFileSystem fs = new POIFSFileSystem(is);
); DirectoryNode root = fs.getRoot();
HSLFSlideShowImpl ss; PowerPointExtractor ppe1 = assertExtractFromEmbedded(root, "MBD0000A3B6", "Sample PowerPoint file\nThis is the 1st file\nNot much too it\n");
PowerPointExtractor ppe2 = assertExtractFromEmbedded(root, "MBD0000A3B3", "Sample PowerPoint file\nThis is the 2nd file\nNot much too it either\n");
ppe2.close();
ppe1.close();
fs.close();
}
DirectoryNode dirA = (DirectoryNode) private PowerPointExtractor assertExtractFromEmbedded(DirectoryNode root, String entryName, String expected)
fs.getRoot().getEntry("MBD0000A3B6"); throws IOException {
DirectoryNode dirB = (DirectoryNode) DirectoryNode dir = (DirectoryNode)root.getEntry(entryName);
fs.getRoot().getEntry("MBD0000A3B3"); assertTrue(dir.hasEntry("PowerPoint Document"));
assertNotNull(dirA.getEntry("PowerPoint Document"));
assertNotNull(dirB.getEntry("PowerPoint Document"));
// Check the first file // Check the first file
ss = new HSLFSlideShowImpl(dirA); HSLFSlideShowImpl ppt = new HSLFSlideShowImpl(dir);
ppe.close(); PowerPointExtractor ppe = new PowerPointExtractor(ppt);
ppe = new PowerPointExtractor(ss); assertEquals(expected, ppe.getText(true, false));
assertEquals("Sample PowerPoint file\nThis is the 1st file\nNot much too it\n", return ppe;
ppe.getText(true, false)
);
// And the second
ss = new HSLFSlideShowImpl(dirB);
ppe.close();
ppe = new PowerPointExtractor(ss);
assertEquals("Sample PowerPoint file\nThis is the 2nd file\nNot much too it either\n",
ppe.getText(true, false)
);
fs.close();
} }
/** /**
* A powerpoint file with embeded powerpoint files * A powerpoint file with embeded powerpoint files
*/ */
@SuppressWarnings("unused")
@Test @Test
public void testExtractFromOwnEmbeded() throws Exception { public void testExtractFromOwnEmbeded() throws IOException {
String path = "ppt_with_embeded.ppt"; PowerPointExtractor ppe = openExtractor("ppt_with_embeded.ppt");
ppe.close();
ppe = new PowerPointExtractor(POIDataSamples.getSlideShowInstance().openResourceAsStream(path));
List<OLEShape> shapes = ppe.getOLEShapes(); List<OLEShape> shapes = ppe.getOLEShapes();
assertEquals("Expected 6 ole shapes in " + path, 6, shapes.size()); assertEquals("Expected 6 ole shapes", 6, shapes.size());
int num_ppt = 0, num_doc = 0, num_xls = 0; int num_ppt = 0, num_doc = 0, num_xls = 0;
for (OLEShape ole : shapes) { for (OLEShape ole : shapes) {
String name = ole.getInstanceName(); String name = ole.getInstanceName();
@ -217,6 +218,7 @@ public final class TestExtractor {
} else if ("Document".equals(name)) { } else if ("Document".equals(name)) {
HWPFDocument doc = new HWPFDocument(data); HWPFDocument doc = new HWPFDocument(data);
num_doc++; num_doc++;
doc.close();
} else if ("Presentation".equals(name)) { } else if ("Presentation".equals(name)) {
num_ppt++; num_ppt++;
HSLFSlideShow ppt = new HSLFSlideShow(data); HSLFSlideShow ppt = new HSLFSlideShow(data);
@ -227,153 +229,147 @@ public final class TestExtractor {
assertEquals("Expected 2 embedded Word Documents", 2, num_doc); assertEquals("Expected 2 embedded Word Documents", 2, num_doc);
assertEquals("Expected 2 embedded Excel Spreadsheets", 2, num_xls); assertEquals("Expected 2 embedded Excel Spreadsheets", 2, num_xls);
assertEquals("Expected 2 embedded PowerPoint Presentations", 2, num_ppt); assertEquals("Expected 2 embedded PowerPoint Presentations", 2, num_ppt);
ppe.close();
} }
/** /**
* A powerpoint file with embeded powerpoint files * A powerpoint file with embeded powerpoint files
*/ */
@Test @Test
public void test52991() throws Exception { public void test52991() throws IOException {
String path = "badzip.ppt"; PowerPointExtractor ppe = openExtractor("badzip.ppt");
ppe.close(); for (OLEShape shape : ppe.getOLEShapes()) {
ppe = new PowerPointExtractor(POIDataSamples.getSlideShowInstance().openResourceAsStream(path));
List<OLEShape> shapes = ppe.getOLEShapes();
for (OLEShape shape : shapes) {
IOUtils.copy(shape.getObjectData().getData(), new ByteArrayOutputStream()); IOUtils.copy(shape.getObjectData().getData(), new ByteArrayOutputStream());
} }
ppe.close();
} }
/** /**
* From bug #45543 * From bug #45543
*/ */
@Test @Test
public void testWithComments() throws Exception { public void testWithComments() throws IOException {
ppe.close(); PowerPointExtractor ppe1 = openExtractor("WithComments.ppt");
ppe = new PowerPointExtractor(slTests.openResourceAsStream("WithComments.ppt")); String text = ppe1.getText();
String text = ppe.getText();
assertFalse("Comments not in by default", text.contains("This is a test comment")); assertFalse("Comments not in by default", text.contains("This is a test comment"));
ppe.setCommentsByDefault(true); ppe1.setCommentsByDefault(true);
text = ppe.getText(); text = ppe1.getText();
assertContains(text, "This is a test comment"); assertContains(text, "This is a test comment");
ppe1.close();
// And another file // And another file
ppe.close(); PowerPointExtractor ppe2 = openExtractor("45543.ppt");
ppe = new PowerPointExtractor(slTests.openResourceAsStream("45543.ppt")); text = ppe2.getText();
text = ppe.getText();
assertFalse("Comments not in by default", text.contains("testdoc")); assertFalse("Comments not in by default", text.contains("testdoc"));
ppe.setCommentsByDefault(true); ppe2.setCommentsByDefault(true);
text = ppe.getText(); text = ppe2.getText();
assertContains(text, "testdoc"); assertContains(text, "testdoc");
ppe2.close();
} }
/** /**
* From bug #45537 * From bug #45537
*/ */
@Test @Test
public void testHeaderFooter() throws Exception { public void testHeaderFooter() throws IOException {
String text; String text;
// With a header on the notes // With a header on the notes
HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("45537_Header.ppt")); InputStream is1 = slTests.openResourceAsStream("45537_Header.ppt");
HSLFSlideShow ss = new HSLFSlideShow(hslf); HSLFSlideShow ppt1 = new HSLFSlideShow(is1);
assertNotNull(ss.getNotesHeadersFooters()); is1.close();
assertEquals("testdoc test phrase", ss.getNotesHeadersFooters().getHeaderText()); assertNotNull(ppt1.getNotesHeadersFooters());
ppe.close(); assertEquals("testdoc test phrase", ppt1.getNotesHeadersFooters().getHeaderText());
ppe = new PowerPointExtractor(hslf); PowerPointExtractor ppe1 = new PowerPointExtractor(ppt1.getSlideShowImpl());
text = ppe.getText(); text = ppe1.getText();
assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc")); assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc"));
assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase")); assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase"));
ppe.setNotesByDefault(true); ppe1.setNotesByDefault(true);
text = ppe.getText(); text = ppe1.getText();
assertContains(text, "testdoc"); assertContains(text, "testdoc");
assertContains(text, "test phrase"); assertContains(text, "test phrase");
ss.close(); ppe1.close();
ppt1.close();
// And with a footer, also on notes // And with a footer, also on notes
hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("45537_Footer.ppt")); InputStream is2 = slTests.openResourceAsStream("45537_Footer.ppt");
ss = new HSLFSlideShow(hslf); HSLFSlideShow ppt2 = new HSLFSlideShow(is2);
assertNotNull(ss.getNotesHeadersFooters()); is2.close();
assertEquals("testdoc test phrase", ss.getNotesHeadersFooters().getFooterText());
ppe.close();
ppe = new PowerPointExtractor(slTests.openResourceAsStream("45537_Footer.ppt")); assertNotNull(ppt2.getNotesHeadersFooters());
assertEquals("testdoc test phrase", ppt2.getNotesHeadersFooters().getFooterText());
ppt2.close();
text = ppe.getText(); PowerPointExtractor ppe2 = openExtractor("45537_Footer.ppt");
text = ppe2.getText();
assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc")); assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc"));
assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase")); assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase"));
ppe.setNotesByDefault(true); ppe2.setNotesByDefault(true);
text = ppe.getText(); text = ppe2.getText();
assertContains(text, "testdoc"); assertContains(text, "testdoc");
assertContains(text, "test phrase"); assertContains(text, "test phrase");
ppe2.close();
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Test @Test
public void testSlideMasterText() throws Exception { public void testSlideMasterText() throws IOException {
String masterTitleText = "This is the Master Title"; String masterTitleText = "This is the Master Title";
String masterRandomText = "This text comes from the Master Slide"; String masterRandomText = "This text comes from the Master Slide";
String masterFooterText = "Footer from the master slide"; String masterFooterText = "Footer from the master slide";
HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("WithMaster.ppt")); PowerPointExtractor ppe = openExtractor("WithMaster.ppt");
ppe.close(); ppe.setMasterByDefault(true);
ppe = new PowerPointExtractor(hslf);
String text = ppe.getText(); String text = ppe.getText();
//assertContains(text, masterTitleText); // TODO Is this available in PPT? assertContains(text, masterRandomText);
//assertContains(text, masterRandomText); // TODO Extract
assertContains(text, masterFooterText); assertContains(text, masterFooterText);
ppe.close();
} }
@Test @Test
public void testMasterText() throws Exception { public void testMasterText() throws IOException {
ppe.close(); PowerPointExtractor ppe1 = openExtractor("master_text.ppt");
ppe = new PowerPointExtractor(slTests.openResourceAsStream("master_text.ppt"));
// Initially not there // Initially not there
String text = ppe.getText(); String text = ppe1.getText();
assertFalse(text.contains("Text that I added to the master slide")); assertFalse(text.contains("Text that I added to the master slide"));
// Enable, shows up // Enable, shows up
ppe.setMasterByDefault(true); ppe1.setMasterByDefault(true);
text = ppe.getText(); text = ppe1.getText();
assertTrue(text.contains("Text that I added to the master slide")); assertTrue(text.contains("Text that I added to the master slide"));
// Make sure placeholder text does not come out // Make sure placeholder text does not come out
assertFalse(text.contains("Click to edit Master")); assertFalse(text.contains("Click to edit Master"));
ppe1.close();
// Now with another file only containing master text // Now with another file only containing master text
// Will always show up // Will always show up
PowerPointExtractor ppe2 = openExtractor("WithMaster.ppt");
String masterText = "Footer from the master slide"; String masterText = "Footer from the master slide";
HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("WithMaster.ppt"));
ppe.close();
ppe = new PowerPointExtractor(hslf); text = ppe2.getText();
text = ppe.getText();
assertContainsIgnoreCase(text, "master"); assertContainsIgnoreCase(text, "master");
assertContains(text, masterText); assertContains(text, masterText);
ppe2.close();
} }
/** /**
* Bug #54880 Chinese text not extracted properly * Bug #54880 Chinese text not extracted properly
*/ */
@Test @Test
public void testChineseText() throws Exception { public void testChineseText() throws IOException {
HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("54880_chinese.ppt")); PowerPointExtractor ppe = openExtractor("54880_chinese.ppt");
ppe.close();
ppe = new PowerPointExtractor(hslf);
String text = ppe.getText(); String text = ppe.getText();
@ -388,6 +384,7 @@ public final class TestExtractor {
// Check for the chinese only text line // Check for the chinese only text line
assertContains(text, "\uff8a\uff9d\uff76\uff78"); assertContains(text, "\uff8a\uff9d\uff76\uff78");
ppe.close();
} }
/** /**
@ -396,12 +393,15 @@ public final class TestExtractor {
*/ */
@SuppressWarnings("resource") @SuppressWarnings("resource")
@Test @Test
public void testDifferentPOIFS() throws Exception { public void testDifferentPOIFS() throws IOException {
// Open the two filesystems // Open the two filesystems
DirectoryNode[] files = new DirectoryNode[2]; File pptFile = slTests.getFile("basic_test_ppt_file.ppt");
files[0] = (new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt"))).getRoot(); InputStream is1 = new FileInputStream(pptFile);
NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(slTests.getFile("basic_test_ppt_file.ppt")); OPOIFSFileSystem opoifs = new OPOIFSFileSystem(is1);
files[1] = npoifsFileSystem.getRoot(); is1.close();
NPOIFSFileSystem npoifs = new NPOIFSFileSystem(pptFile);
DirectoryNode[] files = { opoifs.getRoot(), npoifs.getRoot() };
// Open directly // Open directly
for (DirectoryNode dir : files) { for (DirectoryNode dir : files) {
@ -409,48 +409,48 @@ public final class TestExtractor {
assertEquals(expectText, extractor.getText()); assertEquals(expectText, extractor.getText());
} }
// Open via a HWPFDocument // Open via a HSLFSlideShow
for (DirectoryNode dir : files) { for (DirectoryNode dir : files) {
HSLFSlideShowImpl slideshow = new HSLFSlideShowImpl(dir); HSLFSlideShowImpl slideshow = new HSLFSlideShowImpl(dir);
PowerPointExtractor extractor = new PowerPointExtractor(slideshow); PowerPointExtractor extractor = new PowerPointExtractor(slideshow);
assertEquals(expectText, extractor.getText()); assertEquals(expectText, extractor.getText());
extractor.close();
slideshow.close();
} }
npoifsFileSystem.close(); npoifs.close();
} }
@Test @Test
public void testTable() throws Exception { public void testTable() throws Exception {
// ppe = new PowerPointExtractor(slTests.openResourceAsStream("54111.ppt")); PowerPointExtractor ppe1 = openExtractor("54111.ppt");
// String text = ppe.getText(); String text1 = ppe1.getText();
// String target = "TH Cell 1\tTH Cell 2\tTH Cell 3\tTH Cell 4\n"+ String target1 = "TH Cell 1\tTH Cell 2\tTH Cell 3\tTH Cell 4\n"+
// "Row 1, Cell 1\tRow 1, Cell 2\tRow 1, Cell 3\tRow 1, Cell 4\n"+ "Row 1, Cell 1\tRow 1, Cell 2\tRow 1, Cell 3\tRow 1, Cell 4\n"+
// "Row 2, Cell 1\tRow 2, Cell 2\tRow 2, Cell 3\tRow 2, Cell 4\n"+ "Row 2, Cell 1\tRow 2, Cell 2\tRow 2, Cell 3\tRow 2, Cell 4\n"+
// "Row 3, Cell 1\tRow 3, Cell 2\tRow 3, Cell 3\tRow 3, Cell 4\n"+ "Row 3, Cell 1\tRow 3, Cell 2\tRow 3, Cell 3\tRow 3, Cell 4\n"+
// "Row 4, Cell 1\tRow 4, Cell 2\tRow 4, Cell 3\tRow 4, Cell 4\n"+ "Row 4, Cell 1\tRow 4, Cell 2\tRow 4, Cell 3\tRow 4, Cell 4\n"+
// "Row 5, Cell 1\tRow 5, Cell 2\tRow 5, Cell 3\tRow 5, Cell 4\n"; "Row 5, Cell 1\tRow 5, Cell 2\tRow 5, Cell 3\tRow 5, Cell 4\n";
// assertTrue(text.contains(target)); assertTrue(text1.contains(target1));
ppe.close(); ppe1.close();
ppe = new PowerPointExtractor(slTests.openResourceAsStream("54722.ppt")); PowerPointExtractor ppe2 = openExtractor("54722.ppt");
String text = ppe.getText(); String text2 = ppe2.getText();
String target = "this\tText\tis\twithin\ta\n" + String target2 = "this\tText\tis\twithin\ta\n" +
"table\t1\t2\t3\t4"; "table\t1\t2\t3\t4";
assertTrue(text.contains(target)); assertTrue(text2.contains(target2));
ppe2.close();
} }
// bug 60003 // bug 60003
@Test @Test
public void testExtractMasterSlideFooterText() throws Exception { public void testExtractMasterSlideFooterText() throws Exception {
HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("60003.ppt")); PowerPointExtractor ppe = openExtractor("60003.ppt");
ppe.close();
ppe = new PowerPointExtractor(hslf);
ppe.setMasterByDefault(true); ppe.setMasterByDefault(true);
String text = ppe.getText(); String text = ppe.getText();
assertContains(text, "Prague"); assertContains(text, "Prague");
hslf.close(); ppe.close();
} }
} }

View File

@ -52,7 +52,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testSimpleExcel3() throws Exception { public void testSimpleExcel3() throws IOException {
OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls");
// Check we can call getText without error // Check we can call getText without error
@ -78,7 +78,7 @@ public final class TestOldExcelExtractor {
@Test @Test
public void testSimpleExcel3NoReading() throws Exception { public void testSimpleExcel3NoReading() throws IOException {
OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls");
assertNotNull(extractor); assertNotNull(extractor);
@ -86,7 +86,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testSimpleExcel4() throws Exception { public void testSimpleExcel4() throws IOException {
OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls");
// Check we can call getText without error // Check we can call getText without error
@ -108,7 +108,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testSimpleExcel5() throws Exception { public void testSimpleExcel5() throws IOException {
for (String ver : new String[] {"5", "95"}) { for (String ver : new String[] {"5", "95"}) {
OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls");
@ -135,7 +135,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testStrings() throws Exception { public void testStrings() throws IOException {
OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls");
String text = extractor.getText(); String text = extractor.getText();
@ -156,7 +156,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testFormattedNumbersExcel4() throws Exception { public void testFormattedNumbersExcel4() throws IOException {
OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls");
String text = extractor.getText(); String text = extractor.getText();
@ -177,7 +177,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testFormattedNumbersExcel5() throws Exception { public void testFormattedNumbersExcel5() throws IOException {
for (String ver : new String[] {"5", "95"}) { for (String ver : new String[] {"5", "95"}) {
OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls"); OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls");
String text = extractor.getText(); String text = extractor.getText();
@ -204,7 +204,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testFromFile() throws Exception { public void testFromFile() throws IOException {
for (String ver : new String[] {"4", "5", "95"}) { for (String ver : new String[] {"4", "5", "95"}) {
String filename = "testEXCEL_"+ver+".xls"; String filename = "testEXCEL_"+ver+".xls";
File f = HSSFTestDataSamples.getSampleFile(filename); File f = HSSFTestDataSamples.getSampleFile(filename);
@ -218,47 +218,39 @@ public final class TestOldExcelExtractor {
} }
} }
@Test @Test(expected=OfficeXmlFileException.class)
public void testOpenInvalidFile() throws Exception { public void testOpenInvalidFile1() throws IOException {
// a file that exists, but is a different format // a file that exists, but is a different format
try {
createExtractor("WithVariousData.xlsx"); createExtractor("WithVariousData.xlsx");
fail("Should catch Exception here");
} catch (OfficeXmlFileException e) {
// expected here
} }
@Test(expected=RecordFormatException.class)
public void testOpenInvalidFile2() throws IOException {
// a completely different type of file // a completely different type of file
try {
createExtractor("48936-strings.txt"); createExtractor("48936-strings.txt");
fail("Should catch Exception here");
} catch (RecordFormatException e) {
// expected here
} }
@Test(expected=FileNotFoundException.class)
public void testOpenInvalidFile3() throws IOException {
// a POIFS file which is not a Workbook // a POIFS file which is not a Workbook
InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream("47304.doc");
try { try {
new OldExcelExtractor(POIDataSamples.getDocumentInstance().getFile("47304.doc")); new OldExcelExtractor(is).close();
fail("Should catch Exception here"); } finally {
} catch (FileNotFoundException e) { is.close();
// expected here
} }
} }
@Test @Test(expected=EmptyFileException.class)
public void testOpenNonExistingFile() throws Exception { public void testOpenNonExistingFile() throws IOException {
// a file that exists, but is a different format // a file that exists, but is a different format
try {
OldExcelExtractor extractor = new OldExcelExtractor(new File("notexistingfile.xls")); OldExcelExtractor extractor = new OldExcelExtractor(new File("notexistingfile.xls"));
extractor.close(); extractor.close();
fail("Should catch Exception here");
} catch (EmptyFileException e) {
// expected here
}
} }
@Test @Test
public void testInputStream() throws Exception { public void testInputStream() throws IOException {
File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls");
InputStream stream = new FileInputStream(file); InputStream stream = new FileInputStream(file);
try { try {
@ -272,7 +264,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testInputStreamNPOIHeader() throws Exception { public void testInputStreamNPOIHeader() throws IOException {
File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls");
InputStream stream = new FileInputStream(file); InputStream stream = new FileInputStream(file);
try { try {
@ -284,7 +276,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testNPOIFSFileSystem() throws Exception { public void testNPOIFSFileSystem() throws IOException {
File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls");
NPOIFSFileSystem fs = new NPOIFSFileSystem(file); NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
try { try {
@ -296,7 +288,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testDirectoryNode() throws Exception { public void testDirectoryNode() throws IOException {
File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls");
NPOIFSFileSystem fs = new NPOIFSFileSystem(file); NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
try { try {
@ -308,7 +300,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testDirectoryNodeInvalidFile() throws Exception { public void testDirectoryNodeInvalidFile() throws IOException {
File file = POIDataSamples.getDocumentInstance().getFile("test.doc"); File file = POIDataSamples.getDocumentInstance().getFile("test.doc");
NPOIFSFileSystem fs = new NPOIFSFileSystem(file); NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
try { try {
@ -324,7 +316,7 @@ public final class TestOldExcelExtractor {
@Ignore("Calls System.exit()") @Ignore("Calls System.exit()")
@Test @Test
public void testMainUsage() throws Exception { public void testMainUsage() throws IOException {
PrintStream save = System.err; PrintStream save = System.err;
try { try {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
@ -341,7 +333,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testMain() throws Exception { public void testMain() throws IOException {
File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls");
PrintStream save = System.out; PrintStream save = System.out;
try { try {
@ -362,7 +354,7 @@ public final class TestOldExcelExtractor {
} }
@Test @Test
public void testEncryptionException() throws Exception { public void testEncryptionException() throws IOException {
//test file derives from Common Crawl //test file derives from Common Crawl
File file = HSSFTestDataSamples.getSampleFile("60284.xls"); File file = HSSFTestDataSamples.getSampleFile("60284.xls");
OldExcelExtractor ex = new OldExcelExtractor(file); OldExcelExtractor ex = new OldExcelExtractor(file);

View File

@ -16,6 +16,7 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.model; package org.apache.poi.hssf.model;
import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -32,9 +33,6 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.xml.bind.DatatypeConverter;
import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.DefaultEscherRecordFactory;
import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherContainerRecord;
@ -59,7 +57,6 @@ import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFTestHelper; import org.apache.poi.hssf.usermodel.HSSFTestHelper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.HexDump; import org.apache.poi.util.HexDump;
import org.apache.poi.util.IOUtils;
import org.junit.Test; import org.junit.Test;
public class TestDrawingAggregate { public class TestDrawingAggregate {
@ -946,32 +943,4 @@ public class TestDrawingAggregate {
assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length);
assertTrue("drawing data brefpore and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); assertTrue("drawing data brefpore and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave));
} }
/**
* Decompress previously gziped/base64ed data
*
* @param data the gziped/base64ed data
* @return the raw bytes
* @throws IOException if you copy and pasted the data wrong
*/
public static byte[] decompress(String data) throws IOException {
byte[] base64Bytes = DatatypeConverter.parseBase64Binary(data);
return IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(base64Bytes)));
}
/**
* Compress raw data for test runs - usually called while debugging :)
*
* @param data the raw data
* @return the gziped/base64ed data as String
* @throws IOException usually not ...
*/
public static String compress(byte[] data) throws IOException {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.util.zip.GZIPOutputStream gz = new java.util.zip.GZIPOutputStream(bos);
gz.write(data);
gz.finish();
return DatatypeConverter.printBase64Binary(bos.toByteArray());
}
} }

View File

@ -18,22 +18,22 @@
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianByteArrayInputStream;
import org.apache.poi.util.LittleEndianInput; import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
/** /**
* Tests the serialization and deserialization of the StringRecord * Tests the serialization and deserialization of the StringRecord
* class works correctly. Test data taken directly from a real * class works correctly. Test data taken directly from a real
* Excel file. * Excel file.
*
* @author Glen Stampoultzis (glens at apache.org)
*/ */
public final class TestStringRecord extends TestCase { public final class TestStringRecord {
private static final byte[] data = HexRead.readFromString( private static final byte[] data = HexRead.readFromString(
"0B 00 " + // length "0B 00 " + // length
"00 " + // option "00 " + // option
@ -41,6 +41,7 @@ public final class TestStringRecord extends TestCase {
"46 61 68 72 7A 65 75 67 74 79 70" "46 61 68 72 7A 65 75 67 74 79 70"
); );
@Test
public void testLoad() { public void testLoad() {
StringRecord record = new StringRecord(TestcaseRecordInputStream.create(0x207, data)); StringRecord record = new StringRecord(TestcaseRecordInputStream.create(0x207, data));
@ -49,17 +50,20 @@ public final class TestStringRecord extends TestCase {
assertEquals( 18, record.getRecordSize() ); assertEquals( 18, record.getRecordSize() );
} }
@Test
public void testStore() { public void testStore() {
StringRecord record = new StringRecord(); StringRecord record = new StringRecord();
record.setString("Fahrzeugtyp"); record.setString("Fahrzeugtyp");
byte [] recordBytes = record.serialize(); byte [] recordBytes = record.serialize();
assertEquals(recordBytes.length - 4, data.length); assertEquals(recordBytes.length - 4, data.length);
for (int i = 0; i < data.length; i++) for (int i = 0; i < data.length; i++) {
assertEquals("At offset " + i, data[i], recordBytes[i+4]); assertEquals("At offset " + i, data[i], recordBytes[i+4]);
} }
}
public void testContinue() { @Test
public void testContinue() throws IOException {
int MAX_BIFF_DATA = RecordInputStream.MAX_RECORD_DATA_SIZE; int MAX_BIFF_DATA = RecordInputStream.MAX_RECORD_DATA_SIZE;
int TEXT_LEN = MAX_BIFF_DATA + 1000; // deliberately over-size int TEXT_LEN = MAX_BIFF_DATA + 1000; // deliberately over-size
String textChunk = "ABCDEGGHIJKLMNOP"; // 16 chars String textChunk = "ABCDEGGHIJKLMNOP"; // 16 chars
@ -74,15 +78,14 @@ public final class TestStringRecord extends TestCase {
byte[] ser = sr.serialize(); byte[] ser = sr.serialize();
assertEquals(StringRecord.sid, LittleEndian.getUShort(ser, 0)); assertEquals(StringRecord.sid, LittleEndian.getUShort(ser, 0));
if (LittleEndian.getUShort(ser, 2) > MAX_BIFF_DATA) { if (LittleEndian.getUShort(ser, 2) > MAX_BIFF_DATA) {
throw new AssertionFailedError( fail("StringRecord should have been split with a continue record");
"StringRecord should have been split with a continue record");
} }
// Confirm expected size of first record, and ushort strLen. // Confirm expected size of first record, and ushort strLen.
assertEquals(MAX_BIFF_DATA, LittleEndian.getUShort(ser, 2)); assertEquals(MAX_BIFF_DATA, LittleEndian.getUShort(ser, 2));
assertEquals(TEXT_LEN, LittleEndian.getUShort(ser, 4)); assertEquals(TEXT_LEN, LittleEndian.getUShort(ser, 4));
// Confirm first few bytes of ContinueRecord // Confirm first few bytes of ContinueRecord
LittleEndianInput crIn = new LittleEndianByteArrayInputStream(ser, (MAX_BIFF_DATA + 4)); LittleEndianByteArrayInputStream crIn = new LittleEndianByteArrayInputStream(ser, (MAX_BIFF_DATA + 4));
int nCharsInFirstRec = MAX_BIFF_DATA - (2 + 1); // strLen, optionFlags int nCharsInFirstRec = MAX_BIFF_DATA - (2 + 1); // strLen, optionFlags
int nCharsInSecondRec = TEXT_LEN - nCharsInFirstRec; int nCharsInSecondRec = TEXT_LEN - nCharsInFirstRec;
assertEquals(ContinueRecord.sid, crIn.readUShort()); assertEquals(ContinueRecord.sid, crIn.readUShort());
@ -95,5 +98,6 @@ public final class TestStringRecord extends TestCase {
RecordInputStream in = TestcaseRecordInputStream.create(ser); RecordInputStream in = TestcaseRecordInputStream.create(ser);
StringRecord sr2 = new StringRecord(in); StringRecord sr2 = new StringRecord(in);
assertEquals(sb.toString(), sr2.getString()); assertEquals(sb.toString(), sr2.getString());
crIn.close();
} }
} }

View File

@ -16,7 +16,7 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import static org.apache.poi.hssf.model.TestDrawingAggregate.decompress; import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -41,6 +41,7 @@ import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test; import org.junit.Test;
/** /**
@ -102,7 +103,7 @@ public final class TestHSSFComment extends BaseTestCellComment {
public void testBug56380InsertComments() throws Exception { public void testBug56380InsertComments() throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
int noOfRows = 1025; int noOfRows = 1025;
String comment = "c"; String comment = "c";
@ -139,7 +140,7 @@ public final class TestHSSFComment extends BaseTestCellComment {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
try { try {
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
String comment = "c"; String comment = "c";
for(int rowNum = 0;rowNum < 258;rowNum++) { for(int rowNum = 0;rowNum < 258;rowNum++) {
@ -179,7 +180,7 @@ public final class TestHSSFComment extends BaseTestCellComment {
} }
} }
private Comment insertComment(Drawing drawing, Cell cell, String message) { private Comment insertComment(Drawing<?> drawing, Cell cell, String message) {
CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper(); CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper();
ClientAnchor anchor = factory.createClientAnchor(); ClientAnchor anchor = factory.createClientAnchor();
@ -272,7 +273,7 @@ public final class TestHSSFComment extends BaseTestCellComment {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sh = wb.createSheet(); HSSFSheet sh = wb.createSheet();
HSSFPatriarch patriarch = sh.createDrawingPatriarch(); HSSFPatriarch patriarch = sh.createDrawingPatriarch();
int idx = wb.addPicture(new byte[]{1,2,3}, HSSFWorkbook.PICTURE_TYPE_PNG); int idx = wb.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_PNG);
HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
comment.setColumn(5); comment.setColumn(5);

View File

@ -17,7 +17,7 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import static org.apache.poi.hssf.model.TestDrawingAggregate.decompress; import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;

View File

@ -17,7 +17,7 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import static org.apache.poi.hssf.model.TestDrawingAggregate.decompress; import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@ -16,11 +16,17 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.poifs.storage; package org.apache.poi.poifs.storage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import javax.xml.bind.DatatypeConverter;
import org.apache.poi.util.HexDump; import org.apache.poi.util.HexDump;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import org.apache.poi.util.IOUtils;
/** /**
* Test utility class.<br/> * Test utility class.<br/>
@ -81,4 +87,31 @@ public final class RawDataUtil {
throw new RuntimeException("different"); throw new RuntimeException("different");
} }
} }
/**
* Decompress previously gziped/base64ed data
*
* @param data the gziped/base64ed data
* @return the raw bytes
* @throws IOException if you copy and pasted the data wrong
*/
public static byte[] decompress(String data) throws IOException {
byte[] base64Bytes = DatatypeConverter.parseBase64Binary(data);
return IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(base64Bytes)));
}
/**
* Compress raw data for test runs - usually called while debugging :)
*
* @param data the raw data
* @return the gziped/base64ed data as String
* @throws IOException usually not ...
*/
public static String compress(byte[] data) throws IOException {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.util.zip.GZIPOutputStream gz = new java.util.zip.GZIPOutputStream(bos);
gz.write(data);
gz.finish();
return DatatypeConverter.printBase64Binary(bos.toByteArray());
}
} }

View File

@ -17,6 +17,23 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.text.AttributedString;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
@ -30,18 +47,6 @@ import org.junit.Assume;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.text.AttributedString;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
/** /**
* A base class for bugzilla issues that can be described in terms of common ss interfaces. * A base class for bugzilla issues that can be described in terms of common ss interfaces.
* *
@ -70,9 +75,10 @@ public abstract class BaseTestBugzillaIssues {
public static void assertAlmostEquals(double expected, double actual, float factor) { public static void assertAlmostEquals(double expected, double actual, float factor) {
double diff = Math.abs(expected - actual); double diff = Math.abs(expected - actual);
double fuzz = expected * factor; double fuzz = expected * factor;
if (diff > fuzz) if (diff > fuzz) {
fail(actual + " not within " + fuzz + " of " + expected); fail(actual + " not within " + fuzz + " of " + expected);
} }
}
/** /**
* Test writing a hyperlink * Test writing a hyperlink
@ -359,7 +365,9 @@ public abstract class BaseTestBugzillaIssues {
fmla.append(name); fmla.append(name);
fmla.append("("); fmla.append("(");
for(int i=0; i < maxArgs; i++){ for(int i=0; i < maxArgs; i++){
if(i > 0) fmla.append(','); if(i > 0) {
fmla.append(',');
}
fmla.append("A1"); fmla.append("A1");
} }
fmla.append(")"); fmla.append(")");
@ -512,9 +520,15 @@ public abstract class BaseTestBugzillaIssues {
private static void copyAttributes(Font font, AttributedString str, int endIdx) { private static void copyAttributes(Font font, AttributedString str, int endIdx) {
str.addAttribute(TextAttribute.FAMILY, font.getFontName(), 0, endIdx); str.addAttribute(TextAttribute.FAMILY, font.getFontName(), 0, endIdx);
str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints()); str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints());
if (font.getBold()) str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, endIdx); if (font.getBold()) {
if (font.getItalic() ) str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, 0, endIdx); str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, endIdx);
if (font.getUnderline() == Font.U_SINGLE ) str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 0, endIdx); }
if (font.getItalic() ) {
str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, 0, endIdx);
}
if (font.getUnderline() == Font.U_SINGLE ) {
str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 0, endIdx);
}
} }
/** /**
@ -1063,7 +1077,7 @@ public abstract class BaseTestBugzillaIssues {
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = factory.createClientAnchor(); ClientAnchor anchor = factory.createClientAnchor();
Cell cell0 = sheet.createRow(0).createCell(0); Cell cell0 = sheet.createRow(0).createCell(0);
@ -1513,7 +1527,7 @@ public abstract class BaseTestBugzillaIssues {
CreationHelper helper = wb.getCreationHelper(); CreationHelper helper = wb.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor(); ClientAnchor anchor = helper.createClientAnchor();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -1677,7 +1691,7 @@ public abstract class BaseTestBugzillaIssues {
assertEquals(10, row.getRowNum()); assertEquals(10, row.getRowNum());
for (Cell cell : row) { for (Cell cell : row) {
String cellValue = null; String cellValue;
switch (cell.getCellTypeEnum()) { switch (cell.getCellTypeEnum()) {
case STRING: case STRING:
cellValue = cell.getRichStringCellValue().getString(); cellValue = cell.getRichStringCellValue().getString();
@ -1685,6 +1699,9 @@ public abstract class BaseTestBugzillaIssues {
case FORMULA: case FORMULA:
cellValue = cell.getCellFormula(); cellValue = cell.getCellFormula();
break; break;
default:
fail("unexpected cell type");
return;
} }
assertNotNull(cellValue); assertNotNull(cellValue);
cellValue = cellValue.isEmpty() ? null : cellValue; cellValue = cellValue.isEmpty() ? null : cellValue;

View File

@ -253,7 +253,7 @@ public abstract class BaseTestCell {
Font f = wb1.createFont(); Font f = wb1.createFont();
f.setFontHeightInPoints((short) 20); f.setFontHeightInPoints((short) 20);
f.setColor(IndexedColors.RED.getIndex()); f.setColor(IndexedColors.RED.getIndex());
f.setBoldweight(Font.BOLDWEIGHT_BOLD); f.setBold(true);
f.setFontName("Arial Unicode MS"); f.setFontName("Arial Unicode MS");
cs.setFillBackgroundColor((short)3); cs.setFillBackgroundColor((short)3);
cs.setFont(f); cs.setFont(f);
@ -718,7 +718,7 @@ public abstract class BaseTestCell {
assertFalse(style.getHidden()); assertFalse(style.getHidden());
assertEquals(0, style.getIndention()); assertEquals(0, style.getIndention());
assertEquals(0, style.getFontIndex()); assertEquals(0, style.getFontIndex());
assertEquals(0, style.getAlignment()); assertEquals(HorizontalAlignment.GENERAL, style.getAlignmentEnum());
assertEquals(0, style.getDataFormat()); assertEquals(0, style.getDataFormat());
assertEquals(false, style.getWrapText()); assertEquals(false, style.getWrapText());
@ -1004,7 +1004,7 @@ public abstract class BaseTestCell {
anchor.setRow1(row.getRowNum()); anchor.setRow1(row.getRowNum());
anchor.setRow2(row.getRowNum()+3); anchor.setRow2(row.getRowNum()+3);
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
Comment comment = drawing.createCellComment(anchor); Comment comment = drawing.createCellComment(anchor);
RichTextString str = factory.createRichTextString("Hello, World!"); RichTextString str = factory.createRichTextString("Hello, World!");
comment.setString(str); comment.setString(str);

View File

@ -77,7 +77,7 @@ public abstract class BaseTestCellComment {
assertNull(cell.getCellComment()); assertNull(cell.getCellComment());
assertNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); assertNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn)));
Drawing patr = sheet.createDrawingPatriarch(); Drawing<?> patr = sheet.createDrawingPatriarch();
ClientAnchor anchor = factory.createClientAnchor(); ClientAnchor anchor = factory.createClientAnchor();
anchor.setCol1(2); anchor.setCol1(2);
anchor.setCol2(5); anchor.setCol2(5);
@ -261,7 +261,7 @@ public abstract class BaseTestCellComment {
Cell cell = sheet.createRow(3).createCell(5); Cell cell = sheet.createRow(3).createCell(5);
cell.setCellValue("F4"); cell.setCellValue("F4");
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = factory.createClientAnchor(); ClientAnchor anchor = factory.createClientAnchor();
Comment comment = drawing.createCellComment(anchor); Comment comment = drawing.createCellComment(anchor);
@ -294,7 +294,7 @@ public abstract class BaseTestCellComment {
Cell cell = row.createCell(5); Cell cell = row.createCell(5);
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
double r_mul, c_mul; double r_mul, c_mul;
if (sheet instanceof HSSFSheet) { if (sheet instanceof HSSFSheet) {
@ -365,7 +365,7 @@ public abstract class BaseTestCellComment {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();
Drawing patriarch = sh.createDrawingPatriarch(); Drawing<?> patriarch = sh.createDrawingPatriarch();
patriarch.createCellComment(factory.createClientAnchor()); patriarch.createCellComment(factory.createClientAnchor());
try { try {
@ -388,7 +388,7 @@ public abstract class BaseTestCellComment {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();
Drawing patriarch = sh.createDrawingPatriarch(); Drawing<?> patriarch = sh.createDrawingPatriarch();
Comment comment = patriarch.createCellComment(factory.createClientAnchor()); Comment comment = patriarch.createCellComment(factory.createClientAnchor());
assertEquals(CellAddress.A1, comment.getAddress()); assertEquals(CellAddress.A1, comment.getAddress());
@ -402,7 +402,7 @@ public abstract class BaseTestCellComment {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();
Drawing patriarch = sh.createDrawingPatriarch(); Drawing<?> patriarch = sh.createDrawingPatriarch();
Comment comment = patriarch.createCellComment(factory.createClientAnchor()); Comment comment = patriarch.createCellComment(factory.createClientAnchor());
assertEquals(CellAddress.A1, comment.getAddress()); assertEquals(CellAddress.A1, comment.getAddress());

View File

@ -105,7 +105,7 @@ public abstract class BaseTestPicture {
private void handleResize(Workbook wb, Sheet sheet, Row row) throws IOException { private void handleResize(Workbook wb, Sheet sheet, Row row) throws IOException {
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper createHelper = wb.getCreationHelper(); CreationHelper createHelper = wb.getCreationHelper();
final byte[] bytes = HSSFITestDataProvider.instance.getTestDataFileContent("logoKarmokar4.png"); final byte[] bytes = HSSFITestDataProvider.instance.getTestDataFileContent("logoKarmokar4.png");

View File

@ -1141,7 +1141,7 @@ public abstract class BaseTestSheet {
public void getCellComment() throws IOException { public void getCellComment() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
Drawing dg = sheet.createDrawingPatriarch(); Drawing<?> dg = sheet.createDrawingPatriarch();
Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor()); Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor());
Cell cell = sheet.createRow(9).createCell(2); Cell cell = sheet.createRow(9).createCell(2);
comment.setAuthor("test C10 author"); comment.setAuthor("test C10 author");
@ -1165,7 +1165,7 @@ public abstract class BaseTestSheet {
// a sheet with no cell comments should return an empty map (not null or raise NPE). // a sheet with no cell comments should return an empty map (not null or raise NPE).
assertEquals(Collections.emptyMap(), sheet.getCellComments()); assertEquals(Collections.emptyMap(), sheet.getCellComments());
Drawing dg = sheet.createDrawingPatriarch(); Drawing<?> dg = sheet.createDrawingPatriarch();
ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
int nRows = 5; int nRows = 5;

View File

@ -33,7 +33,6 @@ import java.io.OutputStream;
import java.util.ConcurrentModificationException; import java.util.ConcurrentModificationException;
import java.util.Iterator; import java.util.Iterator;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
@ -908,7 +907,7 @@ public abstract class BaseTestWorkbook {
Sheet sheet = wb.createSheet("Main Sheet"); Sheet sheet = wb.createSheet("Main Sheet");
Row row0 = sheet.createRow(0); Row row0 = sheet.createRow(0);
Row row1 = sheet.createRow(1); Row row1 = sheet.createRow(1);
Cell cell = row1.createCell(0); row1.createCell(0);
row0.createCell(1); row0.createCell(1);
row1.createCell(0); row1.createCell(0);
row1.createCell(1); row1.createCell(1);
@ -916,7 +915,7 @@ public abstract class BaseTestWorkbook {
byte[] pictureData = _testDataProvider.getTestDataFileContent("logoKarmokar4.png"); byte[] pictureData = _testDataProvider.getTestDataFileContent("logoKarmokar4.png");
int handle = wb.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG); int handle = wb.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG);
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper helper = wb.getCreationHelper(); CreationHelper helper = wb.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor(); ClientAnchor anchor = helper.createClientAnchor();
anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);