sonar fixes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1884874 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2020-12-28 14:06:24 +00:00
parent 0ab727bbde
commit 77fc30c0e0
17 changed files with 406 additions and 412 deletions

View File

@ -16,6 +16,7 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.stress; package org.apache.poi.stress;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeFalse;
@ -108,7 +109,7 @@ public class HPSFFileHandler extends POIFSFileHandler {
try { try {
System.setOut(psNew); System.setOut(psNew);
CopyCompare.main(new String[]{file.getAbsolutePath(), copyOutput.getAbsolutePath()}); CopyCompare.main(new String[]{file.getAbsolutePath(), copyOutput.getAbsolutePath()});
assertEquals("Equal" + NL, new String(bos.toByteArray(), StandardCharsets.UTF_8)); assertEquals("Equal" + NL, bos.toString(StandardCharsets.UTF_8.name()));
} finally { } finally {
System.setOut(ps); System.setOut(ps);
} }
@ -128,7 +129,8 @@ public class HPSFFileHandler extends POIFSFileHandler {
// a test-case to test this locally without executing the full TestAllFiles // a test-case to test this locally without executing the full TestAllFiles
@Test @Test
public void testExtractor() throws Exception { public void testExtractor() {
handleExtracting(new File("test-data/hpsf/TestBug44375.xls")); File file = new File("test-data/hpsf/TestBug44375.xls");
assertDoesNotThrow(() -> handleExtracting(file));
} }
} }

View File

@ -16,6 +16,7 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.stress; package org.apache.poi.stress;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File; import java.io.File;
@ -64,8 +65,8 @@ public class HWPFFileHandler extends POIFSFileHandler {
} }
@Test @Test
public void testExtractingOld() throws Exception { public void testExtractingOld() {
File file = new File("test-data/document/52117.doc"); File file = new File("test-data/document/52117.doc");
handleExtracting(file); assertDoesNotThrow(() -> handleExtracting(file));
} }
} }

View File

