Example usage for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument

List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument.

Prototype

public XWPFDocument(InputStream is) throws IOException 

Source Link

Usage

From source file:org.obeonetwork.m2doc.test.AbstractTemplatesTestSuite.java

License:Open Source License

/**
 * Tests the parsing by comparing the result of the generation.
 * //from ww  w.j  a  v a2s  .com
 * @throws Exception
 *             if the generation fails
 */
@Test
public void generation() throws Exception {
    final File expectedGeneratedFile = getExpectedGeneratedFile(new File(testFolderPath));
    final File templateFile = getTemplateFile(new File(testFolderPath));
    final File userContentFile = getUserContentFile(new File(testFolderPath));

    File outputFile = null;
    if (expectedGeneratedFile.exists()) {
        outputFile = File.createTempFile(expectedGeneratedFile.getAbsolutePath(), "generated-test");
    } else {
        outputFile = getActualGeneratedFile(new File(testFolderPath));
        if (userContentFile.exists()) {
            Files.copy(userContentFile, outputFile);
        }
        generateTemplate(templateFile, outputFile);
        fail(expectedGeneratedFile.getAbsoluteFile() + " doesn't exists.");
    }

    try (FileInputStream is = new FileInputStream(templateFile)) {
        try (OPCPackage oPackage = OPCPackage.open(is)) {
            try (XWPFDocument document = new XWPFDocument(oPackage)) {
                if (userContentFile.exists()) {
                    Files.copy(userContentFile, outputFile);
                }
                generateTemplate(templateFile, outputFile);
                M2DocTestUtils.assertDocx(expectedGeneratedFile.getAbsolutePath(),
                        outputFile.getAbsolutePath());
            }
        }
    } finally {
        if (outputFile != null) {
            outputFile.delete();
        }
    }
}

From source file:org.obeonetwork.m2doc.tests.generator.DocumentGeneratorTests.java

License:Open Source License

@Test
public void testBookmarkNominal() throws Exception {
    try (FileInputStream resIs = new FileInputStream(
            "resources/bookmark/nominal/nominal-expected-generation.docx");
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        assertEquals(5, resDocument.getBodyElements().size());
        assertTrue(resDocument.getBodyElements().get(1) instanceof XWPFParagraph);
        XWPFParagraph paragraph = (XWPFParagraph) resDocument.getBodyElements().get(1);
        assertEquals(6, paragraph.getRuns().size());
        assertEquals("Test link before bookmark: ", paragraph.getRuns().get(0).text());

        final BigInteger id = new BigInteger(paragraph.getRuns().get(1).getCTR().getRsidR());

        assertTrue(id != BigInteger.ZERO);
        assertEquals(1, paragraph.getRuns().get(1).getCTR().getFldCharList().size());
        assertEquals(STFldCharType.BEGIN,
                paragraph.getRuns().get(1).getCTR().getFldCharList().get(0).getFldCharType());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(2).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(2).getCTR().getInstrTextList().size());
        assertEquals(Space.PRESERVE, paragraph.getRuns().get(2).getCTR().getInstrTextList().get(0).getSpace());
        assertEquals(" REF bookmark1 \\h ",
                paragraph.getRuns().get(2).getCTR().getInstrTextList().get(0).getStringValue());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(3).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(3).getCTR().getFldCharList().size());
        assertEquals(STFldCharType.SEPARATE,
                paragraph.getRuns().get(3).getCTR().getFldCharList().get(0).getFldCharType());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(4).getCTR().getRsidR()));
        assertEquals("a reference to bookmark1", paragraph.getRuns().get(4).text());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(5).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(5).getCTR().getFldCharList().size());
        assertEquals(STFldCharType.END,/*w  ww .ja  v a  2  s  .  c o m*/
                paragraph.getRuns().get(5).getCTR().getFldCharList().get(0).getFldCharType());

        assertTrue(resDocument.getBodyElements().get(1) instanceof XWPFParagraph);
        paragraph = (XWPFParagraph) resDocument.getBodyElements().get(2);

        assertEquals(1, paragraph.getCTP().getBookmarkStartList().size());
        assertEquals("bookmark1", paragraph.getCTP().getBookmarkStartList().get(0).getName());
        assertEquals(1, paragraph.getCTP().getBookmarkEndList().size());

        assertTrue(resDocument.getBodyElements().get(2) instanceof XWPFParagraph);
        paragraph = (XWPFParagraph) resDocument.getBodyElements().get(3);
        assertEquals(7, paragraph.getRuns().size());
        assertEquals("Test link after bookmark: ", paragraph.getRuns().get(0).text());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(1).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(1).getCTR().getFldCharList().size());
        assertEquals(STFldCharType.BEGIN,
                paragraph.getRuns().get(1).getCTR().getFldCharList().get(0).getFldCharType());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(2).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(2).getCTR().getInstrTextList().size());
        assertEquals(Space.PRESERVE, paragraph.getRuns().get(2).getCTR().getInstrTextList().get(0).getSpace());
        assertEquals(" REF bookmark1 \\h ",
                paragraph.getRuns().get(2).getCTR().getInstrTextList().get(0).getStringValue());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(3).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(3).getCTR().getFldCharList().size());
        assertEquals(STFldCharType.SEPARATE,
                paragraph.getRuns().get(3).getCTR().getFldCharList().get(0).getFldCharType());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(4).getCTR().getRsidR()));
        assertEquals("a reference to bookmark1", paragraph.getRuns().get(4).text());

        assertEquals(id, new BigInteger(paragraph.getRuns().get(5).getCTR().getRsidR()));
        assertEquals(1, paragraph.getRuns().get(5).getCTR().getFldCharList().size());
        assertEquals(STFldCharType.END,
                paragraph.getRuns().get(5).getCTR().getFldCharList().get(0).getFldCharType());
    }
}

