Example usage for org.apache.poi.xwpf.usermodel XWPFRun getParent

List of usage examples for org.apache.poi.xwpf.usermodel XWPFRun getParent

Introduction

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

Prototype

public IRunBody getParent() 

Source Link

Document

Get the currently referenced paragraph/SDT object

Usage

From source file:org.obeonetwork.m2doc.generator.TableClientProcessor.java

License:Open Source License

/**
 * Create a table in a document./*from  ww  w.ja v  a 2  s  .  c  om*/
 * 
 * @param tableRun
 *            the run after which the table must be created
 * @param first
 *            Whether it's the first table to insert or not
 * @param mtable
 *            The table description
 * @return The newly created table.
 */
private XWPFTable createTableInDocument(XWPFRun tableRun, boolean first, MTable mtable) {
    XWPFTable table;
    if (!first) {
        ((XWPFDocument) body).createParagraph();
    }
    if (showTitle() && mtable.getLabel() != null) {
        XWPFRun captionRun;
        if (first) {
            captionRun = tableRun;
            IRunBody runBody = captionRun.getParent();
            if (runBody instanceof XWPFParagraph) {
                ((XWPFParagraph) runBody).setSpacingAfter(0);
            }
        } else {
            XWPFParagraph captionParagraph = ((XWPFDocument) body).createParagraph();
            captionParagraph.setSpacingAfter(0);
            captionRun = captionParagraph.createRun();
        }
        captionRun.setText(mtable.getLabel());
        captionRun.setBold(true);
    }
    table = ((XWPFDocument) body).createTable();
    return table;
}

From source file:org.obeonetwork.m2doc.generator.TableClientProcessor.java

License:Open Source License

/**
 * Create a table in a table cell.//from ww w  .  j  a v  a  2 s.  c o  m
 * 
 * @param tableRun
 *            The table run
 * @param first
 *            whether it's the 1st table created in this cell
 * @param mtable
 *            The table description
 * @param tcell
 *            The cell in which to create a new table
 * @return The newly creatted table, located in the given cell.
 */
private XWPFTable createTableInCell(XWPFRun tableRun, boolean first, MTable mtable, XWPFTableCell tcell) {
    XWPFTable table;
    if (showTitle() && mtable.getLabel() != null) {
        XWPFRun captionRun;
        if (first) {
            captionRun = tableRun;
            IRunBody runBody = captionRun.getParent();
            if (runBody instanceof XWPFParagraph) {
                ((XWPFParagraph) runBody).setSpacingAfter(0);
            }
        } else {
            XWPFParagraph captionParagraph = tcell.addParagraph();
            captionParagraph.setSpacingAfter(0);
            captionRun = captionParagraph.createRun();
        }
        captionRun.setText(mtable.getLabel());
        captionRun.setBold(true);
    }
    CTTbl ctTbl = tcell.getCTTc().addNewTbl();
    table = new XWPFTable(ctTbl, tcell);
    int tableRank = tcell.getTables().size();
    tcell.insertTable(tableRank, table);
    // A paragraph is mandatory at the end of a cell, so let's always add one.
    tcell.addParagraph();
    return table;
}