@ -19,6 +19,7 @@
package org.apache.poi.stress; package org.apache.poi.stress;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File; import java.io.File;
@ -210,11 +211,12 @@ public class POIFileScanner {
@Test @Test
public void testDetectUnnamedFile() throws IOException { public void testDetectUnnamedFile() throws IOException {
POIFileScanner.detectUnnamedFile(new File(ROOT_DIR, "spreadsheet"), "49156.xlsx"); File root = new File(ROOT_DIR, "spreadsheet");
assertDoesNotThrow(() -> POIFileScanner.detectUnnamedFile(root, "49156.xlsx"));
} }
@Test @Test
public void test() throws IOException { public void test() throws IOException {
POIFileScanner.scan(ROOT_DIR); assertDoesNotThrow(() -> POIFileScanner.scan(ROOT_DIR));
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.extractor.ooxml; package org.apache.poi.extractor.ooxml;
import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.extractor.ExtractorFactory.createExtractor;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -28,6 +29,7 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Stream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.ExtractorFactory;
@ -46,7 +48,12 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor; import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlException;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
/** /**
* Test that the extractor factory plays nicely * Test that the extractor factory plays nicely
@ -100,69 +107,94 @@ public class TestExtractorFactory {
return file; return file;
} }
private static final Object[] TEST_SET = { public static Stream<Arguments> testOOXMLData() {
"Excel", xls, "ExcelExtractor", 200, return Stream.of(
"Excel - xlsx", xlsx, "XSSFExcelExtractor", 200, Arguments.of("Excel - xlsx", xlsx, "XSSFExcelExtractor", 200),
"Excel - xltx", xltx, "XSSFExcelExtractor", -1, Arguments.of("Excel - xltx", xltx, "XSSFExcelExtractor", -1),
"Excel - xlsb", xlsb, "XSSFBEventBasedExcelExtractor", -1, Arguments.of("Excel - xlsb", xlsb, "XSSFBEventBasedExcelExtractor", -1),
"Word", doc, "WordExtractor", 120, Arguments.of("Word - docx", docx, "XWPFWordExtractor", 120),
"Word - docx", docx, "XWPFWordExtractor", 120, Arguments.of("Word - dotx", dotx, "XWPFWordExtractor", -1),
"Word - dotx", dotx, "XWPFWordExtractor", -1, Arguments.of("PowerPoint - pptx", pptx, "XSLFExtractor", 120),
"Word 6", doc6, "Word6Extractor", 20, Arguments.of("Visio - vsdx", vsdx, "XDGFVisioExtractor", 20)
"Word 95", doc95, "Word6Extractor", 120, );
"PowerPoint", ppt, "SlideShowExtractor", 120,
"PowerPoint - pptx", pptx, "XSLFExtractor", 120,
"Visio", vsd, "VisioTextExtractor", 50,
"Visio - vsdx", vsdx, "XDGFVisioExtractor", 20,
"Publisher", pub, "PublisherTextExtractor", 50,
"Outlook msg", msg, "OutlookTextExtractor", 50,
// TODO Support OOXML-Strict, see bug #57699
// xlsxStrict
}; };
@FunctionalInterface public static Stream<Arguments> testScratchData() {
interface FunctionEx<T, R> { return Stream.of(
R apply(T t) throws IOException, OpenXML4JException, XmlException; Arguments.of("Excel", xls, "ExcelExtractor", 200),
Arguments.of("Word", doc, "WordExtractor", 120),
Arguments.of("Word 6", doc6, "Word6Extractor", 20),
Arguments.of("Word 95", doc95, "Word6Extractor", 120),
Arguments.of("PowerPoint", ppt, "SlideShowExtractor", 120),
Arguments.of("Visio", vsd, "VisioTextExtractor", 50),
Arguments.of("Publisher", pub, "PublisherTextExtractor", 50),
Arguments.of("Outlook msg", msg, "OutlookTextExtractor", 50)
);
};
public static Stream<Arguments> testFileData() {
return Stream.concat(testOOXMLData(), testScratchData());
// TODO Support OOXML-Strict / xlsxStrict, see bug #57699
};
@ParameterizedTest
@MethodSource("testFileData")
public void testFile(String testcase, File file, String extractor, int count) throws Exception {
try (POITextExtractor ext = createExtractor(file)) {
assertNotNull(ext);
testExtractor(ext, testcase, extractor, count);
}
} }
@SuppressWarnings("ConstantConditions") @ParameterizedTest
@Test @MethodSource("testScratchData")
public void testFile() throws Exception { public void testPOIFS(String testcase, File testFile, String extractor, int count) throws Exception {
for (int i = 0; i < TEST_SET.length; i += 4) { // test processing of InputStream
try (POITextExtractor ext = ExtractorFactory.createExtractor((File) TEST_SET[i + 1])) { try (FileInputStream fis = new FileInputStream(testFile);
testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]); POIFSFileSystem poifs = new POIFSFileSystem(fis);
} POITextExtractor ext = createExtractor(poifs)) {
assertNotNull(ext);
testExtractor(ext, testcase, extractor, count);
}
}
@ParameterizedTest
@MethodSource("testFileData")
public void testOOXML(String testcase, File testFile, String extractor, int count) throws Exception {
// test processing of InputStream
try (FileInputStream fis = new FileInputStream(testFile);
POITextExtractor ext = createExtractor(fis)) {
assertNotNull(ext);
testExtractor(ext, testcase, extractor, count);
}
}
@ParameterizedTest
@MethodSource("testOOXMLData")
public void testPackage(String testcase, File testFile, String extractor, int count) throws Exception {
try (final OPCPackage pkg = OPCPackage.open(testFile, PackageAccess.READ);
final POITextExtractor ext = xmlFactory.create(pkg)) {
assertNotNull(ext);
testExtractor(ext, testcase, extractor, count);
pkg.revert();
} }
} }
@Test @Test
public void testFileInvalid() { public void testFileInvalid() {
IOException ex = assertThrows( IOException ex = assertThrows(IOException.class, () -> createExtractor(txt));
IOException.class,
() -> ExtractorFactory.createExtractor(txt)
);
assertEquals("Can't create extractor - unsupported file type: UNKNOWN", ex.getMessage()); assertEquals("Can't create extractor - unsupported file type: UNKNOWN", ex.getMessage());
} }
@Test
public void testInputStream() throws Exception {
testStream(ExtractorFactory::createExtractor, true);
}
@Test @Test
public void testInputStreamInvalid() throws IOException { public void testInputStreamInvalid() throws IOException {
try (FileInputStream fis = new FileInputStream(txt)) { try (FileInputStream fis = new FileInputStream(txt)) {
IOException ex = assertThrows(IOException.class, () -> ExtractorFactory.createExtractor(fis)); IOException ex = assertThrows(IOException.class, () -> createExtractor(fis));
assertTrue(ex.getMessage().contains(FileMagic.UNKNOWN.name())); assertTrue(ex.getMessage().contains(FileMagic.UNKNOWN.name()));
} }
} }
@Test
public void testPOIFS() throws Exception {
testStream((f) -> ExtractorFactory.createExtractor(new POIFSFileSystem(f)), false);
}
@Test @Test
public void testPOIFSInvalid() { public void testPOIFSInvalid() {
// Not really an Extractor test, but we'll leave it to test POIFS reaction anyway ... // Not really an Extractor test, but we'll leave it to test POIFS reaction anyway ...
@ -170,21 +202,6 @@ public class TestExtractorFactory {
assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0")); assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0"));
} }
@SuppressWarnings("ConstantConditions")
private void testStream(final FunctionEx<FileInputStream, POITextExtractor> poifsIS, final boolean loadOOXML)
throws IOException, OpenXML4JException, XmlException {
for (int i = 0; i < TEST_SET.length; i += 4) {
File testFile = (File) TEST_SET[i + 1];
if (!loadOOXML && (testFile.getName().endsWith("x") || testFile.getName().endsWith("xlsb"))) {
continue;
}
try (FileInputStream fis = new FileInputStream(testFile);
POITextExtractor ext = poifsIS.apply(fis)) {
testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]);
}
}
}
private void testExtractor(final POITextExtractor ext, final String testcase, final String extrClass, final Integer minLength) { private void testExtractor(final POITextExtractor ext, final String testcase, final String extrClass, final Integer minLength) {
assertEquals(extrClass, ext.getClass().getSimpleName(), "invalid extractor for " + testcase); assertEquals(extrClass, ext.getClass().getSimpleName(), "invalid extractor for " + testcase);
final String actual = ext.getText(); final String actual = ext.getText();
@ -194,25 +211,6 @@ public class TestExtractorFactory {
assertTrue(actual.length() > minLength, "extracted content too short for " + testcase); assertTrue(actual.length() > minLength, "extracted content too short for " + testcase);
} }
} }
@SuppressWarnings("ConstantConditions")
@Test
public void testPackage() throws Exception {
for (int i = 0; i < TEST_SET.length; i += 4) {
final File testFile = (File) TEST_SET[i + 1];
if (!testFile.getName().endsWith("x")) {
continue;
}
try (final OPCPackage pkg = OPCPackage.open(testFile, PackageAccess.READ);
final POITextExtractor ext = xmlFactory.create(pkg)) {
assertNotNull(ext);
testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]);
pkg.revert();
}
}
}
@Test @Test
public void testPackageInvalid() { public void testPackageInvalid() {
// Text // Text
@ -245,19 +243,13 @@ public class TestExtractorFactory {
try { try {
// Check we get the right extractors now // Check we get the right extractors now
try (POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) { try (POITextExtractor extractor = createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) {
assertTrue(extractor instanceof EventBasedExcelExtractor); assertTrue(extractor instanceof EventBasedExcelExtractor);
}
try (POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) {
assertTrue(extractor.getText().length() > 200); assertTrue(extractor.getText().length() > 200);
} }
try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) {
assertTrue(extractor instanceof XSSFEventBasedExcelExtractor);
}
try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) { try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) {
assertNotNull(extractor); assertNotNull(extractor);
assertTrue(extractor instanceof XSSFEventBasedExcelExtractor);
assertTrue(extractor.getText().length() > 200); assertTrue(extractor.getText().length() > 200);
} }
} finally { } finally {
@ -270,76 +262,78 @@ public class TestExtractorFactory {
assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors());
// And back // And back
try (POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) { try (POITextExtractor extractor = createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) {
assertTrue(extractor instanceof ExcelExtractor); assertTrue(extractor instanceof ExcelExtractor);
}
try (POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) {
assertTrue(extractor.getText().length() > 200); assertTrue(extractor.getText().length() > 200);
} }
try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) { try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) {
assertTrue(extractor instanceof XSSFExcelExtractor); assertTrue(extractor instanceof XSSFExcelExtractor);
} }
try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString()))) { try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString()))) {
assertNotNull(extractor); assertNotNull(extractor);
assertTrue(extractor.getText().length() > 200); assertTrue(extractor.getText().length() > 200);
} }
} }
public static Stream<Arguments> testEmbeddedData() {
return Stream.of(
Arguments.of("No embeddings", xls, "0-0-0-0-0-0"),
Arguments.of("Excel", xlsEmb, "6-2-2-2-0-0"),
Arguments.of("Word", docEmb, "4-1-2-1-0-0"),
Arguments.of("Word which contains an OOXML file", docEmbOOXML, "3-0-1-1-0-1"),
Arguments.of("Outlook", msgEmb, "1-1-0-0-0-0"),
Arguments.of("Outlook with another outlook file in it", msgEmbMsg, "1-0-0-0-1-0")
// TODO - PowerPoint
// TODO - Publisher
// TODO - Visio
);
}
/** /**
* Test embedded docs text extraction. For now, only * Test embedded docs text extraction. For now, only
* does poifs embedded, but will do ooxml ones * does poifs embedded, but will do ooxml ones
* at some point. * at some point.
*/ */
@Test @ParameterizedTest
public void testEmbedded() throws Exception { @MethodSource("testEmbeddedData")
final Object[] testObj = { public void testEmbedded(String format, File file, String expected) throws Exception {
"No embeddings", xls, "0-0-0-0-0-0", int numWord = 0, numXls = 0, numPpt = 0, numMsg = 0, numWordX = 0;
"Excel", xlsEmb, "6-2-2-2-0-0",
"Word", docEmb, "4-1-2-1-0-0",
"Word which contains an OOXML file", docEmbOOXML, "3-0-1-1-0-1",
"Outlook", msgEmb, "1-1-0-0-0-0",
"Outlook with another outlook file in it", msgEmbMsg, "1-0-0-0-1-0",
};
for (int i=0; i<testObj.length; i+=3) { try (final POIOLE2TextExtractor ext = (POIOLE2TextExtractor) createExtractor(file)) {
try (final POIOLE2TextExtractor ext = (POIOLE2TextExtractor)ExtractorFactory.createExtractor((File)testObj[i+1])) { final POITextExtractor[] embeds = ExtractorFactory.getEmbeddedDocsTextExtractors(ext);
final POITextExtractor[] embeds = ExtractorFactory.getEmbeddedDocsTextExtractors(ext);
int numWord = 0, numXls = 0, numPpt = 0, numMsg = 0, numWordX = 0; for (POITextExtractor embed : embeds) {
for (POITextExtractor embed : embeds) { assertTrue(embed.getText().length() > 20);
assertTrue(embed.getText().length() > 20); switch (embed.getClass().getSimpleName()) {
switch (embed.getClass().getSimpleName()) { case "SlideShowExtractor":
case "SlideShowExtractor": numPpt++;
numPpt++; break;
break; case "ExcelExtractor":
case "ExcelExtractor": numXls++;
numXls++; break;
break; case "WordExtractor":
case "WordExtractor": numWord++;
numWord++; break;
break; case "OutlookTextExtractor":
case "OutlookTextExtractor": numMsg++;
numMsg++; break;
break; case "XWPFWordExtractor":
case "XWPFWordExtractor": numWordX++;
numWordX++; break;
break;
}
} }
final String actual = embeds.length+"-"+numWord+"-"+numXls+"-"+numPpt+"-"+numMsg+"-"+numWordX;
final String expected = (String)testObj[i+2];
assertEquals(expected, actual, "invalid number of embeddings - "+testObj[i]);
} }
final String actual = embeds.length+"-"+numWord+"-"+numXls+"-"+numPpt+"-"+numMsg+"-"+numWordX;
assertEquals(expected, actual, "invalid number of embeddings - "+format);
} }
// TODO - PowerPoint
// TODO - Publisher
// TODO - Visio
} }
private static final String[] EXPECTED_FAILURES = { @ParameterizedTest
@ValueSource(strings = {
// password protected files // password protected files
"spreadsheet/password.xls", "spreadsheet/password.xls",
"spreadsheet/protected_passtika.xlsx", "spreadsheet/protected_passtika.xlsx",
@ -419,22 +413,13 @@ public class TestExtractorFactory {
"spreadsheet/57231_MixedGasReport.xls", "spreadsheet/57231_MixedGasReport.xls",
"spreadsheet/OddStyleRecord.xls", "spreadsheet/OddStyleRecord.xls",
"spreadsheet/WithChartSheet.xlsx", "spreadsheet/WithChartSheet.xlsx",
"spreadsheet/chart_sheet.xlsx", "spreadsheet/chart_sheet.xlsx"
}; })
public void testFileLeak(String file) {
@Test
public void testFileLeak() {
// run a number of files that might fail in order to catch // run a number of files that might fail in order to catch
// leaked file resources when using file-leak-detector while // leaked file resources when using file-leak-detector while
// running the test // running the test
assertThrows(Exception.class, () -> ex(file));
for(String file : EXPECTED_FAILURES) {
try {
ExtractorFactory.createExtractor(POIDataSamples.getSpreadSheetInstance().getFile(file));
} catch (Exception e) {
// catch all exceptions here as we are only interested in file-handle leaks
}
}
} }
/** /**
@ -443,7 +428,7 @@ public class TestExtractorFactory {
*/ */
@Test @Test
public void bug59074() throws Exception { public void bug59074() throws Exception {
try (POITextExtractor extractor = ExtractorFactory.createExtractor(POIDataSamples.getSpreadSheetInstance().getFile("59074.xls"))) { try (POITextExtractor extractor = ex("59074.xls")) {
String text = extractor.getText(); String text = extractor.getText();
assertContains(text, "Exotic warrant"); assertContains(text, "Exotic warrant");
} }
@ -460,7 +445,7 @@ public class TestExtractorFactory {
// bug 45565: text within TextBoxes is extracted by ExcelExtractor and WordExtractor // bug 45565: text within TextBoxes is extracted by ExcelExtractor and WordExtractor
@Test @Test
public void test45565() throws Exception { public void test45565() throws Exception {
try (POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("45565.xls"))) { try (POITextExtractor extractor = ex("45565.xls")) {
String text = extractor.getText(); String text = extractor.getText();
assertThrows(AssertionError.class, () -> { assertThrows(AssertionError.class, () -> {
assertContains(text, "testdoc"); assertContains(text, "testdoc");
@ -468,4 +453,8 @@ public class TestExtractorFactory {
}); });
} }
} }
private static POITextExtractor ex(String filename) throws IOException {
return createExtractor(ssTests.getFile(filename));
}
} }

View File

@ -21,6 +21,7 @@ import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_HREF;
import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_LABEL; import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_LABEL;
import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument; import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -107,6 +108,7 @@ import org.apache.poi.xslf.util.DummyGraphics2d;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.ThrowingSupplier;
import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
@ -513,35 +515,6 @@ public class TestXSLFBugs {
ppt.close(); ppt.close();
} }
@Test
@Disabled("Similar to TestFontRendering it doesn't make sense to compare images because of tiny rendering differences in windows/unix")
public void bug54542() throws Exception {
XMLSlideShow ss = openSampleDocument("54542_cropped_bitmap.pptx");
Dimension pgsize = ss.getPageSize();
XSLFSlide slide = ss.getSlides().get(0);
// render it
double zoom = 1;
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
BufferedImage imgActual = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D graphics = imgActual.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setTransform(at);
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
slide.draw(graphics);
ImageIO.write(imgActual, "PNG", new File("bug54542.png"));
ss.close();
}
private String getSlideText(XMLSlideShow ppt, XSLFSlide slide) throws IOException { private String getSlideText(XMLSlideShow ppt, XSLFSlide slide) throws IOException {
try (SlideShowExtractor<XSLFShape, XSLFTextParagraph> extr = new SlideShowExtractor<>(ppt)) { try (SlideShowExtractor<XSLFShape, XSLFTextParagraph> extr = new SlideShowExtractor<>(ppt)) {
// do not auto-close the slideshow // do not auto-close the slideshow
@ -880,9 +853,9 @@ public class TestXSLFBugs {
@Test @Test
public void bug60715() throws IOException { public void bug60715() throws IOException {
XMLSlideShow ppt = openSampleDocument("bug60715.pptx"); try (XMLSlideShow ppt = openSampleDocument("bug60715.pptx")) {
ppt.createSlide(); assertDoesNotThrow((ThrowingSupplier<XSLFSlide>) ppt::createSlide);
ppt.close(); }
} }
@Test @Test
@ -927,10 +900,11 @@ public class TestXSLFBugs {
@Test @Test
public void test60042() throws IOException { public void test60042() throws IOException {
XMLSlideShow ppt = openSampleDocument("60042.pptx"); try (XMLSlideShow ppt = openSampleDocument("60042.pptx")) {
ppt.removeSlide(0); ppt.removeSlide(0);
ppt.createSlide(); ppt.createSlide();
ppt.close(); assertEquals(2, ppt.getSlides().size());
}
} }
@Test @Test

View File

@ -50,7 +50,7 @@ public class TestPPTX2PNG {
"bug64693.pptx, 53446.ppt, alterman_security.ppt, alterman_security.pptx, KEY02.pptx, themes.pptx, " + "bug64693.pptx, 53446.ppt, alterman_security.ppt, alterman_security.pptx, KEY02.pptx, themes.pptx, " +
"backgrounds.pptx, layouts.pptx, sample.pptx, shapes.pptx, 54880_chinese.ppt, keyframes.pptx," + "backgrounds.pptx, layouts.pptx, sample.pptx, shapes.pptx, 54880_chinese.ppt, keyframes.pptx," +
"customGeo.pptx, customGeo.ppt, wrench.emf, santa.wmf, missing-moveto.ppt, " + "customGeo.pptx, customGeo.ppt, wrench.emf, santa.wmf, missing-moveto.ppt, " +
"64716_image1.wmf, 64716_image2.wmf, 64716_image3.wmf"; "64716_image1.wmf, 64716_image2.wmf, 64716_image3.wmf, 54542_cropped_bitmap.pptx";
private static final String svgFiles = private static final String svgFiles =
"bug64693.pptx"; "bug64693.pptx";

View File

@ -23,10 +23,12 @@ import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr;
import java.awt.Color; import java.awt.Color;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape;
import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize;
import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.xslf.XSLFTestDataSamples;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.drawingml.x2006.main.CTConnection; import org.openxmlformats.schemas.drawingml.x2006.main.CTConnection;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualConnectorProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualConnectorProperties;
@ -40,120 +42,125 @@ public class TestXSLFConnectorShape {
@Test @Test
public void testLineDecorations() throws IOException { public void testLineDecorations() throws IOException {
XMLSlideShow ppt = new XMLSlideShow(); try (XMLSlideShow ppt = new XMLSlideShow()) {
XSLFSlide slide = ppt.createSlide(); XSLFSlide slide = ppt.createSlide();
XSLFConnectorShape shape = slide.createConnector(); XSLFConnectorShape shape = slide.createConnector();
assertEquals(1, slide.getShapes().size()); assertEquals(1, slide.getShapes().size());
assertFalse(getSpPr(shape).getLn().isSetHeadEnd()); assertFalse(getSpPr(shape).getLn().isSetHeadEnd());
assertFalse(getSpPr(shape).getLn().isSetTailEnd()); assertFalse(getSpPr(shape).getLn().isSetTailEnd());
// line decorations // line decorations
assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration()); assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration());
assertEquals(DecorationShape.NONE, shape.getLineTailDecoration()); assertEquals(DecorationShape.NONE, shape.getLineTailDecoration());
shape.setLineHeadDecoration(null); shape.setLineHeadDecoration(null);
shape.setLineTailDecoration(null); shape.setLineTailDecoration(null);
assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration()); assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration());
assertEquals(DecorationShape.NONE, shape.getLineTailDecoration()); assertEquals(DecorationShape.NONE, shape.getLineTailDecoration());
assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetType()); assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetType());
assertFalse(getSpPr(shape).getLn().getTailEnd().isSetType()); assertFalse(getSpPr(shape).getLn().getTailEnd().isSetType());
shape.setLineHeadDecoration(DecorationShape.ARROW); shape.setLineHeadDecoration(DecorationShape.ARROW);
shape.setLineTailDecoration(DecorationShape.DIAMOND); shape.setLineTailDecoration(DecorationShape.DIAMOND);
assertEquals(DecorationShape.ARROW, shape.getLineHeadDecoration()); assertEquals(DecorationShape.ARROW, shape.getLineHeadDecoration());
assertEquals(DecorationShape.DIAMOND, shape.getLineTailDecoration()); assertEquals(DecorationShape.DIAMOND, shape.getLineTailDecoration());
assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getHeadEnd().getType()); assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getHeadEnd().getType());
assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getTailEnd().getType()); assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getTailEnd().getType());
shape.setLineHeadDecoration(DecorationShape.DIAMOND); shape.setLineHeadDecoration(DecorationShape.DIAMOND);
shape.setLineTailDecoration(DecorationShape.ARROW); shape.setLineTailDecoration(DecorationShape.ARROW);
assertEquals(DecorationShape.DIAMOND, shape.getLineHeadDecoration()); assertEquals(DecorationShape.DIAMOND, shape.getLineHeadDecoration());
assertEquals(DecorationShape.ARROW, shape.getLineTailDecoration()); assertEquals(DecorationShape.ARROW, shape.getLineTailDecoration());
assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getHeadEnd().getType()); assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getHeadEnd().getType());
assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getTailEnd().getType()); assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getTailEnd().getType());
// line end width // line end width
assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth());
assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth());
shape.setLineHeadWidth(null); shape.setLineHeadWidth(null);
shape.setLineHeadWidth(null); shape.setLineHeadWidth(null);
assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth());
assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth());
assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetW()); assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetW());
assertFalse(getSpPr(shape).getLn().getTailEnd().isSetW()); assertFalse(getSpPr(shape).getLn().getTailEnd().isSetW());
shape.setLineHeadWidth(DecorationSize.LARGE); shape.setLineHeadWidth(DecorationSize.LARGE);
shape.setLineTailWidth(DecorationSize.MEDIUM); shape.setLineTailWidth(DecorationSize.MEDIUM);
assertEquals(DecorationSize.LARGE, shape.getLineHeadWidth()); assertEquals(DecorationSize.LARGE, shape.getLineHeadWidth());
assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth());
assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getHeadEnd().getW()); assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getHeadEnd().getW());
assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getTailEnd().getW()); assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getTailEnd().getW());
shape.setLineHeadWidth(DecorationSize.MEDIUM); shape.setLineHeadWidth(DecorationSize.MEDIUM);
shape.setLineTailWidth(DecorationSize.LARGE); shape.setLineTailWidth(DecorationSize.LARGE);
assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth());
assertEquals(DecorationSize.LARGE, shape.getLineTailWidth()); assertEquals(DecorationSize.LARGE, shape.getLineTailWidth());
assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getHeadEnd().getW()); assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getHeadEnd().getW());
assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getTailEnd().getW()); assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getTailEnd().getW());
// line end length // line end length
assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength());
assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength());
shape.setLineHeadLength(null); shape.setLineHeadLength(null);
shape.setLineTailLength(null); shape.setLineTailLength(null);
assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength());
assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength());
assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetLen()); assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetLen());
assertFalse(getSpPr(shape).getLn().getTailEnd().isSetLen()); assertFalse(getSpPr(shape).getLn().getTailEnd().isSetLen());
shape.setLineHeadLength(DecorationSize.LARGE); shape.setLineHeadLength(DecorationSize.LARGE);
shape.setLineTailLength(DecorationSize.MEDIUM); shape.setLineTailLength(DecorationSize.MEDIUM);
assertEquals(DecorationSize.LARGE, shape.getLineHeadLength()); assertEquals(DecorationSize.LARGE, shape.getLineHeadLength());
assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength());
assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getHeadEnd().getLen()); assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getHeadEnd().getLen());
assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getTailEnd().getLen()); assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getTailEnd().getLen());
shape.setLineHeadLength(DecorationSize.MEDIUM); shape.setLineHeadLength(DecorationSize.MEDIUM);
shape.setLineTailLength(DecorationSize.LARGE); shape.setLineTailLength(DecorationSize.LARGE);
assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength());
assertEquals(DecorationSize.LARGE, shape.getLineTailLength()); assertEquals(DecorationSize.LARGE, shape.getLineTailLength());
assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getHeadEnd().getLen()); assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getHeadEnd().getLen());
assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getTailEnd().getLen()); assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getTailEnd().getLen());
}
ppt.close();
} }
@Test @Test
public void testAddConnector() throws IOException { public void testAddConnector() throws IOException {
XMLSlideShow pptx = new XMLSlideShow(); try (XMLSlideShow pptx = new XMLSlideShow()) {
XSLFSlide slide = pptx.createSlide(); XSLFSlide slide = pptx.createSlide();
XSLFAutoShape rect1 = slide.createAutoShape(); XSLFAutoShape rect1 = slide.createAutoShape();
rect1.setShapeType(ShapeType.RECT); rect1.setShapeType(ShapeType.RECT);
rect1.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); rect1.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
rect1.setFillColor(Color.blue); rect1.setFillColor(Color.blue);
XSLFAutoShape rect2 = slide.createAutoShape(); XSLFAutoShape rect2 = slide.createAutoShape();
rect2.setShapeType(ShapeType.RECT); rect2.setShapeType(ShapeType.RECT);
rect2.setAnchor(new Rectangle2D.Double(300, 300, 100, 100)); rect2.setAnchor(new Rectangle2D.Double(300, 300, 100, 100));
rect2.setFillColor(Color.red); rect2.setFillColor(Color.red);
XSLFConnectorShape connector1 = slide.createConnector(); XSLFConnectorShape connector1 = slide.createConnector();
connector1.setAnchor(new Rectangle2D.Double(200, 150, 100, 200)); Rectangle2D r1 = new Rectangle2D.Double(200, 150, 100, 200);
connector1.setAnchor(r1);
CTConnector ctConnector = (CTConnector)connector1.getXmlObject(); CTConnector ctConnector = (CTConnector) connector1.getXmlObject();
ctConnector.getSpPr().getPrstGeom().setPrst(STShapeType.BENT_CONNECTOR_3); ctConnector.getSpPr().getPrstGeom().setPrst(STShapeType.BENT_CONNECTOR_3);
CTNonVisualConnectorProperties cx = ctConnector.getNvCxnSpPr().getCNvCxnSpPr(); CTNonVisualConnectorProperties cx = ctConnector.getNvCxnSpPr().getCNvCxnSpPr();
// connection start // connection start
CTConnection stCxn = cx.addNewStCxn(); CTConnection stCxn = cx.addNewStCxn();
stCxn.setId(rect1.getShapeId()); stCxn.setId(rect1.getShapeId());
// side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4
stCxn.setIdx(2); stCxn.setIdx(2);
CTConnection end = cx.addNewEndCxn(); CTConnection end = cx.addNewEndCxn();
end.setId(rect2.getShapeId()); end.setId(rect2.getShapeId());
// side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4
end.setIdx(3); end.setIdx(3);
pptx.close(); try (XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(pptx)) {
XSLFSlide s1 = ppt2.getSlides().get(0);
List<XSLFShape> shapes = s1.getShapes();
XSLFConnectorShape c1 = (XSLFConnectorShape)shapes.get(2);
assertEquals(r1, c1.getAnchor());
}
}
} }
} }