From source file:org.obeonetwork.m2doc.tests.generator.TemplateValidationGeneratorTests.java

License:Open Source License

/**
 * Ensure that the validation generation produces a document with an info.
 * /*from  w  ww. j  a va 2 s  . c o m*/
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 * @throws DocumentGenerationException
 */
@Test
public void testInfoGeneration()
        throws InvalidFormatException, IOException, DocumentParserException, DocumentGenerationException {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    final File tempFile = File.createTempFile("testParsingErrorSimpleTag", ".docx");

    try (DocumentTemplate template = M2DocUtils.parse(
            URI.createFileURI("resources/document/notEmpty/notEmpty-template.docx"), queryEnvironment,
            this.getClass().getClassLoader())) {
        final XWPFRun location = ((XWPFParagraph) template.getDocument().getBodyElements().get(0)).getRuns()
                .get(0);
        template.getBody().getValidationMessages().add(new TemplateValidationMessage(
                ValidationMessageLevel.INFO, "XXXXXXXXXXXXXXXXXXXXXXXX", location));
        M2DocUtils.serializeValidatedDocumentTemplate(template, URI.createFileURI(tempFile.getAbsolutePath()));
    }
    assertTrue(new File(tempFile.getAbsolutePath()).exists());

    try (FileInputStream resIs = new FileInputStream(tempFile.getAbsolutePath());
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        final XWPFRun messageRun = M2DocTestUtils.getRunContaining(resDocument, "XXXXXXXXXXXXXXXXXXXXXXXX");

        assertNotNull(messageRun);
        assertEquals("XXXXXXXXXXXXXXXXXXXXXXXX", messageRun.text());
        assertEquals("0000FF", messageRun.getColor());
    }

    tempFile.delete();
}

From source file:org.obeonetwork.m2doc.tests.generator.TemplateValidationGeneratorTests.java

License:Open Source License

/**
 * Ensure that the validation generation produces a document with an warning.
 * /* w w w  . ja  va2 s.  c  om*/
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 * @throws DocumentGenerationException
 */