From source file:org.obeonetwork.m2doc.generator.TemplateProcessor.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   ww w  . j a v  a2  s.c om*/
public AbstractConstruct caseRepetition(Repetition object) {
    // first evaluate the query
    @SuppressWarnings("restriction")
    EvaluationResult result = new QueryEvaluationEngine(queryEnvironment).eval(object.getQuery(),
            definitions.getCurrentDefinitions());
    if (result == null || result.getDiagnostic().getCode() == Diagnostic.ERROR) {
        // insert the tag runs as is.
        for (XWPFRun tagRun : object.getRuns()) {
            insertRun(tagRun);
        }
        // insert the error message.
        XWPFRun run = currentGeneratedParagraph.createRun();
        if (result != null) {
            run.setText(result.getDiagnostic().getMessage());
        } else {
            run.setText("couldn't evaluate expression");
        }
        if (result == null || result.getDiagnostic().getCode() == Diagnostic.ERROR) {
            run.setBold(true);
            run.setColor(ERROR_COLOR);
        }

        for (XWPFRun tagRun : object.getClosingRuns()) {
            insertRun(tagRun);
        }
    } else {
        List<Object> iteration = new ArrayList<Object>();
        if (result.getResult() instanceof Collection) {
            iteration.addAll((Collection<? extends Object>) result.getResult());
        } else {
            iteration.add(result.getResult());
        }
        for (Object val : iteration) {
            this.definitions.setValue(object.getIterationVar(), val);
            for (AbstractConstruct construct : object.getSubConstructs()) {
                doSwitch(construct);
            }
            // if the {gd:endfor} lies on a distinct paragraph, insert a new
            // paragraph there to take this into acount.
            int bodySize = object.getSubConstructs().size();
            if (bodySize > 0 && object.getSubConstructs().get(bodySize - 1).getRuns().size() > 0) {
                AbstractConstruct lastBodyPart = object.getSubConstructs().get(bodySize - 1);
                int runNumber = lastBodyPart.getRuns().size();
                XWPFRun lastRun = lastBodyPart.getRuns().get(runNumber - 1);
                int closingRunNumber = object.getClosingRuns().size();
                if (closingRunNumber > 0 && object.getClosingRuns().get(0).getParent() != lastRun.getParent()) {
                    forceNewParagraph = true;
                }
            }
        }
    }
    return object;

}

From source file:org.obeonetwork.m2doc.generator.test.TemplateGeneratorTest.java

License:Open Source License