View File

@ -18,6 +18,7 @@
package org.apache.poi.xslf.usermodel; package org.apache.poi.xslf.usermodel;
import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS; import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Rectangle; import java.awt.Rectangle;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -25,6 +26,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.List;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
@ -33,6 +35,7 @@ import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.sl.usermodel.PictureData; import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.xslf.XSLFTestDataSamples;
import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink;
@ -55,15 +58,14 @@ import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeType;
public class TestXSLFExamples { public class TestXSLFExamples {
@Test @Test
public void LinkVideoToPptx() throws IOException, URISyntaxException { public void LinkVideoToPptx() throws IOException, URISyntaxException {
String videoFileName = "file_example_MP4_640_3MG.mp4"; String videoFileName = "file_example_MP4_640_3MG.mp4";
File previewJpg = POIDataSamples.getDocumentInstance().getFile("abstract1.jpg"); File previewJpg = POIDataSamples.getDocumentInstance().getFile("abstract1.jpg");
XMLSlideShow pptx = new XMLSlideShow();
try (XMLSlideShow pptx = new XMLSlideShow()) {
XSLFSlide slide1 = pptx.createSlide(); XSLFSlide slide1 = pptx.createSlide();
PackagePart pp = slide1.getPackagePart(); PackagePart pp = slide1.getPackagePart();
URI mp4uri = new URI("./"+videoFileName); URI mp4uri = new URI("./" + videoFileName);
PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media"); PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media");
PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video"); PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
@ -72,7 +74,7 @@ public class TestXSLFExamples {
XSLFPictureShape pic1 = slide1.createPicture(snap); XSLFPictureShape pic1 = slide1.createPicture(snap);
pic1.setAnchor(new Rectangle(100, 100, 500, 400)); pic1.setAnchor(new Rectangle(100, 100, 500, 400));
CTPicture xpic1 = (CTPicture)pic1.getXmlObject(); CTPicture xpic1 = (CTPicture) pic1.getXmlObject();
CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick(); CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick();
link1.setId(""); link1.setId("");
link1.setAction("ppaction://media"); link1.setAction("ppaction://media");
@ -111,10 +113,10 @@ public class TestXSLFExamples {
ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE); ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE);
cmedia.addNewTgtEl().addNewSpTgt().setSpid(pic1.getShapeId()); cmedia.addNewTgtEl().addNewSpTgt().setSpid(pic1.getShapeId());
try (XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(pptx)) {
// write to file - use FileOutputStream instead XSLFShape sh = ppt2.getSlides().get(0).getShapes().get(0);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { assertTrue(sh instanceof XSLFPictureShape);
pptx.write(bos);
} }
}
} }
} }