@Test
public void testWarningGeneration()
        throws InvalidFormatException, IOException, DocumentParserException, DocumentGenerationException {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    final File tempFile = File.createTempFile("testParsingErrorSimpleTag", ".docx");

    try (DocumentTemplate template = M2DocUtils.parse(
            URI.createFileURI("resources/document/notEmpty/notEmpty-template.docx"), queryEnvironment,
            this.getClass().getClassLoader())) {
        final XWPFRun location = ((XWPFParagraph) template.getDocument().getBodyElements().get(0)).getRuns()
                .get(0);
        template.getBody().getValidationMessages().add(new TemplateValidationMessage(
                ValidationMessageLevel.WARNING, "XXXXXXXXXXXXXXXXXXXXXXXX", location));
        M2DocUtils.serializeValidatedDocumentTemplate(template, URI.createFileURI(tempFile.getAbsolutePath()));
    }
    assertTrue(new File(tempFile.getAbsolutePath()).exists());

    try (FileInputStream resIs = new FileInputStream(tempFile.getAbsolutePath());
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        final XWPFRun messageRun = M2DocTestUtils.getRunContaining(resDocument, "XXXXXXXXXXXXXXXXXXXXXXXX");

        assertNotNull(messageRun);
        assertEquals("XXXXXXXXXXXXXXXXXXXXXXXX", messageRun.text());
        assertEquals("FFA500", messageRun.getColor());
    }

    tempFile.delete();
}

From source file:org.obeonetwork.m2doc.tests.generator.TemplateValidationGeneratorTests.java

License:Open Source License

/**
 * Ensure that the validation generation produces a document with an error.
 * /*from   w  ww.j  a  va2 s.co  m*/
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 * @throws DocumentGenerationException
 */
@Test
public void testErrorGeneration()
        throws InvalidFormatException, IOException, DocumentParserException, DocumentGenerationException {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    final File tempFile = File.createTempFile("testParsingErrorSimpleTag", ".docx");

    try (DocumentTemplate template = M2DocUtils.parse(
            URI.createFileURI("resources/document/notEmpty/notEmpty-template.docx"), queryEnvironment,
            this.getClass().getClassLoader())) {
        final XWPFRun location = ((XWPFParagraph) template.getDocument().getBodyElements().get(0)).getRuns()
                .get(0);
        template.getBody().getValidationMessages().add(new TemplateValidationMessage(
                ValidationMessageLevel.ERROR, "XXXXXXXXXXXXXXXXXXXXXXXX", location));
        M2DocUtils.serializeValidatedDocumentTemplate(template, URI.createFileURI(tempFile.getAbsolutePath()));
    }
    assertTrue(new File(tempFile.getAbsolutePath()).exists());

    try (FileInputStream resIs = new FileInputStream(tempFile.getAbsolutePath());
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        final XWPFRun messageRun = M2DocTestUtils.getRunContaining(resDocument, "XXXXXXXXXXXXXXXXXXXXXXXX");

        assertNotNull(messageRun);
        assertEquals("XXXXXXXXXXXXXXXXXXXXXXXX", messageRun.text());
        assertEquals("FF0000", messageRun.getColor());
    }

    tempFile.delete();
}

From source file:org.obeonetwork.m2doc.tests.generator.TemplateValidationGeneratorTests.java

License:Open Source License

/**
 * Ensure that the validation generation produces a document with errors in the good order.
 * /*from  w  w w.  ja v  a 2 s.  c o  m*/
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 * @throws DocumentGenerationException
 */