/**
 * Ensure that the validation generation produces a document with errors in the good order.
 * /*  w w  w. j a v a 2  s  . co 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);
    FileInputStream is = new FileInputStream("templates/testParsingErrorSimpleTag.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    DocumentParser parser = new DocumentParser(document, queryEnvironment);
    DocumentTemplate template = parser.parseDocument();
    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));
    TemplateGenerator generator = new TemplateGenerator("results/testParsingErrorSimpleTag.docx", template);
    generator.generate();
    assertTrue(new File("results/testParsingErrorSimpleTag.docx").exists());

    FileInputStream resIs = new FileInputStream("results/testParsingErrorSimpleTag.docx");
    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);
}

From source file:org.obeonetwork.m2doc.generator.test.TemplateValidationGeneratorTest.java

License:Open Source License

/**
 * Ensure that the validation generation produces a document with errors in the good order.
 * /*from   ww  w.j  a  v  a2s  .com*/
 * @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)) {
        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.generator.UserContentRawCopy.java

License:Open Source License

/**
 * Copy.//from   w w w.  ja v  a2  s  .  c o  m
 * 
 * @param userContent
 *            UserContent EObject
 * @param outputParagraphBeforeUserDocContent
 *            Output Paragraph Before User Doc Dest content (User Code dest is writen by {@link M2DocEvaluator} )
 * @param outputBody
 *            output body
 * @return last paragraph created by copy
 * @throws InvalidFormatException
 *             InvalidFormatException
 * @throws XmlException
 *             XmlException
 * @throws IOException
 *             if the copy fails
 */
@SuppressWarnings("resource")
public XWPFParagraph copy(UserContent userContent, XWPFParagraph outputParagraphBeforeUserDocContent,
        IBody outputBody) throws InvalidFormatException, XmlException, IOException {
    XWPFDocument containerOutputDocument = outputParagraphBeforeUserDocContent.getDocument();
    // Test if run before userContent is in same XWPFParagraph than first run of userContent
    if (!userDocContentIsFirstRunOfParagraph(userContent)) {
        previousInputParagraph = (XWPFParagraph) userContent.getRuns().get(userContent.getRuns().size() - 1)
                .getParent();
        currentInputParagraph = previousInputParagraph;
        currentOutputParagraph = outputParagraphBeforeUserDocContent;
    }
    XWPFParagraph currentRunParagraph = null;
    for (IConstruct abstractConstruct : userContent.getBody().getStatements()) {
        for (XWPFRun inputRun : abstractConstruct.getRuns()) {
            currentRunParagraph = (XWPFParagraph) inputRun.getParent();
            if (currentRunParagraph != currentInputParagraph) {
                currentInputParagraph = currentRunParagraph;
                // currentOutputParagraph = outputDocument.createParagraph();
                currentOutputParagraph = createNewParagraph(outputBody);
                // Copy new paragraph
                currentOutputParagraph.getCTP().set(currentInputParagraph.getCTP());
                listOutputParagraphs.add(currentOutputParagraph);
            }
            // Test if some run exist between userContent tag and first paragraph in this tag
            if (currentRunParagraph == previousInputParagraph) {
                // Clone run directly, paragraph is already generate by normal processing
                XWPFRun outputRun = currentOutputParagraph.createRun();
                outputRun.getCTR().set(inputRun.getCTR());
                // Keep run to change relation id later
                listOutputRuns.add(outputRun);
            }
            // Create picture embedded in run and keep relation id in map (input to output)
            createPictures(inputRun, containerOutputDocument);
        }
        // In case of table (no run in abstractConstruct)
        if (abstractConstruct instanceof Table) {
            Table table = (Table) abstractConstruct;
            XWPFTable inputTable = table.getTable();
            // XWPFTable outputTable = contenerOutputDocument.createTable();
            XWPFTable outputTable = createNewTable(outputBody, inputTable);
            outputTable.getCTTbl().set(inputTable.getCTTbl());
            copyTableStyle(inputTable, containerOutputDocument);
            listOutputTables.add(outputTable);
            // Inspect table to extract all picture ID in run
            collectRelationId(inputTable, containerOutputDocument);

        }
    }
    // Change Picture Id by xml replacement
    changePictureId();

    if (userContent.getClosingRuns().size() != 0
            && currentInputParagraph == userContent.getClosingRuns().get(0).getParent()) {
        needNewParagraph = false;
    }
    return currentOutputParagraph;
}

From source file:org.obeonetwork.m2doc.generator.UserContentRawCopy.java

License:Open Source License

/**
 * Test if first userContent content begin by a paragraph.
 * /*from   w  w  w  .j  a  v  a2 s  . c o  m*/
 * @param userContent
 *            userContent EObject
 * @return true if userContent content begin by a paragraph
 */
private boolean userDocContentIsFirstRunOfParagraph(UserContent userContent) {
    boolean result = true;
    if (userContent.getBody() != null && userContent.getBody().getStatements().size() > 0
            && userContent.getBody().getStatements().get(0).getRuns().size() > 0) {
        XWPFRun userContentFirstRun = userContent.getBody().getStatements().get(0).getRuns().get(0);
        XWPFParagraph userContentFirstRunParagraph = (XWPFParagraph) userContentFirstRun.getParent();
        if (userContentFirstRunParagraph != null && userContentFirstRunParagraph.getRuns().size() > 0) {
            XWPFRun paragraphFirstRun = userContentFirstRunParagraph.getRuns().get(0);
            result = userContentFirstRun == paragraphFirstRun;
        }
    }
    return result;
}

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  www.j a v a2 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.util.M2DocUtils.java

License:Open Source License

/**
 * Inserts a new message {@link XWPFRun} after the given {@link XWPFRun}.
 * /*  w ww  .j a  v  a 2 s  . co m*/
 * @param run
 *            the {@link XWPFRun} used as reference.
 * @param level
 *            the {@link ValidationMessageLevel}
 * @param message
 *            the message
 * @return the created {@link XWPFRun}
 */
public static XWPFRun insertMessageAfter(XWPFRun run, ValidationMessageLevel level, String message) {
    final XWPFRun res;

    final IRunBody parent = run.getParent();
    if (parent instanceof XWPFParagraph) {
        final XWPFParagraph paragraph = (XWPFParagraph) parent;
        res = paragraph.insertNewRun(paragraph.getRuns().indexOf(run));
        setRunMessage(res, level, message);
    } else {
        throw new IllegalStateException("this should not happend");
    }

    return res;
}