View File

@ -23,86 +23,86 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import org.apache.poi.xslf.XSLFTestDataSamples;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/**
* @author Yegor Kozlov
*/
public class TestXSLFGroupShape { public class TestXSLFGroupShape {
@Test @Test
public void testCreateShapes() throws Exception { public void testCreateShapes() throws Exception {
XMLSlideShow ppt = new XMLSlideShow(); try (XMLSlideShow ppt = new XMLSlideShow()) {
XSLFSlide slide = ppt.createSlide(); XSLFSlide slide = ppt.createSlide();
ppt.setPageSize(new Dimension(792, 612)); ppt.setPageSize(new Dimension(792, 612));
XSLFGroupShape group = slide.createGroup(); XSLFGroupShape group = slide.createGroup();
assertEquals(1, slide.getShapes().size()); assertEquals(1, slide.getShapes().size());
Rectangle2D interior = new Rectangle2D.Double(-10, -10, 20, 20); Rectangle2D interior = new Rectangle2D.Double(-10, -10, 20, 20);
group.setInteriorAnchor(interior); group.setInteriorAnchor(interior);
assertEquals(interior, group.getInteriorAnchor()); assertEquals(interior, group.getInteriorAnchor());
Rectangle2D anchor = new Rectangle2D.Double(0, 0, 792, 612); Rectangle2D anchor = new Rectangle2D.Double(0, 0, 792, 612);
group.setAnchor(anchor); group.setAnchor(anchor);
assertEquals(anchor, group.getAnchor()); assertEquals(anchor, group.getAnchor());
assertTrue(group.getShapes().isEmpty()); assertTrue(group.getShapes().isEmpty());
XSLFTextBox shape1 = group.createTextBox(); XSLFTextBox shape1 = group.createTextBox();
assertEquals(1, group.getShapes().size()); assertEquals(1, group.getShapes().size());
assertSame(shape1, group.getShapes().get(0)); assertSame(shape1, group.getShapes().get(0));
assertEquals(3, shape1.getShapeId()); assertEquals(3, shape1.getShapeId());
XSLFAutoShape shape2 = group.createAutoShape(); XSLFAutoShape shape2 = group.createAutoShape();
assertEquals(2, group.getShapes().size()); assertEquals(2, group.getShapes().size());
assertSame(shape1, group.getShapes().get(0)); assertSame(shape1, group.getShapes().get(0));
assertSame(shape2, group.getShapes().get(1)); assertSame(shape2, group.getShapes().get(1));
assertEquals(4, shape2.getShapeId()); assertEquals(4, shape2.getShapeId());
XSLFConnectorShape shape3 = group.createConnector(); XSLFConnectorShape shape3 = group.createConnector();
assertEquals(3, group.getShapes().size()); assertEquals(3, group.getShapes().size());
assertSame(shape3, group.getShapes().get(2)); assertSame(shape3, group.getShapes().get(2));
assertEquals(5, shape3.getShapeId()); assertEquals(5, shape3.getShapeId());
XSLFGroupShape shape4 = group.createGroup(); XSLFGroupShape shape4 = group.createGroup();
assertEquals(4, group.getShapes().size()); assertEquals(4, group.getShapes().size());
assertSame(shape4, group.getShapes().get(3)); assertSame(shape4, group.getShapes().get(3));
assertEquals(6, shape4.getShapeId()); assertEquals(6, shape4.getShapeId());
group.removeShape(shape2); group.removeShape(shape2);
assertEquals(3, group.getShapes().size()); assertEquals(3, group.getShapes().size());
assertSame(shape1, group.getShapes().get(0)); assertSame(shape1, group.getShapes().get(0));
assertSame(shape3, group.getShapes().get(1)); assertSame(shape3, group.getShapes().get(1));
assertSame(shape4, group.getShapes().get(2)); assertSame(shape4, group.getShapes().get(2));
group.removeShape(shape3); group.removeShape(shape3);
assertEquals(2, group.getShapes().size()); assertEquals(2, group.getShapes().size());
assertSame(shape1, group.getShapes().get(0)); assertSame(shape1, group.getShapes().get(0));
assertSame(shape4, group.getShapes().get(1)); assertSame(shape4, group.getShapes().get(1));
group.removeShape(shape1); group.removeShape(shape1);
group.removeShape(shape4); group.removeShape(shape4);
assertTrue(group.getShapes().isEmpty()); assertTrue(group.getShapes().isEmpty());
}
ppt.close();
} }
@Test @Test
public void testRemoveShapes() throws Exception { public void testRemoveShapes() throws Exception {
XMLSlideShow ppt = new XMLSlideShow(); try (XMLSlideShow ppt = new XMLSlideShow()) {
XSLFSlide slide = ppt.createSlide(); XSLFSlide slide = ppt.createSlide();
XSLFGroupShape group1 = slide.createGroup(); XSLFGroupShape group1 = slide.createGroup();
group1.createTextBox(); group1.createTextBox();
XSLFGroupShape group2 = slide.createGroup(); XSLFGroupShape group2 = slide.createGroup();
group2.createTextBox(); group2.createTextBox();
XSLFGroupShape group3 = slide.createGroup(); XSLFGroupShape group3 = slide.createGroup();
slide.removeShape(group1); slide.removeShape(group1);
slide.removeShape(group2); slide.removeShape(group2);
slide.removeShape(group3); slide.removeShape(group3);
ppt.close(); try (XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt)) {
assertEquals(0, ppt2.getSlides().get(0).getShapes().size());
}
}
} }
} }