@Test
public void testErrorGenerationOrder()
        throws InvalidFormatException, IOException, DocumentParserException, DocumentGenerationException {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    final File tempFile = File.createTempFile("testParsingErrorSimpleTag", ".docx");

    try (DocumentTemplate template = M2DocUtils.parse(
            URI.createFileURI("resources/document/notEmpty/notEmpty-template.docx"), queryEnvironment,
            this.getClass().getClassLoader())) {
        final XWPFRun location = ((XWPFParagraph) template.getDocument().getBodyElements().get(0)).getRuns()
                .get(0);
        template.getBody().getValidationMessages()
                .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR, "AAAA", location));
        template.getBody().getValidationMessages()
                .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR, "BBBB", location));
        template.getBody().getValidationMessages()
                .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR, "CCCC", location));
        template.getBody().getValidationMessages()
                .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR, "DDDD", location));
        M2DocUtils.serializeValidatedDocumentTemplate(template, URI.createFileURI(tempFile.getAbsolutePath()));
    }
    assertTrue(new File(tempFile.getAbsolutePath()).exists());

    try (FileInputStream resIs = new FileInputStream(tempFile.getAbsolutePath());
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        final XWPFRun messageARun = M2DocTestUtils.getRunContaining(resDocument, "AAAA");
        final XWPFRun messageBRun = M2DocTestUtils.getRunContaining(resDocument, "BBBB");
        final XWPFRun messageCRun = M2DocTestUtils.getRunContaining(resDocument, "CCCC");
        final XWPFRun messageDRun = M2DocTestUtils.getRunContaining(resDocument, "DDDD");

        assertNotNull(messageARun);
        assertEquals("AAAA", messageARun.text());
        assertEquals("FF0000", messageARun.getColor());

        assertNotNull(messageBRun);
        assertEquals("BBBB", messageBRun.text());
        assertEquals("FF0000", messageBRun.getColor());

        assertNotNull(messageCRun);
        assertEquals("CCCC", messageCRun.text());
        assertEquals("FF0000", messageCRun.getColor());

        assertNotNull(messageDRun);
        assertEquals("DDDD", messageDRun.text());
        assertEquals("FF0000", messageDRun.getColor());

        final int indexA = ((XWPFParagraph) messageARun.getParent()).getRuns().indexOf(messageARun);
        final int indexB = ((XWPFParagraph) messageBRun.getParent()).getRuns().indexOf(messageBRun);
        final int indexC = ((XWPFParagraph) messageCRun.getParent()).getRuns().indexOf(messageCRun);
        final int indexD = ((XWPFParagraph) messageDRun.getParent()).getRuns().indexOf(messageDRun);

        assertTrue(indexA < indexB);
        assertTrue(indexB < indexC);
        assertTrue(indexC < indexD);
    }

    tempFile.delete();
}

From source file:org.obeonetwork.m2doc.tests.M2DocTestUtils.java

License:Open Source License

/**
 * Gets the textual element of the .docx at the given {@link URI}.
 * //  ww w  .  j a va  2 s  .c  o  m
 * @param uri
 *            the .docx {@link URI}
 * @return the textual element of the .docx at the given {@link URI}
 */
public static String getTextContent(URI uri) {
    String result = "";

    try (InputStream is = URIConverter.INSTANCE.createInputStream(uri);
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);
            XWPFWordExtractor ex = new XWPFWordExtractor(document);) {

        result += "===== Document Text ====\n";
        result += ex.getText();
        // CHECKSTYLE:OFF
    } catch (Throwable e) {
        // CHECKSTYLE:ON
        /*
         * if for some reason we can't use POI to get the text content then move along, we'll still get the XML and hashs
         */
    }
    return result;
}

From source file:org.obeonetwork.m2doc.tests.parser.RunIteratorTests.java

License:Open Source License

@Test
public void testNonEmptyDoc() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);
        XWPFRun run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();/*w  w w . j ava2s.  c  o m*/
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}

From source file:org.obeonetwork.m2doc.tests.parser.RunIteratorTests.java

License:Open Source License

@Test
public void testAccessEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);
        assertNotNull(iterator.next());/* www  .j ava 2s .  c  o m*/
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertFalse(iterator.hasNext());
        boolean hasException = false;
        try {
            iterator.next();
        } catch (NoSuchElementException e) {
            assertTrue(e instanceof NoSuchElementException);
            hasException = true;
        }
        assertTrue(hasException);
    }
}

From source file:org.obeonetwork.m2doc.tests.parser.RunIteratorTests.java

License:Open Source License

@Test(expected = NotOfficeXmlFileException.class)
public void testEmptyDoc() throws InvalidFormatException, IOException {
    final File file = new File("resources/document/empty/empty-template.docx");
    assertTrue(file.exists());/*  w  w  w . j  av a  2s  .  c o  m*/
    try (FileInputStream is = new FileInputStream(file);
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);

        assertTrue(!iterator.hasNext());
    }
}