View File

@ -16,6 +16,7 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.xslf.usermodel; package org.apache.poi.xslf.usermodel;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -316,18 +317,20 @@ public class TestXSLFTable {
} }
@Test @Test
public void checkNullPointerException() { public void checkNullPointerException() throws IOException {
XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx"); String file = "au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx";
Dimension pgsize = ss.getPageSize(); try (XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument(file)) {
for (Slide<?, ?> s : ss.getSlides()) { Dimension pgsize = ss.getPageSize();
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB); for (Slide<?, ?> s : ss.getSlides()) {
Graphics2D graphics = img.createGraphics(); BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = img.createGraphics();
// draw stuff // draw stuff
s.draw(graphics); assertDoesNotThrow(() -> s.draw(graphics));
graphics.dispose(); graphics.dispose();
img.flush(); img.flush();
}
} }
} }
} }

View File

@ -19,6 +19,7 @@
package org.apache.poi.xslf.usermodel; package org.apache.poi.xslf.usermodel;
import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
@ -108,18 +109,19 @@ public class TestXSLFTextRun {
} }
@Test @Test
public void testCopyNullFontSize() { public void testCopyNullFontSize() throws IOException {
XMLSlideShow ppt = new XMLSlideShow(); try (XMLSlideShow ppt = new XMLSlideShow()) {
XSLFSlide slide = ppt.createSlide(); XSLFSlide slide = ppt.createSlide();
XSLFTextShape sh = slide.createAutoShape(); XSLFTextShape sh = slide.createAutoShape();
XSLFTextRun r = sh.addNewTextParagraph().addNewTextRun(); XSLFTextRun r = sh.addNewTextParagraph().addNewTextRun();
XSLFTextRun s = new XSLFTextRun(CTTextLineBreak.Factory.newInstance(), XSLFTextRun s = new XSLFTextRun(CTTextLineBreak.Factory.newInstance(),
new XSLFTextParagraph(CTTextParagraph.Factory.newInstance(), new XSLFTextParagraph(CTTextParagraph.Factory.newInstance(),
new XSLFTextBox(CTShape.Factory.newInstance(), slide))); new XSLFTextBox(CTShape.Factory.newInstance(), slide)));
r.copy(s); assertDoesNotThrow(() -> r.copy(s));
}
} }
@Test @Test

View File

@ -17,6 +17,8 @@
package org.apache.poi; package org.apache.poi;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.RenderingHints; import java.awt.RenderingHints;
import java.awt.font.TextLayout; import java.awt.font.TextLayout;
@ -38,16 +40,18 @@ import org.junit.jupiter.api.Test;
*/ */
public class TestJDK12 { public class TestJDK12 {
@Test @Test
public void test() throws Exception { public void test() {
BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); assertDoesNotThrow(() -> {
Graphics2D graphics = img.createGraphics(); BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Graphics2D graphics = img.createGraphics();
graphics.scale(200, 1); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.scale(200, 1);
new TextLayout(new AttributedString("agriculture").getIterator(), graphics.getFontRenderContext()); new TextLayout(new AttributedString("agriculture").getIterator(), graphics.getFontRenderContext());
graphics.dispose(); graphics.dispose();
img.flush(); img.flush();
});
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.hpsf.basic; package org.apache.poi.hpsf.basic;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -66,8 +67,8 @@ public final class TestClassID {
@Test @Test
public void testWriteArrayStoreException3() { public void testWriteArrayStoreException3() {
ClassID clsidTest = new ClassID(BUF16, 0); ClassID clsidTest = new ClassID(BUF16, 0);
clsidTest.write(new byte[16], 0); assertDoesNotThrow(() -> clsidTest.write(new byte[16], 0));
clsidTest.write(new byte[17], 1); assertDoesNotThrow(() -> clsidTest.write(new byte[17], 1));
} }
@Test @Test

View File

@ -19,8 +19,11 @@ package org.apache.poi.hssf.record;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import org.apache.poi.hssf.model.RecordStream; import org.apache.poi.hssf.model.RecordStream;
@ -59,13 +62,15 @@ public final class TestMergeCellsRecord {
@Test @Test
public void testMCTable_bug46009() { public void testMCTable_bug46009() {
MergedCellsTable mct = new MergedCellsTable(); MergedCellsTable mct = new MergedCellsTable();
List<org.apache.poi.hssf.record.Record> recList = new ArrayList<>(); CellRangeAddress[] cras = { new CellRangeAddress(0, 0, 0, 3) };
CellRangeAddress[] cras = new CellRangeAddress[] { MergeCellsRecord mcr1 = new MergeCellsRecord(cras, 0, 1);
new CellRangeAddress(0, 0, 0, 3), RecordStream rs = new RecordStream(Collections.singletonList(mcr1), 0);
};
recList.add(new MergeCellsRecord(cras, 0, 1));
RecordStream rs = new RecordStream(recList, 0);
mct.read(rs); mct.read(rs);
mct.visitContainedRecords(r -> {}); mct.visitContainedRecords(r -> {
assertTrue(r instanceof MergeCellsRecord);
MergeCellsRecord mcr2 = (MergeCellsRecord)r;
assertEquals(mcr1.getNumAreas(), mcr2.getNumAreas());
assertEquals(mcr1.getAreaAt(0), mcr2.getAreaAt(0));
});
} }
} }

View File

@ -17,11 +17,14 @@
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.DVConstraint; import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation; import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataValidationConstraint; import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.ss.util.CellRangeAddressList;
@ -49,7 +52,8 @@ public final class TestPLVRecord {
// This used to throw an IllegalStateException before // This used to throw an IllegalStateException before
// Identified bug 53972, PLV record breaks addDataValidation() // Identified bug 53972, PLV record breaks addDataValidation()
workbook.getSheet(SHEET_NAME).addValidationData(dataValidation); HSSFSheet sheet = workbook.getSheet(SHEET_NAME);
assertDoesNotThrow(() -> sheet.addValidationData(dataValidation));
} }
} }
} }

View File

@ -17,10 +17,13 @@
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/** /**
* Tests for {@link RecordInputStream} * Tests for {@link RecordInputStream}
@ -91,13 +94,10 @@ public final class TestRecordInputStream {
assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual); assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual);
} }
@SuppressWarnings("ThrowableNotThrown") @ParameterizedTest
@Test @CsvSource({"1, 200", "0, 200", "999999999, 200", HeaderRecord.sid+", 200"})
public void testLeftoverDataException() { public void testLeftoverDataException(int sid, int remainingByteCount) {
// just ensure that the exception is created correctly, even with unknown sids // just ensure that the exception is created correctly, even with unknown sids
new RecordInputStream.LeftoverDataException(1, 200); assertDoesNotThrow(() -> new RecordInputStream.LeftoverDataException(sid, remainingByteCount));
new RecordInputStream.LeftoverDataException(0, 200);
new RecordInputStream.LeftoverDataException(999999999, 200);
new RecordInputStream.LeftoverDataException(HeaderRecord.sid, 200);
} }
} }

View File

@ -18,10 +18,12 @@
package org.apache.poi.hssf.record.aggregates; package org.apache.poi.hssf.record.aggregates;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -41,6 +43,7 @@ import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SharedFormulaRecord; import org.apache.poi.hssf.record.SharedFormulaRecord;
import org.apache.poi.hssf.record.WindowTwoRecord; import org.apache.poi.hssf.record.WindowTwoRecord;
import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
@ -314,28 +317,23 @@ public final class TestValueRecordsAggregate {
} }
@Test @Test
public void testRemoveNewRow_bug46312() { public void testRemoveNewRow_bug46312() throws IOException {
// To make bug occur, rowIndex needs to be >= ValueRecordsAggregate.records.length // To make bug occur, rowIndex needs to be >= ValueRecordsAggregate.records.length
int rowIndex = 30; int rowIndex = 30;
ValueRecordsAggregate vra = new ValueRecordsAggregate(); ValueRecordsAggregate vra = new ValueRecordsAggregate();
// bug 46312 - Specified rowIndex 30 is outside the allowable range (0..30) // bug 46312 - Specified rowIndex 30 is outside the allowable range (0..30)
vra.removeAllCellsValuesForRow(rowIndex); assertDoesNotThrow(() -> vra.removeAllCellsValuesForRow(rowIndex));
// if (false) { // same bug as demonstrated through usermodel API // same bug as demonstrated through usermodel API
// try (HSSFWorkbook wb = new HSSFWorkbook()) {
// HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet();
// HSSFSheet sheet = wb.createSheet(); HSSFRow row = sheet.createRow(rowIndex);
// HSSFRow row = sheet.createRow(rowIndex);
// if (false) { // must not add any cells to the new row if we want to see the bug // must not add any cells to the new row if we want to see the bug
// row.createCell(0); // this causes ValueRecordsAggregate.records to auto-extend // row.createCell(0); // this causes ValueRecordsAggregate.records to auto-extend
// } assertDoesNotThrow(() -> sheet.createRow(rowIndex));
// try { }
// sheet.createRow(rowIndex);
// } catch (IllegalArgumentException e) {
// throw new AssertionFailedError("Identified bug 46312");
// }
// }
} }
/** /**