From ca1705609606c773106db2a00a5951e416b15cbd Mon Sep 17 00:00:00 2001 From: Tim Allison Date: Fri, 29 May 2015 14:01:31 +0000 Subject: [PATCH] POI-57975: clean up white spaces and other style issues in XWPF git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1682473 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/poi/util/OOXMLLite.java | 14 +- .../poi/xwpf/extractor/XWPFWordExtractor.java | 295 ++-- .../apache/poi/xwpf/model/XMLParagraph.java | 17 +- .../poi/xwpf/model/XWPFCommentsDecorator.java | 56 +- .../xwpf/model/XWPFHeaderFooterPolicy.java | 94 +- .../xwpf/model/XWPFHyperlinkDecorator.java | 81 +- .../xwpf/model/XWPFParagraphDecorator.java | 36 +- .../java/org/apache/poi/xwpf/package.html | 8 +- .../poi/xwpf/usermodel/AbstractXWPFSDT.java | 188 ++- .../poi/xwpf/usermodel/BodyElementType.java | 23 +- .../apache/poi/xwpf/usermodel/Borders.java | 74 +- .../apache/poi/xwpf/usermodel/BreakClear.java | 85 +- .../apache/poi/xwpf/usermodel/BreakType.java | 81 +- .../apache/poi/xwpf/usermodel/Document.java | 64 +- .../org/apache/poi/xwpf/usermodel/IBody.java | 172 +-- .../poi/xwpf/usermodel/IBodyElement.java | 27 +- .../org/apache/poi/xwpf/usermodel/ICell.java | 20 +- .../apache/poi/xwpf/usermodel/IRunBody.java | 7 +- .../poi/xwpf/usermodel/IRunElement.java | 9 +- .../poi/xwpf/usermodel/ISDTContent.java | 33 +- .../poi/xwpf/usermodel/ISDTContents.java | 4 +- .../poi/xwpf/usermodel/LineSpacingRule.java | 71 +- .../xwpf/usermodel/ParagraphAlignment.java | 55 +- .../xwpf/usermodel/PositionInParagraph.java | 90 +- .../org/apache/poi/xwpf/usermodel/TOC.java | 164 +-- .../poi/xwpf/usermodel/TextAlignment.java | 101 +- .../poi/xwpf/usermodel/TextSegement.java | 161 +-- .../poi/xwpf/usermodel/UnderlinePatterns.java | 71 +- .../poi/xwpf/usermodel/VerticalAlign.java | 71 +- .../poi/xwpf/usermodel/XWPFAbstractNum.java | 79 +- .../poi/xwpf/usermodel/XWPFComment.java | 33 +- .../usermodel/XWPFDefaultParagraphStyle.java | 30 +- .../xwpf/usermodel/XWPFDefaultRunStyle.java | 30 +- .../poi/xwpf/usermodel/XWPFDocument.java | 483 +++---- .../poi/xwpf/usermodel/XWPFFactory.java | 83 +- .../apache/poi/xwpf/usermodel/XWPFFooter.java | 25 +- .../poi/xwpf/usermodel/XWPFFootnote.java | 546 ++++---- .../poi/xwpf/usermodel/XWPFFootnotes.java | 200 +-- .../apache/poi/xwpf/usermodel/XWPFHeader.java | 20 +- .../poi/xwpf/usermodel/XWPFHeaderFooter.java | 231 ++-- .../poi/xwpf/usermodel/XWPFHyperlink.java | 22 +- .../poi/xwpf/usermodel/XWPFHyperlinkRun.java | 84 +- .../poi/xwpf/usermodel/XWPFLatentStyles.java | 62 +- .../apache/poi/xwpf/usermodel/XWPFNum.java | 87 +- .../poi/xwpf/usermodel/XWPFNumbering.java | 473 +++---- .../poi/xwpf/usermodel/XWPFParagraph.java | 696 +++++----- .../poi/xwpf/usermodel/XWPFPicture.java | 82 +- .../poi/xwpf/usermodel/XWPFPictureData.java | 108 +- .../poi/xwpf/usermodel/XWPFRelation.java | 123 +- .../apache/poi/xwpf/usermodel/XWPFRun.java | 1231 +++++++++-------- .../apache/poi/xwpf/usermodel/XWPFSDT.java | 55 +- .../poi/xwpf/usermodel/XWPFSDTCell.java | 51 +- .../poi/xwpf/usermodel/XWPFSDTContent.java | 190 ++- .../xwpf/usermodel/XWPFSDTContentCell.java | 135 +- .../poi/xwpf/usermodel/XWPFSettings.java | 207 +-- .../apache/poi/xwpf/usermodel/XWPFStyle.java | 263 ++-- .../apache/poi/xwpf/usermodel/XWPFStyles.java | 430 +++--- .../apache/poi/xwpf/usermodel/XWPFTable.java | 95 +- .../poi/xwpf/usermodel/XWPFTableCell.java | 851 ++++++------ .../poi/xwpf/usermodel/XWPFTableRow.java | 372 ++--- .../org/apache/poi/xwpf/AllXWPFTests.java | 40 +- .../poi/xwpf/TestAllExtendedProperties.java | 160 ++- .../TestPackageCorePropertiesGetKeywords.java | 58 +- .../org/apache/poi/xwpf/TestXWPFBugs.java | 10 +- .../xwpf/extractor/TestExternalEntities.java | 8 +- .../xwpf/extractor/TestXWPFWordExtractor.java | 142 +- .../poi/xwpf/model/TestXWPFDecorators.java | 159 ++- .../model/TestXWPFHeaderFooterPolicy.java | 253 ++-- .../xwpf/usermodel/TestChangeTracking.java | 2 +- .../poi/xwpf/usermodel/TestXWPFBugs.java | 46 +- .../poi/xwpf/usermodel/TestXWPFDocument.java | 46 +- .../poi/xwpf/usermodel/TestXWPFFootnotes.java | 96 +- .../poi/xwpf/usermodel/TestXWPFHeader.java | 41 +- .../poi/xwpf/usermodel/TestXWPFHeadings.java | 65 +- .../poi/xwpf/usermodel/TestXWPFNumbering.java | 165 ++- .../poi/xwpf/usermodel/TestXWPFParagraph.java | 278 ++-- .../xwpf/usermodel/TestXWPFPictureData.java | 227 ++- .../poi/xwpf/usermodel/TestXWPFRun.java | 470 +++---- .../poi/xwpf/usermodel/TestXWPFSDT.java | 293 ++-- .../poi/xwpf/usermodel/TestXWPFSmartTag.java | 3 +- .../poi/xwpf/usermodel/TestXWPFStyles.java | 285 ++-- .../poi/xwpf/usermodel/TestXWPFTable.java | 169 ++- .../poi/xwpf/usermodel/TestXWPFTableCell.java | 123 +- .../poi/xwpf/usermodel/TestXWPFTableRow.java | 103 +- 84 files changed, 6485 insertions(+), 6306 deletions(-) diff --git a/src/ooxml/java/org/apache/poi/util/OOXMLLite.java b/src/ooxml/java/org/apache/poi/util/OOXMLLite.java index 3b8dc32203..0503dfa766 100644 --- a/src/ooxml/java/org/apache/poi/util/OOXMLLite.java +++ b/src/ooxml/java/org/apache/poi/util/OOXMLLite.java @@ -32,14 +32,12 @@ import java.util.Map; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarFile; -import java.util.regex.Pattern; - -import junit.framework.TestCase; - -import org.junit.Test; -import org.junit.internal.TextListener; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; +import java.util.regex.Pattern; + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.internal.TextListener; +import org.junit.runner.JUnitCore;import org.junit.runner.Result; /** * Build a 'lite' version of the ooxml-schemas.jar diff --git a/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java b/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java index afff770c74..ec701b7e32 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java +++ b/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java @@ -46,46 +46,47 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; * Helper class to extract text from an OOXML Word file */ public class XWPFWordExtractor extends POIXMLTextExtractor { - public static final XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[] { - XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE, - XWPFRelation.MACRO_DOCUMENT, - XWPFRelation.MACRO_TEMPLATE_DOCUMENT - }; - - private XWPFDocument document; - private boolean fetchHyperlinks = false; - - public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { - this(new XWPFDocument(container)); - } - public XWPFWordExtractor(XWPFDocument document) { - super(document); - this.document = document; - } - - /** - * Should we also fetch the hyperlinks, when fetching - * the text content? Default is to only output the - * hyperlink label, and not the contents - */ - public void setFetchHyperlinks(boolean fetch) { - fetchHyperlinks = fetch; - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" XWPFWordExtractor "); - System.exit(1); - } - POIXMLTextExtractor extractor = - new XWPFWordExtractor(POIXMLDocument.openPackage( - args[0] - )); - System.out.println(extractor.getText()); - extractor.close(); - } - + public static final XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[]{ + XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE, + XWPFRelation.MACRO_DOCUMENT, + XWPFRelation.MACRO_TEMPLATE_DOCUMENT + }; + + private XWPFDocument document; + private boolean fetchHyperlinks = false; + + public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { + this(new XWPFDocument(container)); + } + + public XWPFWordExtractor(XWPFDocument document) { + super(document); + this.document = document; + } + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("Use:"); + System.err.println(" XWPFWordExtractor "); + System.exit(1); + } + POIXMLTextExtractor extractor = + new XWPFWordExtractor(POIXMLDocument.openPackage( + args[0] + )); + System.out.println(extractor.getText()); + extractor.close(); + } + + /** + * Should we also fetch the hyperlinks, when fetching + * the text content? Default is to only output the + * hyperlink label, and not the contents + */ + public void setFetchHyperlinks(boolean fetch) { + fetchHyperlinks = fetch; + } + public String getText() { StringBuffer text = new StringBuffer(); XWPFHeaderFooterPolicy hfPolicy = document.getHeaderFooterPolicy(); @@ -94,9 +95,9 @@ public class XWPFWordExtractor extends POIXMLTextExtractor { extractHeaders(text, hfPolicy); // Process all body elements - for (IBodyElement e : document.getBodyElements()){ - appendBodyElementText(text, e); - text.append('\n'); + for (IBodyElement e : document.getBodyElements()) { + appendBodyElementText(text, e); + text.append('\n'); } // Finish up with all the footers @@ -105,108 +106,108 @@ public class XWPFWordExtractor extends POIXMLTextExtractor { return text.toString(); } - public void appendBodyElementText(StringBuffer text, IBodyElement e){ - if (e instanceof XWPFParagraph){ - appendParagraphText(text, (XWPFParagraph)e); - } else if (e instanceof XWPFTable){ - appendTableText(text, (XWPFTable)e); - } else if (e instanceof XWPFSDT){ - text.append(((XWPFSDT)e).getContent().getText()); - } - } - - public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph){ - try { - CTSectPr ctSectPr = null; - if (paragraph.getCTP().getPPr()!=null) { - ctSectPr = paragraph.getCTP().getPPr().getSectPr(); - } - - XWPFHeaderFooterPolicy headerFooterPolicy = null; - - if (ctSectPr!=null) { - headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr); - extractHeaders(text, headerFooterPolicy); - } - - - for(IRunElement run : paragraph.getRuns()) { - text.append(run.toString()); - if(run instanceof XWPFHyperlinkRun && fetchHyperlinks) { - XWPFHyperlink link = ((XWPFHyperlinkRun)run).getHyperlink(document); - if(link != null) - text.append(" <" + link.getURL() + ">"); - } - } - - // Add comments - XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null); - String commentText = decorator.getCommentText(); - if (commentText.length() > 0){ - text.append(commentText).append('\n'); - } - - // Do endnotes and footnotes - String footnameText = paragraph.getFootnoteText(); - if(footnameText != null && footnameText.length() > 0) { - text.append(footnameText + '\n'); - } - - if (ctSectPr!=null) { - extractFooters(text, headerFooterPolicy); - } - } catch (IOException e) { - throw new POIXMLException(e); - } catch (XmlException e) { - throw new POIXMLException(e); - } - - } - - private void appendTableText(StringBuffer text, XWPFTable table) { - //this works recursively to pull embedded tables from tables - for (XWPFTableRow row : table.getRows()) { - List cells = row.getTableICells(); - for (int i = 0; i < cells.size(); i++) { - ICell cell = cells.get(i); - if (cell instanceof XWPFTableCell) { - text.append(((XWPFTableCell)cell).getTextRecursively()); - } else if (cell instanceof XWPFSDTCell) { - text.append(((XWPFSDTCell)cell).getContent().getText()); - } - if (i < cells.size()-1) { - text.append("\t"); - } - } - text.append('\n'); - } - } - - private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { - if (hfPolicy == null) return; - - if(hfPolicy.getFirstPageFooter() != null) { - text.append( hfPolicy.getFirstPageFooter().getText() ); - } - if(hfPolicy.getEvenPageFooter() != null) { - text.append( hfPolicy.getEvenPageFooter().getText() ); - } - if(hfPolicy.getDefaultFooter() != null) { - text.append( hfPolicy.getDefaultFooter().getText() ); - } - } - - private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { - if (hfPolicy == null) return; - - if(hfPolicy.getFirstPageHeader() != null) { - text.append( hfPolicy.getFirstPageHeader().getText() ); - } - if(hfPolicy.getEvenPageHeader() != null) { - text.append( hfPolicy.getEvenPageHeader().getText() ); - } - if(hfPolicy.getDefaultHeader() != null) { - text.append( hfPolicy.getDefaultHeader().getText() ); - } - } + public void appendBodyElementText(StringBuffer text, IBodyElement e) { + if (e instanceof XWPFParagraph) { + appendParagraphText(text, (XWPFParagraph) e); + } else if (e instanceof XWPFTable) { + appendTableText(text, (XWPFTable) e); + } else if (e instanceof XWPFSDT) { + text.append(((XWPFSDT) e).getContent().getText()); + } + } + + public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph) { + try { + CTSectPr ctSectPr = null; + if (paragraph.getCTP().getPPr() != null) { + ctSectPr = paragraph.getCTP().getPPr().getSectPr(); + } + + XWPFHeaderFooterPolicy headerFooterPolicy = null; + + if (ctSectPr != null) { + headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr); + extractHeaders(text, headerFooterPolicy); + } + + + for (IRunElement run : paragraph.getRuns()) { + text.append(run.toString()); + if (run instanceof XWPFHyperlinkRun && fetchHyperlinks) { + XWPFHyperlink link = ((XWPFHyperlinkRun) run).getHyperlink(document); + if (link != null) + text.append(" <" + link.getURL() + ">"); + } + } + + // Add comments + XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null); + String commentText = decorator.getCommentText(); + if (commentText.length() > 0) { + text.append(commentText).append('\n'); + } + + // Do endnotes and footnotes + String footnameText = paragraph.getFootnoteText(); + if (footnameText != null && footnameText.length() > 0) { + text.append(footnameText + '\n'); + } + + if (ctSectPr != null) { + extractFooters(text, headerFooterPolicy); + } + } catch (IOException e) { + throw new POIXMLException(e); + } catch (XmlException e) { + throw new POIXMLException(e); + } + + } + + private void appendTableText(StringBuffer text, XWPFTable table) { + //this works recursively to pull embedded tables from tables + for (XWPFTableRow row : table.getRows()) { + List cells = row.getTableICells(); + for (int i = 0; i < cells.size(); i++) { + ICell cell = cells.get(i); + if (cell instanceof XWPFTableCell) { + text.append(((XWPFTableCell) cell).getTextRecursively()); + } else if (cell instanceof XWPFSDTCell) { + text.append(((XWPFSDTCell) cell).getContent().getText()); + } + if (i < cells.size() - 1) { + text.append("\t"); + } + } + text.append('\n'); + } + } + + private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { + if (hfPolicy == null) return; + + if (hfPolicy.getFirstPageFooter() != null) { + text.append(hfPolicy.getFirstPageFooter().getText()); + } + if (hfPolicy.getEvenPageFooter() != null) { + text.append(hfPolicy.getEvenPageFooter().getText()); + } + if (hfPolicy.getDefaultFooter() != null) { + text.append(hfPolicy.getDefaultFooter().getText()); + } + } + + private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { + if (hfPolicy == null) return; + + if (hfPolicy.getFirstPageHeader() != null) { + text.append(hfPolicy.getFirstPageHeader().getText()); + } + if (hfPolicy.getEvenPageHeader() != null) { + text.append(hfPolicy.getEvenPageHeader().getText()); + } + if (hfPolicy.getDefaultHeader() != null) { + text.append(hfPolicy.getDefaultHeader().getText()); + } + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java b/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java index c7d4bc2613..25aa7aab35 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java +++ b/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java @@ -22,16 +22,15 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; * Base class for XWPF paragraphs * * @author Yury Batrakov (batrakov at gmail.com) - * */ public class XMLParagraph { - protected CTP paragraph; - - public XMLParagraph(CTP paragraph) { - this.paragraph = paragraph; - } + protected CTP paragraph; - public CTP getCTP() { - return paragraph; - } + public XMLParagraph(CTP paragraph) { + this.paragraph = paragraph; + } + + public CTP getCTP() { + return paragraph; + } } \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java index 502a3b7861..bf2b5e8f41 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java +++ b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java @@ -21,38 +21,36 @@ import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTMarkupRange; /** - * Decorator class for XWPFParagraph allowing to add comments + * Decorator class for XWPFParagraph allowing to add comments * found in paragraph to its text * * @author Yury Batrakov (batrakov at gmail.com) - * */ public class XWPFCommentsDecorator extends XWPFParagraphDecorator { - private StringBuffer commentText; - - public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) { - this(nextDecorator.paragraph, nextDecorator); - } - - @SuppressWarnings("deprecation") - public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { - super(paragraph, nextDecorator); - - XWPFComment comment; - commentText = new StringBuffer(); - - for(CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) - { - if((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null) - commentText.append("\tComment by " + comment.getAuthor()+": "+comment.getText()); - } - } - - public String getCommentText() { - return commentText.toString(); - } - - public String getText() { - return super.getText() + commentText; - } + private StringBuffer commentText; + + public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) { + this(nextDecorator.paragraph, nextDecorator); + } + + @SuppressWarnings("deprecation") + public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { + super(paragraph, nextDecorator); + + XWPFComment comment; + commentText = new StringBuffer(); + + for (CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) { + if ((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null) + commentText.append("\tComment by " + comment.getAuthor() + ": " + comment.getText()); + } + } + + public String getCommentText() { + return commentText.toString(); + } + + public String getText() { + return super.getText() + commentText; + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java index 15783163ea..700645df75 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java +++ b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java @@ -45,7 +45,6 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.FtrDocument; import org.openxmlformats.schemas.wordprocessingml.x2006.main.HdrDocument; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum; - import schemasMicrosoftComOfficeOffice.CTLock; import schemasMicrosoftComOfficeOffice.STConnectType; import schemasMicrosoftComVml.CTFormulas; @@ -61,10 +60,10 @@ import schemasMicrosoftComVml.STTrueFalse; /** * A .docx file can have no headers/footers, the same header/footer - * on each page, odd/even page footers, and optionally also - * a different header/footer on the first page. + * on each page, odd/even page footers, and optionally also + * a different header/footer on the first page. * This class handles sorting out what there is, and giving you - * the right headers and footers for the document. + * the right headers and footers for the document. */ public class XWPFHeaderFooterPolicy { public static final Enum DEFAULT = STHdrFtr.DEFAULT; @@ -84,8 +83,8 @@ public class XWPFHeaderFooterPolicy { /** * Figures out the policy for the given document, - * and creates any header and footer objects - * as required. + * and creates any header and footer objects + * as required. */ public XWPFHeaderFooterPolicy(XWPFDocument doc) throws IOException, XmlException { this(doc, doc.getDocument().getBody().getSectPr()); @@ -93,8 +92,8 @@ public class XWPFHeaderFooterPolicy { /** * Figures out the policy for the given document, - * and creates any header and footer objects - * as required. + * and creates any header and footer objects + * as required. */ public XWPFHeaderFooterPolicy(XWPFDocument doc, CTSectPr sectPr) throws IOException, XmlException { // Grab what headers and footers have been defined @@ -102,7 +101,7 @@ public class XWPFHeaderFooterPolicy { // doesn't seem that .docx properly supports that // feature of the file format yet this.doc = doc; - for(int i=0; i relations = doc.getRelations(); int i = 1; - for (Iterator it = relations.iterator(); it.hasNext() ; ) { + for (Iterator it = relations.iterator(); it.hasNext(); ) { POIXMLDocumentPart item = it.next(); if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) { - i++; + i++; } } return i; @@ -231,14 +229,14 @@ public class XWPFHeaderFooterPolicy { private CTHdrFtr buildFtr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { //CTHdrFtr ftr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 - CTHdrFtr ftr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010 + CTHdrFtr ftr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010 setFooterReference(type, wrapper); return ftr; } private CTHdrFtr buildHdr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { //CTHdrFtr hdr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 - CTHdrFtr hdr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010 + CTHdrFtr hdr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010 setHeaderReference(type, wrapper); return hdr; } @@ -246,13 +244,12 @@ public class XWPFHeaderFooterPolicy { private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs) { CTHdrFtr ftr = CTHdrFtr.Factory.newInstance(); if (paragraphs != null) { - for (int i = 0 ; i < paragraphs.length ; i++) { + for (int i = 0; i < paragraphs.length; i++) { CTP p = ftr.addNewP(); //ftr.setPArray(0, paragraphs[i].getCTP()); // MB 23 May 2010 - ftr.setPArray(i, paragraphs[i].getCTP()); // MB 23 May 2010 + ftr.setPArray(i, paragraphs[i].getCTP()); // MB 23 May 2010 } - } - else { + } else { CTP p = ftr.addNewP(); byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR(); byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault(); @@ -270,21 +267,20 @@ public class XWPFHeaderFooterPolicy { * and createFooter(int, XWPFParagraph[]) methods or the getXXXXXHeader/Footer methods where * headers or footers had been added to a document since it had been created/opened, returned * an object that contained no XWPFParagraph objects even if the header/footer itself did contain - * text. The reason was that this line of code; CTHdrFtr ftr = CTHdrFtr.Factory.newInstance(); + * text. The reason was that this line of code; CTHdrFtr ftr = CTHdrFtr.Factory.newInstance(); * created a brand new instance of the CTHDRFtr class which was then populated with data when * it should have recovered the CTHdrFtr object encapsulated within the XWPFHeaderFooter object - * that had previoulsy been instantiated in the createHeader(int, XWPFParagraph[]) or + * that had previoulsy been instantiated in the createHeader(int, XWPFParagraph[]) or * createFooter(int, XWPFParagraph[]) methods. */ private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs, XWPFHeaderFooter wrapper) { CTHdrFtr ftr = wrapper._getHdrFtr(); if (paragraphs != null) { - for (int i = 0 ; i < paragraphs.length ; i++) { + for (int i = 0; i < paragraphs.length; i++) { CTP p = ftr.addNewP(); ftr.setPArray(i, paragraphs[i].getCTP()); } - } - else { + } else { CTP p = ftr.addNewP(); byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR(); byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault(); @@ -330,60 +326,70 @@ public class XWPFHeaderFooterPolicy { public XWPFHeader getFirstPageHeader() { return firstPageHeader; } + public XWPFFooter getFirstPageFooter() { return firstPageFooter; } + /** * Returns the odd page header. This is - * also the same as the default one... + * also the same as the default one... */ public XWPFHeader getOddPageHeader() { return defaultHeader; } + /** * Returns the odd page footer. This is - * also the same as the default one... + * also the same as the default one... */ public XWPFFooter getOddPageFooter() { return defaultFooter; } + public XWPFHeader getEvenPageHeader() { return evenPageHeader; } + public XWPFFooter getEvenPageFooter() { return evenPageFooter; } + public XWPFHeader getDefaultHeader() { return defaultHeader; } + public XWPFFooter getDefaultFooter() { return defaultFooter; } /** * Get the header that applies to the given - * (1 based) page. + * (1 based) page. + * * @param pageNumber The one based page number */ public XWPFHeader getHeader(int pageNumber) { - if(pageNumber == 1 && firstPageHeader != null) { + if (pageNumber == 1 && firstPageHeader != null) { return firstPageHeader; } - if(pageNumber % 2 == 0 && evenPageHeader != null) { + if (pageNumber % 2 == 0 && evenPageHeader != null) { return evenPageHeader; } return defaultHeader; } + /** * Get the footer that applies to the given - * (1 based) page. + * (1 based) page. + * * @param pageNumber The one based page number */ public XWPFFooter getFooter(int pageNumber) { - if(pageNumber == 1 && firstPageFooter != null) { + if (pageNumber == 1 && firstPageFooter != null) { return firstPageFooter; } - if(pageNumber % 2 == 0 && evenPageFooter != null) { + if (pageNumber % 2 == 0 && evenPageFooter != null) { return evenPageFooter; } return defaultFooter; @@ -459,7 +465,7 @@ public class XWPFHeaderFooterPolicy { lock.setExt(STExt.EDIT); CTShape shape = group.addNewShape(); shape.setId("PowerPlusWaterMarkObject" + idx); - shape.setSpid("_x0000_s102" + (4+idx)); + shape.setSpid("_x0000_s102" + (4 + idx)); shape.setType("#_x0000_t136"); shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin"); shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068"); diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHyperlinkDecorator.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHyperlinkDecorator.java index d8120340f5..27e8282eaf 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHyperlinkDecorator.java +++ b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHyperlinkDecorator.java @@ -23,50 +23,49 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; /** - * Decorator class for XWPFParagraph allowing to add hyperlinks - * found in paragraph to its text. - * + * Decorator class for XWPFParagraph allowing to add hyperlinks + * found in paragraph to its text. + *

* Note - adds the hyperlink at the end, not in the right place... - * + * * @deprecated Use {@link XWPFHyperlinkRun} instead */ @Deprecated public class XWPFHyperlinkDecorator extends XWPFParagraphDecorator { - private StringBuffer hyperlinkText; - - /** - * @param nextDecorator The next decorator to use - * @param outputHyperlinkUrls Should we output the links too, or just the link text? - */ - public XWPFHyperlinkDecorator(XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) { - this(nextDecorator.paragraph, nextDecorator, outputHyperlinkUrls); - } - - /** - * @param prgrph The paragraph of text to work on - * @param outputHyperlinkUrls Should we output the links too, or just the link text? - */ - public XWPFHyperlinkDecorator(XWPFParagraph prgrph, XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) { - super(prgrph, nextDecorator); - - hyperlinkText = new StringBuffer(); - - // loop over hyperlink anchors - for(CTHyperlink link : paragraph.getCTP().getHyperlinkArray()){ - for (CTR r : link.getRArray()) { - // Loop over text runs - for (CTText text : r.getTArray()){ - hyperlinkText.append(text.getStringValue()); - } - } - if(outputHyperlinkUrls && paragraph.getDocument().getHyperlinkByID(link.getId()) != null) { - hyperlinkText.append(" <"+paragraph.getDocument().getHyperlinkByID(link.getId()).getURL()+">"); - } - } - } - - public String getText() - { - return super.getText() + hyperlinkText; - } + private StringBuffer hyperlinkText; + + /** + * @param nextDecorator The next decorator to use + * @param outputHyperlinkUrls Should we output the links too, or just the link text? + */ + public XWPFHyperlinkDecorator(XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) { + this(nextDecorator.paragraph, nextDecorator, outputHyperlinkUrls); + } + + /** + * @param prgrph The paragraph of text to work on + * @param outputHyperlinkUrls Should we output the links too, or just the link text? + */ + public XWPFHyperlinkDecorator(XWPFParagraph prgrph, XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) { + super(prgrph, nextDecorator); + + hyperlinkText = new StringBuffer(); + + // loop over hyperlink anchors + for (CTHyperlink link : paragraph.getCTP().getHyperlinkArray()) { + for (CTR r : link.getRArray()) { + // Loop over text runs + for (CTText text : r.getTArray()) { + hyperlinkText.append(text.getStringValue()); + } + } + if (outputHyperlinkUrls && paragraph.getDocument().getHyperlinkByID(link.getId()) != null) { + hyperlinkText.append(" <" + paragraph.getDocument().getHyperlinkByID(link.getId()).getURL() + ">"); + } + } + } + + public String getText() { + return super.getText() + hyperlinkText; + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java index 3946b22b88..46636c3ef2 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java +++ b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java @@ -22,22 +22,22 @@ import org.apache.poi.xwpf.usermodel.XWPFParagraph; * Base decorator class for XWPFParagraph */ public abstract class XWPFParagraphDecorator { - protected XWPFParagraph paragraph; - protected XWPFParagraphDecorator nextDecorator; - - public XWPFParagraphDecorator(XWPFParagraph paragraph) { - this(paragraph, null); - } - - public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { - this.paragraph = paragraph; - this.nextDecorator = nextDecorator; - } - - public String getText() { - if(nextDecorator != null) { - return nextDecorator.getText(); - } - return paragraph.getText(); - } + protected XWPFParagraph paragraph; + protected XWPFParagraphDecorator nextDecorator; + + public XWPFParagraphDecorator(XWPFParagraph paragraph) { + this(paragraph, null); + } + + public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { + this.paragraph = paragraph; + this.nextDecorator = nextDecorator; + } + + public String getText() { + if (nextDecorator != null) { + return nextDecorator.getText(); + } + return paragraph.getText(); + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/package.html b/src/ooxml/java/org/apache/poi/xwpf/package.html index 8c6c70d9e0..0a59556461 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/package.html +++ b/src/ooxml/java/org/apache/poi/xwpf/package.html @@ -19,9 +19,9 @@ --> -

This package contains classes for handling Microsoft .docx - Word Processing files, known in POI as XWPF (XML Word Processing - Format). -

+

This package contains classes for handling Microsoft .docx + Word Processing files, known in POI as XWPF (XML Word Processing + Format). +

diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java index e69b0244e7..0e275460a0 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java @@ -13,102 +13,92 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; - -/** - * Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell - * - * WARNING - APIs expected to change rapidly. - * - * These classes have so far been built only for read-only processing. - * - */ -public abstract class AbstractXWPFSDT implements ISDTContents { - private final String title; - private final String tag; - private final IBody part; - - @SuppressWarnings("deprecation") - public AbstractXWPFSDT(CTSdtPr pr, IBody part){ - - CTString[] aliases = pr.getAliasArray(); - if (aliases != null && aliases.length > 0){ - title = aliases[0].getVal(); - } else { - title = ""; - } - CTString[] tags = pr.getTagArray(); - if (tags != null && tags.length > 0){ - tag = tags[0].getVal(); - } else { - tag = ""; - } - this.part = part; - - } - - /** - * - * @return first SDT Title - */ - public String getTitle(){ - return title; - } - - /** - * - * @return first SDT Tag - */ - public String getTag(){ - return tag; - } - - /** - * - * @return the content object - */ - public abstract ISDTContent getContent(); - - /** - * - * @return null - */ - public IBody getBody() { - return null; - } - - /** - * - * @return document part - */ - public POIXMLDocumentPart getPart() { - return part.getPart(); - } - - /** - * - * @return partType - */ - public BodyType getPartType() { - return BodyType.CONTENTCONTROL; - } - - /** - * - * @return element type - */ - public BodyElementType getElementType() { - return BodyElementType.CONTENTCONTROL; - } - - public XWPFDocument getDocument() { - return part.getXWPFDocument(); - } -} +==================================================================== */ +package org.apache.poi.xwpf.usermodel; + +import org.apache.poi.POIXMLDocumentPart; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; + +/** + * Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell + *

+ * WARNING - APIs expected to change rapidly. + *

+ * These classes have so far been built only for read-only processing. + */ +public abstract class AbstractXWPFSDT implements ISDTContents { + private final String title; + private final String tag; + private final IBody part; + + @SuppressWarnings("deprecation") + public AbstractXWPFSDT(CTSdtPr pr, IBody part) { + + CTString[] aliases = pr.getAliasArray(); + if (aliases != null && aliases.length > 0) { + title = aliases[0].getVal(); + } else { + title = ""; + } + CTString[] tags = pr.getTagArray(); + if (tags != null && tags.length > 0) { + tag = tags[0].getVal(); + } else { + tag = ""; + } + this.part = part; + + } + + /** + * @return first SDT Title + */ + public String getTitle() { + return title; + } + + /** + * @return first SDT Tag + */ + public String getTag() { + return tag; + } + + /** + * @return the content object + */ + public abstract ISDTContent getContent(); + + /** + * @return null + */ + public IBody getBody() { + return null; + } + + /** + * @return document part + */ + public POIXMLDocumentPart getPart() { + return part.getPart(); + } + + /** + * @return partType + */ + public BodyType getPartType() { + return BodyType.CONTENTCONTROL; + } + + /** + * @return element type + */ + public BodyElementType getElementType() { + return BodyElementType.CONTENTCONTROL; + } + + public XWPFDocument getDocument() { + return part.getXWPFDocument(); + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java index 160c637bdc..5a1df0e218 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java @@ -21,15 +21,14 @@ package org.apache.poi.xwpf.usermodel; *

* 9 Jan 2010 *

- *

- * // TODO insert Javadoc here! - *

- * @author epp - * - */ -public enum BodyElementType { - CONTENTCONTROL, - PARAGRAPH, - TABLE, - -} + *

+ * // TODO insert Javadoc here! + *

+ * + * @author epp + */ +public enum BodyElementType { + CONTENTCONTROL, + PARAGRAPH, + TABLE, +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java index 48ea33d2ac..b7937e5282 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java @@ -29,14 +29,15 @@ import java.util.Map; * *
  • Art borders: which specify a repeated image to be used * when drawing a border around the specified object. Line borders may be - * specified on any object which allows a border, however, art borders may only - * be used as a border at the page level - the borders under the pgBorders - * element - *
  • - * - * @author Gisella Bronzetti - */ -public enum Borders { + * specified on any object which allows a border, however, art borders may only + * be used as a border at the page level - the borders under the pgBorders + * element + * + * + * + * @author Gisella Bronzetti + */ +public enum Borders { NIL(1), @@ -596,31 +597,32 @@ public enum Borders { ZANY_TRIANGLES(189), ZIG_ZAG(190), - - ZIG_ZAG_STITCH(191); - - private final int value; - - private Borders(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static Map imap = new HashMap(); - static { - for (Borders p : values()) { - imap.put(Integer.valueOf(p.getValue()), p); - } - } - - public static Borders valueOf(int type) { - Borders pBorder = imap.get(Integer.valueOf(type)); - if (pBorder == null) { - throw new IllegalArgumentException("Unknown paragraph border: " + type); - } - return pBorder; - } -} + + ZIG_ZAG_STITCH(191); + + private static Map imap = new HashMap(); + + static { + for (Borders p : values()) { + imap.put(Integer.valueOf(p.getValue()), p); + } + } + + private final int value; + + private Borders(int val) { + value = val; + } + + public static Borders valueOf(int type) { + Borders pBorder = imap.get(Integer.valueOf(type)); + if (pBorder == null) { + throw new IllegalArgumentException("Unknown paragraph border: " + type); + } + return pBorder; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java index 8ad98905e0..4fbef1d20f 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java @@ -20,23 +20,23 @@ import java.util.HashMap; import java.util.Map; /** - * Specifies the set of possible restart locations which may be used as to - * determine the next available line when a break's type attribute has a value - * of textWrapping. - * - * @author Gisella Bronzetti - */ -public enum BreakClear { + * Specifies the set of possible restart locations which may be used as to + * determine the next available line when a break's type attribute has a value + * of textWrapping. + * + * @author Gisella Bronzetti + */ +public enum BreakClear { /** * Specifies that the text wrapping break shall advance the text to the next - * line in the WordprocessingML document, regardless of its position left to - * right or the presence of any floating objects which intersect with the - * line, - * - * This is the setting for a typical line break in a document. - */ - + * line in the WordprocessingML document, regardless of its position left to + * right or the presence of any floating objects which intersect with the + * line, + *

    + * This is the setting for a typical line break in a document. + */ + NONE(1), /** @@ -80,31 +80,32 @@ public enum BreakClear { * Specifies that the text wrapping break shall advance the text to the next * line in the WordprocessingML document which spans the full width of the * line. - */ - ALL(4); - - private final int value; - - private BreakClear(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static Map imap = new HashMap(); - static { - for (BreakClear p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static BreakClear valueOf(int type) { - BreakClear bType = imap.get(new Integer(type)); - if (bType == null) - throw new IllegalArgumentException("Unknown break clear type: " - + type); - return bType; - } -} + */ + ALL(4); + + private static Map imap = new HashMap(); + + static { + for (BreakClear p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private BreakClear(int val) { + value = val; + } + + public static BreakClear valueOf(int type) { + BreakClear bType = imap.get(new Integer(type)); + if (bType == null) + throw new IllegalArgumentException("Unknown break clear type: " + + type); + return bType; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java index 60b35225b7..94cddab502 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java @@ -21,18 +21,18 @@ import java.util.Map; /** * Specifies the possible types of break characters in a WordprocessingML - * document. - * The break type determines the next location where text shall be - * placed after this manual break is applied to the text contents - * - * @author Gisella Bronzetti - */ -public enum BreakType { - - - /** - * Specifies that the current break shall restart itself on the next page of - * the document when the document is displayed in page view. + * document. + * The break type determines the next location where text shall be + * placed after this manual break is applied to the text contents + * + * @author Gisella Bronzetti + */ +public enum BreakType { + + + /** + * Specifies that the current break shall restart itself on the next page of + * the document when the document is displayed in page view. */ PAGE(1), @@ -53,31 +53,32 @@ public enum BreakType { * the document when the document is displayed in page view. * The determine of the next line shall be done subject to the value of the clear * attribute on the specified break character. - */ - TEXT_WRAPPING(3); - - private final int value; - - private BreakType(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static Map imap = new HashMap(); - static { - for (BreakType p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static BreakType valueOf(int type) { - BreakType bType = imap.get(new Integer(type)); - if (bType == null) - throw new IllegalArgumentException("Unknown break type: " - + type); - return bType; - } -} + */ + TEXT_WRAPPING(3); + + private static Map imap = new HashMap(); + + static { + for (BreakType p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private BreakType(int val) { + value = val; + } + + public static BreakType valueOf(int type) { + BreakType bType = imap.get(new Integer(type)); + if (bType == null) + throw new IllegalArgumentException("Unknown break type: " + + type); + return bType; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java index 2df6f577f5..077697a167 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java @@ -14,31 +14,45 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -public interface Document { - /** Extended windows meta file */ - public static final int PICTURE_TYPE_EMF = 2; - - /** Windows Meta File */ - public static final int PICTURE_TYPE_WMF = 3; - - /** Mac PICT format */ - public static final int PICTURE_TYPE_PICT = 4; - - /** JPEG format */ - public static final int PICTURE_TYPE_JPEG = 5; - - /** PNG format */ - public static final int PICTURE_TYPE_PNG = 6; - - /** Device independent bitmap */ - public static final int PICTURE_TYPE_DIB = 7; - - /** GIF image format */ - public static final int PICTURE_TYPE_GIF = 8; - - /** +package org.apache.poi.xwpf.usermodel; + +public interface Document { + /** + * Extended windows meta file + */ + public static final int PICTURE_TYPE_EMF = 2; + + /** + * Windows Meta File + */ + public static final int PICTURE_TYPE_WMF = 3; + + /** + * Mac PICT format + */ + public static final int PICTURE_TYPE_PICT = 4; + + /** + * JPEG format + */ + public static final int PICTURE_TYPE_JPEG = 5; + + /** + * PNG format + */ + public static final int PICTURE_TYPE_PNG = 6; + + /** + * Device independent bitmap + */ + public static final int PICTURE_TYPE_DIB = 7; + + /** + * GIF image format + */ + public static final int PICTURE_TYPE_GIF = 8; + + /** * Tag Image File (.tiff) */ public static final int PICTURE_TYPE_TIFF = 9; diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java index e035888110..6e9ce05e4d 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java @@ -27,64 +27,68 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; /** *

    An IBody represents the different parts of the document which - * can contain collections of Paragraphs and Tables. It provides a - * common way to work with these and their contents.

    - *

    Typically, this is something like a XWPFDocument, or one of - * the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell - *

    - */ -public interface IBody { + * can contain collections of Paragraphs and Tables. It provides a + * common way to work with these and their contents.

    + *

    Typically, this is something like a XWPFDocument, or one of + * the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell + *

    + */ +public interface IBody { /** - * returns the Part, to which the body belongs, which you need for adding relationship to other parts - * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell - * belongs. - * @return the Part, to which the body belongs - */ - public POIXMLDocumentPart getPart(); - - /** - * get the PartType of the body, for example - * DOCUMENT, HEADER, FOOTER, FOOTNOTE, - * @return the PartType of the body - */ - public BodyType getPartType(); - - /** - * Returns an Iterator with paragraphs and tables, - * in the order that they occur in the text. - */ - public List getBodyElements(); - - /** - * Returns the paragraph(s) that holds - * the text of the header or footer. - */ - public List getParagraphs(); - - /** - * Return the table(s) that holds the text - * of the IBodyPart, for complex cases - * where a paragraph isn't used. - */ - public List getTables(); - - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer - * XWPFParagraph with the correspondig CTP p - */ - public XWPFParagraph getParagraph(CTP p); - - /** - * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header - * the method will return this table - * if there is no corresponding {@link XWPFTable} the method will return null - * @param ctTable - */ - public XWPFTable getTable(CTTbl ctTable); + * returns the Part, to which the body belongs, which you need for adding relationship to other parts + * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell + * belongs. + * + * @return the Part, to which the body belongs + */ + public POIXMLDocumentPart getPart(); + + /** + * get the PartType of the body, for example + * DOCUMENT, HEADER, FOOTER, FOOTNOTE, + * + * @return the PartType of the body + */ + public BodyType getPartType(); + + /** + * Returns an Iterator with paragraphs and tables, + * in the order that they occur in the text. + */ + public List getBodyElements(); + + /** + * Returns the paragraph(s) that holds + * the text of the header or footer. + */ + public List getParagraphs(); + + /** + * Return the table(s) that holds the text + * of the IBodyPart, for complex cases + * where a paragraph isn't used. + */ + public List getTables(); + + /** + * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer + * the method will return this paragraph + * if there is no corresponding {@link XWPFParagraph} the method will return null + * + * @param p is instance of CTP and is searching for an XWPFParagraph + * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer + * XWPFParagraph with the correspondig CTP p + */ + public XWPFParagraph getParagraph(CTP p); + + /** + * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header + * the method will return this table + * if there is no corresponding {@link XWPFTable} the method will return null + * + * @param ctTable + */ + public XWPFTable getTable(CTTbl ctTable); /** * Returns the paragraph that of position pos @@ -94,32 +98,36 @@ public interface IBody { /** * Returns the table at position pos */ - public XWPFTable getTableArray(int pos); - - /** - *inserts a new paragraph at position of the cursor - * @param cursor - */ - public XWPFParagraph insertNewParagraph(XmlCursor cursor); - - /** - * inserts a new Table at the cursor position. - * @param cursor - */ - public XWPFTable insertNewTbl(XmlCursor cursor); - - /** - * inserts a new Table at position pos - * @param pos - * @param table - */ + public XWPFTable getTableArray(int pos); + + /** + * inserts a new paragraph at position of the cursor + * + * @param cursor + */ + public XWPFParagraph insertNewParagraph(XmlCursor cursor); + + /** + * inserts a new Table at the cursor position. + * + * @param cursor + */ + public XWPFTable insertNewTbl(XmlCursor cursor); + + /** + * inserts a new Table at position pos + * + * @param pos + * @param table + */ void insertTable(int pos, XWPFTable table); - - /** - * returns the TableCell to which the Table belongs - * @param cell - */ - public XWPFTableCell getTableCell(CTTc cell); + + /** + * returns the TableCell to which the Table belongs + * + * @param cell + */ + public XWPFTableCell getTableCell(CTTc cell); /** * Return XWPFDocument diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java index 70009be3b5..312ea493fc 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java @@ -18,15 +18,18 @@ package org.apache.poi.xwpf.usermodel; import org.apache.poi.POIXMLDocumentPart; - -/** - * 9 Jan 2010 - * @author Philipp Epp - * - */ -public interface IBodyElement{ - IBody getBody(); - POIXMLDocumentPart getPart(); - BodyType getPartType(); - BodyElementType getElementType(); -} + +/** + * 9 Jan 2010 + * + * @author Philipp Epp + */ +public interface IBodyElement { + IBody getBody(); + + POIXMLDocumentPart getPart(); + + BodyType getPartType(); + + BodyElementType getElementType(); +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java index cf32924b8e..0ac12c7937 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java @@ -15,13 +15,13 @@ limitations under the License. ==================================================================== */ package org.apache.poi.xwpf.usermodel; - -/** - * Interface for anything that can be at a table cell level: - * {@link XWPFTableCell}, {@link XWPFSDTCell} - *

    - * Schematically something like this: - * <tr><tc/><tc/><sdt><tc/></sdt></tr> - */ -public interface ICell { -} + +/** + * Interface for anything that can be at a table cell level: + * {@link XWPFTableCell}, {@link XWPFSDTCell} + *

    + * Schematically something like this: + * <tr><tc/><tc/><sdt><tc/></sdt></tr> + */ +public interface ICell { +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java index 3ea4acabee..fea7856d1c 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java @@ -22,10 +22,11 @@ import org.apache.poi.wp.usermodel.Paragraph; /** * Simple interface describing both {@link XWPFParagraph} * and {@link XWPFSDT} - * + *

    * TODO Should this be based on / extend {@link Paragraph}? */ public interface IRunBody { - public XWPFDocument getDocument(); - public POIXMLDocumentPart getPart(); + public XWPFDocument getDocument(); + + public POIXMLDocumentPart getPart(); } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java index f11b46a135..e8d1b83e71 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java @@ -20,11 +20,10 @@ import org.apache.poi.wp.usermodel.CharacterRun; /** * Common interface for things that can occur - * where a run (text with common stylings) can, - * eg {@link XWPFRun} or {@link XWPFSDT}. + * where a run (text with common stylings) can, + * eg {@link XWPFRun} or {@link XWPFSDT}. * TODO More methods to follow shortly! - * + *

    * TODO Make this based on {@link CharacterRun} */ -public interface IRunElement { -} \ No newline at end of file +public interface IRunElement {} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java index 25599d7e61..5493ff3bdb 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java @@ -15,21 +15,20 @@ limitations under the License. ==================================================================== */ package org.apache.poi.xwpf.usermodel; - - -/** - * Experimental interface to offer rudimentary read-only processing of - * of the contentblock of an SDT/ContentControl. - * - * - * - * WARNING - APIs expected to change rapidly - * - */ -public interface ISDTContent { - - public String getText(); - - public String toString(); - + + +/** + * Experimental interface to offer rudimentary read-only processing of + * of the contentblock of an SDT/ContentControl. + *

    + *

    + *

    + * WARNING - APIs expected to change rapidly + */ +public interface ISDTContent { + + public String getText(); + + public String toString(); + } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java index 40776e218a..66922b8376 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java @@ -18,8 +18,8 @@ package org.apache.poi.xwpf.usermodel; /** * Interface for anything that can be within an SDT: - * {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph}, - * {@link XWPFSDT} etc + * {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph}, + * {@link XWPFSDT} etc */ public interface ISDTContents { } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java index 166d8e7012..b46c53206c 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java @@ -19,13 +19,13 @@ package org.apache.poi.xwpf.usermodel; import java.util.HashMap; import java.util.Map; -/** - * Specifies the logic which shall be used to calculate the line spacing of the - * parent object when it is displayed in the document. - * - * @author Gisella Bronzetti - */ -public enum LineSpacingRule { +/** + * Specifies the logic which shall be used to calculate the line spacing of the + * parent object when it is displayed in the document. + * + * @author Gisella Bronzetti + */ +public enum LineSpacingRule { /** * Specifies that the line spacing of the parent object shall be @@ -45,31 +45,32 @@ public enum LineSpacingRule { /** * Specifies that the height of the line shall be at least the value * specified, but may be expanded to fit its content as needed. - */ - AT_LEAST(3); - - - private final int value; - - private LineSpacingRule(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static Map imap = new HashMap(); - static { - for (LineSpacingRule p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static LineSpacingRule valueOf(int type) { - LineSpacingRule lineType = imap.get(new Integer(type)); - if (lineType == null) - throw new IllegalArgumentException("Unknown line type: " + type); - return lineType; - } -} + */ + AT_LEAST(3); + + + private static Map imap = new HashMap(); + + static { + for (LineSpacingRule p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private LineSpacingRule(int val) { + value = val; + } + + public static LineSpacingRule valueOf(int type) { + LineSpacingRule lineType = imap.get(new Integer(type)); + if (lineType == null) + throw new IllegalArgumentException("Unknown line type: " + type); + return lineType; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java index 0585ecb4c4..226d4095ae 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java @@ -37,30 +37,31 @@ public enum ParagraphAlignment { DISTRIBUTE(6), NUM_TAB(7), HIGH_KASHIDA(8), - LOW_KASHIDA(9), - THAI_DISTRIBUTE(10); - - private final int value; - - private ParagraphAlignment(int val){ - value = val; - } - - public int getValue(){ - return value; - } - - private static Map imap = new HashMap(); - static{ - for (ParagraphAlignment p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static ParagraphAlignment valueOf(int type){ - ParagraphAlignment err = imap.get(new Integer(type)); - if(err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type); - return err; - } - -} + LOW_KASHIDA(9), + THAI_DISTRIBUTE(10); + + private static Map imap = new HashMap(); + + static { + for (ParagraphAlignment p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private ParagraphAlignment(int val) { + value = val; + } + + public static ParagraphAlignment valueOf(int type) { + ParagraphAlignment err = imap.get(new Integer(type)); + if (err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type); + return err; + } + + public int getValue() { + return value; + } + +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java index 5e387e7f8c..4eebe412e1 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java @@ -17,49 +17,47 @@ package org.apache.poi.xwpf.usermodel; - -/** - * postion of a character in a paragrapho -* 1st RunPositon -* 2nd TextPosition -* 3rd CharacterPosition -* -* -*/ -public class PositionInParagraph { - private int posRun = 0, posText = 0, posChar = 0; - - public PositionInParagraph(){ - } - - public PositionInParagraph(int posRun, int posText, int posChar){ - this.posRun=posRun; - this.posChar=posChar; - this.posText= posText; - } - - public int getRun() { - return posRun; - } - - public void setRun(int beginRun) { - this.posRun = beginRun; - } - - public int getText() { - return posText; - } - - public void setText(int beginText) { - this.posText = beginText; - } - - public int getChar() { - return posChar; - } - - public void setChar(int beginChar) { - this.posChar = beginChar; - } - -} + +/** + * postion of a character in a paragrapho + * 1st RunPositon + * 2nd TextPosition + * 3rd CharacterPosition + */ +public class PositionInParagraph { + private int posRun = 0, posText = 0, posChar = 0; + + public PositionInParagraph() { + } + + public PositionInParagraph(int posRun, int posText, int posChar) { + this.posRun = posRun; + this.posChar = posChar; + this.posText = posText; + } + + public int getRun() { + return posRun; + } + + public void setRun(int beginRun) { + this.posRun = beginRun; + } + + public int getText() { + return posText; + } + + public void setText(int beginText) { + this.posText = beginText; + } + + public int getChar() { + return posChar; + } + + public void setChar(int beginChar) { + this.posChar = beginChar; + } + +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java index f144e624d8..b7dc6ee2f5 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java @@ -38,85 +38,85 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabTlc; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTheme; - -public class TOC { - - CTSdtBlock block; - - public TOC() { - this(CTSdtBlock.Factory.newInstance()); - } - - public TOC(CTSdtBlock block) { - this.block = block; - CTSdtPr sdtPr = block.addNewSdtPr(); - CTDecimalNumber id = sdtPr.addNewId(); - id.setVal(new BigInteger("4844945")); - sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents"); - CTSdtEndPr sdtEndPr = block.addNewSdtEndPr(); - CTRPr rPr = sdtEndPr.addNewRPr(); - CTFonts fonts = rPr.addNewRFonts(); - fonts.setAsciiTheme(STTheme.MINOR_H_ANSI); - fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI); - fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI); - fonts.setCstheme(STTheme.MINOR_BIDI); - rPr.addNewB().setVal(STOnOff.OFF); - rPr.addNewBCs().setVal(STOnOff.OFF); - rPr.addNewColor().setVal("auto"); - rPr.addNewSz().setVal(new BigInteger("24")); - rPr.addNewSzCs().setVal(new BigInteger("24")); - CTSdtContentBlock content = block.addNewSdtContent(); - CTP p = content.addNewP(); - p.setRsidR("00EF7E24".getBytes()); - p.setRsidRDefault("00EF7E24".getBytes()); - p.addNewPPr().addNewPStyle().setVal("TOCHeading"); - p.addNewR().addNewT().setStringValue("Table of Contents"); - } - - @Internal - public CTSdtBlock getBlock() { - return this.block; - } - - public void addRow(int level, String title, int page, String bookmarkRef) { - CTSdtContentBlock contentBlock = this.block.getSdtContent(); - CTP p = contentBlock.addNewP(); - p.setRsidR("00EF7E24".getBytes()); - p.setRsidRDefault("00EF7E24".getBytes()); - CTPPr pPr = p.addNewPPr(); - pPr.addNewPStyle().setVal("TOC" + level); - CTTabs tabs = pPr.addNewTabs(); - CTTabStop tab = tabs.addNewTab(); - tab.setVal(STTabJc.RIGHT); - tab.setLeader(STTabTlc.DOT); - tab.setPos(new BigInteger("8290")); - pPr.addNewRPr().addNewNoProof(); - CTR run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewT().setStringValue(title); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewTab(); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewFldChar().setFldCharType(STFldCharType.BEGIN); - // pageref run - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - CTText text = run.addNewInstrText(); - text.setSpace(Space.PRESERVE); - // bookmark reference - text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h "); - p.addNewR().addNewRPr().addNewNoProof(); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE); - // page number run - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewT().setStringValue(Integer.valueOf(page).toString()); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewFldChar().setFldCharType(STFldCharType.END); - } -} + +public class TOC { + + CTSdtBlock block; + + public TOC() { + this(CTSdtBlock.Factory.newInstance()); + } + + public TOC(CTSdtBlock block) { + this.block = block; + CTSdtPr sdtPr = block.addNewSdtPr(); + CTDecimalNumber id = sdtPr.addNewId(); + id.setVal(new BigInteger("4844945")); + sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents"); + CTSdtEndPr sdtEndPr = block.addNewSdtEndPr(); + CTRPr rPr = sdtEndPr.addNewRPr(); + CTFonts fonts = rPr.addNewRFonts(); + fonts.setAsciiTheme(STTheme.MINOR_H_ANSI); + fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI); + fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI); + fonts.setCstheme(STTheme.MINOR_BIDI); + rPr.addNewB().setVal(STOnOff.OFF); + rPr.addNewBCs().setVal(STOnOff.OFF); + rPr.addNewColor().setVal("auto"); + rPr.addNewSz().setVal(new BigInteger("24")); + rPr.addNewSzCs().setVal(new BigInteger("24")); + CTSdtContentBlock content = block.addNewSdtContent(); + CTP p = content.addNewP(); + p.setRsidR("00EF7E24".getBytes()); + p.setRsidRDefault("00EF7E24".getBytes()); + p.addNewPPr().addNewPStyle().setVal("TOCHeading"); + p.addNewR().addNewT().setStringValue("Table of Contents"); + } + + @Internal + public CTSdtBlock getBlock() { + return this.block; + } + + public void addRow(int level, String title, int page, String bookmarkRef) { + CTSdtContentBlock contentBlock = this.block.getSdtContent(); + CTP p = contentBlock.addNewP(); + p.setRsidR("00EF7E24".getBytes()); + p.setRsidRDefault("00EF7E24".getBytes()); + CTPPr pPr = p.addNewPPr(); + pPr.addNewPStyle().setVal("TOC" + level); + CTTabs tabs = pPr.addNewTabs(); + CTTabStop tab = tabs.addNewTab(); + tab.setVal(STTabJc.RIGHT); + tab.setLeader(STTabTlc.DOT); + tab.setPos(new BigInteger("8290")); + pPr.addNewRPr().addNewNoProof(); + CTR run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + run.addNewT().setStringValue(title); + run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + run.addNewTab(); + run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + run.addNewFldChar().setFldCharType(STFldCharType.BEGIN); + // pageref run + run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + CTText text = run.addNewInstrText(); + text.setSpace(Space.PRESERVE); + // bookmark reference + text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h "); + p.addNewR().addNewRPr().addNewNoProof(); + run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE); + // page number run + run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + run.addNewT().setStringValue(Integer.valueOf(page).toString()); + run = p.addNewR(); + run.addNewRPr().addNewNoProof(); + run.addNewFldChar().setFldCharType(STFldCharType.END); + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java index b2a8c13c78..7c1187df60 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java @@ -17,25 +17,25 @@ package org.apache.poi.xwpf.usermodel; import java.util.HashMap; -import java.util.Map; - -/** - * Specifies all types of vertical alignment which are available to be applied to of all text - * on each line displayed within a paragraph. - * - * @author Gisella Bronzetti - */ -public enum TextAlignment { - /** - * Specifies that all text in the parent object shall be - * aligned to the top of each character when displayed - */ - TOP(1), - /** - * Specifies that all text in the parent object shall be - * aligned to the center of each character when displayed. - */ - CENTER(2), +import java.util.Map; + +/** + * Specifies all types of vertical alignment which are available to be applied to of all text + * on each line displayed within a paragraph. + * + * @author Gisella Bronzetti + */ +public enum TextAlignment { + /** + * Specifies that all text in the parent object shall be + * aligned to the top of each character when displayed + */ + TOP(1), + /** + * Specifies that all text in the parent object shall be + * aligned to the center of each character when displayed. + */ + CENTER(2), /** * Specifies that all text in the parent object shall be * aligned to the baseline of each character when displayed. @@ -44,34 +44,35 @@ public enum TextAlignment { /** * Specifies that all text in the parent object shall be * aligned to the bottom of each character when displayed. - */ - BOTTOM(4), - /** - * Specifies that all text in the parent object shall be - * aligned automatically when displayed. - */ - AUTO(5); - - private final int value; - - private TextAlignment(int val){ - value = val; - } - - public int getValue(){ - return value; - } - - private static Map imap = new HashMap(); - static{ - for (TextAlignment p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static TextAlignment valueOf(int type){ - TextAlignment align = imap.get(new Integer(type)); - if(align == null) throw new IllegalArgumentException("Unknown text alignment: " + type); - return align; - } -} + */ + BOTTOM(4), + /** + * Specifies that all text in the parent object shall be + * aligned automatically when displayed. + */ + AUTO(5); + + private static Map imap = new HashMap(); + + static { + for (TextAlignment p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private TextAlignment(int val) { + value = val; + } + + public static TextAlignment valueOf(int type) { + TextAlignment align = imap.get(new Integer(type)); + if (align == null) throw new IllegalArgumentException("Unknown text alignment: " + type); + return align; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java index 23aa158081..44477daf87 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java @@ -16,83 +16,84 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; - -/** - * saves the begin and end position of a text in a Paragraph -*/ -public class TextSegement { - private PositionInParagraph beginPos; - private PositionInParagraph endPos; - - public TextSegement(){ - this.beginPos = new PositionInParagraph(); - this. endPos = new PositionInParagraph(); - } - - public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar){ - PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar); - PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar); - this.beginPos = beginPos; - this.endPos = endPos; - } - - public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos){ - this.beginPos = beginPos; - this.endPos = endPos; - } - - public PositionInParagraph getBeginPos(){ - return beginPos; - } - - public PositionInParagraph getEndPos(){ - return endPos; - } - - public int getBeginRun(){ - return beginPos.getRun(); - } - - public void setBeginRun(int beginRun){ - beginPos.setRun(beginRun); - } - - public int getBeginText(){ - return beginPos.getText(); - } - - public void setBeginText(int beginText){ - beginPos.setText(beginText); - } - - public int getBeginChar(){ - return beginPos.getChar(); - } - - public void setBeginChar(int beginChar){ - beginPos.setChar(beginChar); - } - public int getEndRun(){ - return endPos.getRun(); - } - - public void setEndRun(int endRun){ - endPos.setRun(endRun); - } - - public int getEndText(){ - return endPos.getText(); - } - - public void setEndText(int endText){ - endPos.setText(endText); - } - - public int getEndChar(){ - return endPos.getChar(); - } - - public void setEndChar(int endChar){ - endPos.setChar(endChar); - } -} + +/** + * saves the begin and end position of a text in a Paragraph + */ +public class TextSegement { + private PositionInParagraph beginPos; + private PositionInParagraph endPos; + + public TextSegement() { + this.beginPos = new PositionInParagraph(); + this.endPos = new PositionInParagraph(); + } + + public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar) { + PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar); + PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar); + this.beginPos = beginPos; + this.endPos = endPos; + } + + public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos) { + this.beginPos = beginPos; + this.endPos = endPos; + } + + public PositionInParagraph getBeginPos() { + return beginPos; + } + + public PositionInParagraph getEndPos() { + return endPos; + } + + public int getBeginRun() { + return beginPos.getRun(); + } + + public void setBeginRun(int beginRun) { + beginPos.setRun(beginRun); + } + + public int getBeginText() { + return beginPos.getText(); + } + + public void setBeginText(int beginText) { + beginPos.setText(beginText); + } + + public int getBeginChar() { + return beginPos.getChar(); + } + + public void setBeginChar(int beginChar) { + beginPos.setChar(beginChar); + } + + public int getEndRun() { + return endPos.getRun(); + } + + public void setEndRun(int endRun) { + endPos.setRun(endRun); + } + + public int getEndText() { + return endPos.getText(); + } + + public void setEndText(int endText) { + endPos.setText(endText); + } + + public int getEndChar() { + return endPos.getChar(); + } + + public void setEndChar(int endChar) { + endPos.setChar(endChar); + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java index 578dec3325..9272ac0600 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java @@ -19,13 +19,13 @@ package org.apache.poi.xwpf.usermodel; import java.util.HashMap; import java.util.Map; -/** - * Specifies the types of patterns which may be used to create the underline - * applied beneath the text in a run. - * - * @author Gisella Bronzetti - */ -public enum UnderlinePatterns { +/** + * Specifies the types of patterns which may be used to create the underline + * applied beneath the text in a run. + * + * @author Gisella Bronzetti + */ +public enum UnderlinePatterns { /** * Specifies an underline consisting of a single line beneath all characters @@ -132,31 +132,32 @@ public enum UnderlinePatterns { /** * Specifies no underline beneath this run. - */ - NONE(18); - - private final int value; - - private UnderlinePatterns(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static Map imap = new HashMap(); - static { - for (UnderlinePatterns p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static UnderlinePatterns valueOf(int type) { - UnderlinePatterns align = imap.get(new Integer(type)); - if (align == null) - throw new IllegalArgumentException("Unknown underline pattern: " - + type); - return align; - } -} + */ + NONE(18); + + private static Map imap = new HashMap(); + + static { + for (UnderlinePatterns p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private UnderlinePatterns(int val) { + value = val; + } + + public static UnderlinePatterns valueOf(int type) { + UnderlinePatterns align = imap.get(new Integer(type)); + if (align == null) + throw new IllegalArgumentException("Unknown underline pattern: " + + type); + return align; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java index 84ff628587..4114c11009 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java @@ -21,13 +21,13 @@ import java.util.Map; /** * Specifies possible values for the alignment of the contents of this run in - * relation to the default appearance of the run's text. This allows the text to - * be repositioned as subscript or superscript without altering the font size of - * the run properties. - * - * @author Gisella Bronzetti - */ -public enum VerticalAlign { + * relation to the default appearance of the run's text. This allows the text to + * be repositioned as subscript or superscript without altering the font size of + * the run properties. + * + * @author Gisella Bronzetti + */ +public enum VerticalAlign { /** * Specifies that the text in the parent run shall be located at the @@ -44,31 +44,32 @@ public enum VerticalAlign { * Specifies that this text should be superscript. This setting shall raise * the text in this run above the baseline and change it to a smaller size, * if a smaller size is available. - */ - SUBSCRIPT(3); - - private final int value; - - private VerticalAlign(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static Map imap = new HashMap(); - static { - for (VerticalAlign p : values()) { - imap.put(new Integer(p.getValue()), p); - } - } - - public static VerticalAlign valueOf(int type) { - VerticalAlign align = imap.get(new Integer(type)); - if (align == null) - throw new IllegalArgumentException("Unknown vertical alignment: " - + type); - return align; - } -} + */ + SUBSCRIPT(3); + + private static Map imap = new HashMap(); + + static { + for (VerticalAlign p : values()) { + imap.put(new Integer(p.getValue()), p); + } + } + + private final int value; + + private VerticalAlign(int val) { + value = val; + } + + public static VerticalAlign valueOf(int type) { + VerticalAlign align = imap.get(new Integer(type)); + if (align == null) + throw new IllegalArgumentException("Unknown vertical alignment: " + + type); + return align; + } + + public int getValue() { + return value; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java index 12d2d3a02c..8d4886b909 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java @@ -18,42 +18,43 @@ package org.apache.poi.xwpf.usermodel; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; - -/** - * @author Philipp Epp - * - */ -public class XWPFAbstractNum { - private CTAbstractNum ctAbstractNum; - protected XWPFNumbering numbering; - - protected XWPFAbstractNum() { - this.ctAbstractNum = null; - this.numbering = null; - - } - public XWPFAbstractNum(CTAbstractNum abstractNum){ - this.ctAbstractNum = abstractNum; - } - - public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering){ - this.ctAbstractNum = ctAbstractNum; - this.numbering = numbering; - } - public CTAbstractNum getAbstractNum(){ - return ctAbstractNum; - } - - public XWPFNumbering getNumbering(){ - return numbering; - } - - public CTAbstractNum getCTAbstractNum(){ - return ctAbstractNum; - } - - public void setNumbering(XWPFNumbering numbering){ - this.numbering = numbering; - } - -} + +/** + * @author Philipp Epp + */ +public class XWPFAbstractNum { + protected XWPFNumbering numbering; + private CTAbstractNum ctAbstractNum; + + protected XWPFAbstractNum() { + this.ctAbstractNum = null; + this.numbering = null; + + } + + public XWPFAbstractNum(CTAbstractNum abstractNum) { + this.ctAbstractNum = abstractNum; + } + + public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering) { + this.ctAbstractNum = ctAbstractNum; + this.numbering = numbering; + } + + public CTAbstractNum getAbstractNum() { + return ctAbstractNum; + } + + public XWPFNumbering getNumbering() { + return numbering; + } + + public void setNumbering(XWPFNumbering numbering) { + this.numbering = numbering; + } + + public CTAbstractNum getCTAbstractNum() { + return ctAbstractNum; + } + +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java index 84ebc36bb1..627971b344 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java @@ -21,42 +21,35 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; /** * Sketch of XWPF comment class - * -* @author Yury Batrakov (batrakov at gmail.com) - * + * + * @author Yury Batrakov (batrakov at gmail.com) */ -public class XWPFComment -{ +public class XWPFComment { protected String id; protected String author; protected StringBuffer text; - + @SuppressWarnings("deprecation") - public XWPFComment(CTComment comment, XWPFDocument document) - { + public XWPFComment(CTComment comment, XWPFDocument document) { text = new StringBuffer(); id = comment.getId().toString(); author = comment.getAuthor(); - - for(CTP ctp : comment.getPArray()) - { + + for (CTP ctp : comment.getPArray()) { XWPFParagraph p = new XWPFParagraph(ctp, document); text.append(p.getText()); } } - - public String getId() - { + + public String getId() { return id; } - - public String getAuthor() - { + + public String getAuthor() { return author; } - - public String getText() - { + + public String getText() { return text.toString(); } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java index 9d16e26dab..a430c87e52 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java @@ -22,21 +22,21 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; /** * Default Paragraph style, from which other styles will override * TODO Share logic with {@link XWPFParagraph} which also uses CTPPr - */ -public class XWPFDefaultParagraphStyle { - private CTPPr ppr; - - public XWPFDefaultParagraphStyle(CTPPr ppr) { - this.ppr = ppr; - } - - protected CTPPr getPPr() { - return ppr; - } - - public int getSpacingAfter() { - if (ppr.isSetSpacing()) - return ppr.getSpacing().getAfter().intValue(); + */ +public class XWPFDefaultParagraphStyle { + private CTPPr ppr; + + public XWPFDefaultParagraphStyle(CTPPr ppr) { + this.ppr = ppr; + } + + protected CTPPr getPPr() { + return ppr; + } + + public int getSpacingAfter() { + if (ppr.isSetSpacing()) + return ppr.getSpacing().getAfter().intValue(); return -1; } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java index 210a951638..459335de6d 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java @@ -22,21 +22,21 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; /** * Default Character Run style, from which other styles will override * TODO Share logic with {@link XWPFRun} which also uses CTRPr - */ -public class XWPFDefaultRunStyle { - private CTRPr rpr; - - public XWPFDefaultRunStyle(CTRPr rpr) { - this.rpr = rpr; - } - - protected CTRPr getRPr() { - return rpr; - } - - public int getFontSize() { - if (rpr.isSetSz()) - return rpr.getSz().getVal().intValue() / 2; + */ +public class XWPFDefaultRunStyle { + private CTRPr rpr; + + public XWPFDefaultRunStyle(CTRPr rpr) { + this.rpr = rpr; + } + + protected CTRPr getRPr() { + return rpr; + } + + public int getFontSize() { + if (rpr.isSetSz()) + return rpr.getSz().getVal().intValue() / 2; return -1; } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java index 6a28db2a87..9eabdebc8b 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java @@ -76,23 +76,17 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; /** *

    High(ish) level class for working with .docx files.

    - * + *

    *

    This class tries to hide some of the complexity - * of the underlying file format, but as it's not a - * mature and stable API yet, certain parts of the - * XML structure come through. You'll therefore almost - * certainly need to refer to the OOXML specifications - * from - * http://www.ecma-international.org/publications/standards/Ecma-376.htm - * at some point in your use.

    + * of the underlying file format, but as it's not a + * mature and stable API yet, certain parts of the + * XML structure come through. You'll therefore almost + * certainly need to refer to the OOXML specifications + * from + * http://www.ecma-international.org/publications/standards/Ecma-376.htm + * at some point in your use.

    */ public class XWPFDocument extends POIXMLDocument implements Document, IBody { - private CTDocument1 ctDocument; - private XWPFSettings settings; - /** - * Keeps track on all id-values used in this document and included parts, like headers, footers, etc. - */ - private IdentifierManager drawingIdManager = new IdentifierManager(0L,4294967295L); protected List footers = new ArrayList(); protected List headers = new ArrayList(); protected List comments = new ArrayList(); @@ -107,8 +101,15 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { protected XWPFNumbering numbering; protected XWPFStyles styles; protected XWPFFootnotes footnotes; - - /** Handles the joy of different headers/footers for different pages */ + private CTDocument1 ctDocument; + private XWPFSettings settings; + /** + * Keeps track on all id-values used in this document and included parts, like headers, footers, etc. + */ + private IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L); + /** + * Handles the joy of different headers/footers for different pages + */ private XWPFHeaderFooterPolicy headerFooterPolicy; public XWPFDocument(OPCPackage pkg) throws IOException { @@ -125,11 +126,32 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { load(XWPFFactory.getInstance()); } - public XWPFDocument(){ + public XWPFDocument() { super(newPackage()); onDocumentCreate(); } + /** + * Create a new WordProcessingML package and setup the default minimal content + */ + protected static OPCPackage newPackage() { + try { + OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream()); + // Main part + PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName()); + // Create main part relationship + pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT); + // Create main document part + pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType()); + + pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR); + + return pkg; + } catch (Exception e) { + throw new POIXMLException(e); + } + } + @Override protected void onDocumentRead() throws IOException { try { @@ -152,11 +174,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { XWPFTable t = new XWPFTable((CTTbl) o, this); bodyElements.add(t); tables.add(t); - } else if (o instanceof CTSdtBlock){ - XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); - bodyElements.add(c); - contentControls.add(c); - } + } else if (o instanceof CTSdtBlock) { + XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); + bodyElements.add(c); + contentControls.add(c); + } } cursor.dispose(); @@ -205,7 +227,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { Method onDocumentRead = gp.getClass().getDeclaredMethod("onDocumentRead"); onDocumentRead.setAccessible(true); onDocumentRead.invoke(gp); - } catch(Exception e) { + } catch (Exception e) { throw new POIXMLException(e); } } @@ -217,59 +239,38 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { } } - private void initHyperlinks(){ + private void initHyperlinks() { // Get the hyperlinks // TODO: make me optional/separated in private function try { Iterator relIter = getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator(); - while(relIter.hasNext()) { + while (relIter.hasNext()) { PackageRelationship rel = relIter.next(); hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString())); } - } catch (InvalidFormatException e){ + } catch (InvalidFormatException e) { throw new POIXMLException(e); } } @SuppressWarnings("deprecation") private void initFootnotes() throws XmlException, IOException { - for(POIXMLDocumentPart p : getRelations()){ + for (POIXMLDocumentPart p : getRelations()) { String relation = p.getPackageRelationship().getRelationshipType(); if (relation.equals(XWPFRelation.FOOTNOTE.getRelation())) { - this.footnotes = (XWPFFootnotes)p; + this.footnotes = (XWPFFootnotes) p; this.footnotes.onDocumentRead(); - } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())){ + } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())) { EndnotesDocument endnotesDocument = EndnotesDocument.Factory.parse(p.getPackagePart().getInputStream()); - for(CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) { + for (CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) { endnotes.put(ctFtnEdn.getId().intValue(), new XWPFFootnote(this, ctFtnEdn)); } } } } - /** - * Create a new WordProcessingML package and setup the default minimal content - */ - protected static OPCPackage newPackage() { - try { - OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream()); - // Main part - PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName()); - // Create main part relationship - pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT); - // Create main document part - pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType()); - - pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR); - - return pkg; - } catch (Exception e){ - throw new POIXMLException(e); - } - } - /** * Create a new CTWorkbook with all values set to default */ @@ -278,7 +279,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { ctDocument = CTDocument1.Factory.newInstance(); ctDocument.addNewBody(); - settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS,XWPFFactory.getInstance()); + settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS, XWPFFactory.getInstance()); POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties(); expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR); @@ -298,6 +299,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * returns an Iterator with paragraphs and tables + * * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() */ @Override @@ -313,7 +315,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphs() */ @Override - public List getParagraphs(){ + public List getParagraphs() { return Collections.unmodifiableList(paragraphs); } @@ -321,7 +323,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * @see org.apache.poi.xwpf.usermodel.IBody#getTables() */ @Override - public List getTables(){ + public List getTables() { return Collections.unmodifiableList(tables); } @@ -330,37 +332,35 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { */ @Override public XWPFTable getTableArray(int pos) { - if (pos > 0 && pos < tables.size()){ + if (pos > 0 && pos < tables.size()) { return tables.get(pos); } return null; } /** - * - * @return the list of footers + * @return the list of footers */ - public List getFooterList(){ + public List getFooterList() { return Collections.unmodifiableList(footers); } - public XWPFFooter getFooterArray(int pos){ + public XWPFFooter getFooterArray(int pos) { return footers.get(pos); } /** - * - * @return the list of headers + * @return the list of headers */ - public List getHeaderList(){ + public List getHeaderList() { return Collections.unmodifiableList(headers); } - public XWPFHeader getHeaderArray(int pos){ + public XWPFHeader getHeaderArray(int pos) { return headers.get(pos); } - public String getTblStyle(XWPFTable table){ + public String getTblStyle(XWPFTable table) { return table.getStyleID(); } @@ -374,17 +374,17 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { } public XWPFFootnote getFootnoteByID(int id) { - if(footnotes == null) return null; + if (footnotes == null) return null; return footnotes.getFootnoteById(id); } public XWPFFootnote getEndnoteByID(int id) { - if(endnotes == null) return null; + if (endnotes == null) return null; return endnotes.get(id); } public List getFootnotes() { - if(footnotes == null) { + if (footnotes == null) { return Collections.emptyList(); } return footnotes.getFootnotesList(); @@ -409,7 +409,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Get the document part that's defined as the - * given relationship of the core document. + * given relationship of the core document. */ public PackagePart getPartById(String id) { try { @@ -422,7 +422,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Returns the policy on headers and footers, which - * also provides a way to get at them. + * also provides a way to get at them. */ public XWPFHeaderFooterPolicy getHeaderFooterPolicy() { return headerFooterPolicy; @@ -436,10 +436,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { PackagePart[] parts; try { parts = getRelatedByType(XWPFRelation.STYLES.getRelation()); - } catch(InvalidFormatException e) { + } catch (InvalidFormatException e) { throw new IllegalStateException(e); } - if(parts.length != 1) { + if (parts.length != 1) { throw new IllegalStateException("Expecting one Styles document part, but found " + parts.length); } @@ -471,57 +471,56 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * Finds that for example the 2nd entry in the body list is the 1st paragraph */ private int getBodyElementSpecificPos(int pos, List list) { - // If there's nothing to find, skip it - if(list.size() == 0) { - return -1; - } - - if(pos >= 0 && pos < bodyElements.size()) { - // Ensure the type is correct - IBodyElement needle = bodyElements.get(pos); - if(needle.getElementType() != list.get(0).getElementType()) { - // Wrong type - return -1; - } - - // Work back until we find it - int startPos = Math.min(pos, list.size()-1); - for(int i=startPos; i>=0; i--) { - if(list.get(i) == needle) { - return i; - } - } - } - - // Couldn't be found - return -1; - } - + // If there's nothing to find, skip it + if (list.size() == 0) { + return -1; + } + + if (pos >= 0 && pos < bodyElements.size()) { + // Ensure the type is correct + IBodyElement needle = bodyElements.get(pos); + if (needle.getElementType() != list.get(0).getElementType()) { + // Wrong type + return -1; + } + + // Work back until we find it + int startPos = Math.min(pos, list.size() - 1); + for (int i = startPos; i >= 0; i--) { + if (list.get(i) == needle) { + return i; + } + } + } + + // Couldn't be found + return -1; + } + /** * Look up the paragraph at the specified position in the body elements list * and return this paragraphs position in the paragraphs list - * - * @param pos - * The position of the relevant paragraph in the body elements + * + * @param pos The position of the relevant paragraph in the body elements * list * @return the position of the paragraph in the paragraphs list, if there is - * a paragraph at the position in the bodyelements list. Else it - * will return -1 - * + * a paragraph at the position in the bodyelements list. Else it + * will return -1 */ public int getParagraphPos(int pos) { - return getBodyElementSpecificPos(pos, paragraphs); + return getBodyElementSpecificPos(pos, paragraphs); } /** - * get with the position of a table in the bodyelement array list + * get with the position of a table in the bodyelement array list * the position of this table in the table array list + * * @param pos position of the table in the bodyelement array list * @return if there is a table at the position in the bodyelement array list, - * else it will return null. + * else it will return null. */ public int getTablePos(int pos) { - return getBodyElementSpecificPos(pos, tables); + return getBodyElementSpecificPos(pos, tables); } /** @@ -530,10 +529,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * of the documents body. When this method is done, the cursor passed as * parameter points to the {@link org.apache.xmlbeans.XmlCursor.TokenType#END} * of the newly inserted paragraph. - * + * * @param cursor * @return the {@link XWPFParagraph} object representing the newly inserted - * CTP object + * CTP object */ @Override public XWPFParagraph insertNewParagraph(XmlCursor cursor) { @@ -635,8 +634,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { cursor.toCursor(tableCursor); cursor.toEndToken(); return newT; - } - finally { + } finally { tableCursor.dispose(); } } @@ -645,6 +643,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * verifies that cursor is on the right position + * * @param cursor */ private boolean isCursorInBody(XmlCursor cursor) { @@ -659,11 +658,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { private int getPosOfBodyElement(IBodyElement needle) { BodyElementType type = needle.getElementType(); - IBodyElement current; - for(int i=0; i relations = getRelations(); int i = 1; - for (Iterator it = relations.iterator(); it.hasNext() ; ) { - POIXMLDocumentPart item = it.next(); - if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) { - i++; - } + for (Iterator it = relations.iterator(); it.hasNext(); ) { + POIXMLDocumentPart item = it.next(); + if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) { + i++; + } } return i; } /** * Appends a new paragraph to this document + * * @return a new paragraph */ public XWPFParagraph createParagraph() { @@ -746,16 +749,17 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Creates an empty numbering if one does not already exist and sets the numbering member + * * @return numbering */ public XWPFNumbering createNumbering() { - if(numbering == null) { + if (numbering == null) { NumberingDocument numberingDoc = NumberingDocument.Factory.newInstance(); XWPFRelation relation = XWPFRelation.NUMBERING; int i = getRelationIndex(relation); - XWPFNumbering wrapper = (XWPFNumbering)createRelationship(relation, XWPFFactory.getInstance(), i); + XWPFNumbering wrapper = (XWPFNumbering) createRelationship(relation, XWPFFactory.getInstance(), i); wrapper.setNumbering(numberingDoc.addNewNumbering()); numbering = wrapper; } @@ -765,61 +769,64 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Creates an empty styles for the document if one does not already exist + * * @return styles */ public XWPFStyles createStyles() { - if(styles == null) { - StylesDocument stylesDoc = StylesDocument.Factory.newInstance(); + if (styles == null) { + StylesDocument stylesDoc = StylesDocument.Factory.newInstance(); - XWPFRelation relation = XWPFRelation.STYLES; - int i = getRelationIndex(relation); + XWPFRelation relation = XWPFRelation.STYLES; + int i = getRelationIndex(relation); - XWPFStyles wrapper = (XWPFStyles)createRelationship(relation, XWPFFactory.getInstance(), i); - wrapper.setStyles(stylesDoc.addNewStyles()); - styles = wrapper; - } + XWPFStyles wrapper = (XWPFStyles) createRelationship(relation, XWPFFactory.getInstance(), i); + wrapper.setStyles(stylesDoc.addNewStyles()); + styles = wrapper; + } - return styles; + return styles; } /** * Creates an empty footnotes element for the document if one does not already exist + * * @return footnotes */ public XWPFFootnotes createFootnotes() { - if(footnotes == null) { - FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance(); + if (footnotes == null) { + FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance(); - XWPFRelation relation = XWPFRelation.FOOTNOTE; - int i = getRelationIndex(relation); + XWPFRelation relation = XWPFRelation.FOOTNOTE; + int i = getRelationIndex(relation); - XWPFFootnotes wrapper = (XWPFFootnotes)createRelationship(relation, XWPFFactory.getInstance(), i); - wrapper.setFootnotes(footnotesDoc.addNewFootnotes()); - footnotes = wrapper; - } + XWPFFootnotes wrapper = (XWPFFootnotes) createRelationship(relation, XWPFFactory.getInstance(), i); + wrapper.setFootnotes(footnotesDoc.addNewFootnotes()); + footnotes = wrapper; + } - return footnotes; + return footnotes; } public XWPFFootnote addFootnote(CTFtnEdn note) { - return footnotes.addFootnote(note); + return footnotes.addFootnote(note); } public XWPFFootnote addEndnote(CTFtnEdn note) { - XWPFFootnote endnote = new XWPFFootnote(this, note); - endnotes.put(note.getId().intValue(), endnote); - return endnote; + XWPFFootnote endnote = new XWPFFootnote(this, note); + endnotes.put(note.getId().intValue(), endnote); + return endnote; } /** - * remove a BodyElement from bodyElements array list + * remove a BodyElement from bodyElements array list + * * @param pos * @return true if removing was successfully, else return false */ public boolean removeBodyElement(int pos) { if (pos >= 0 && pos < bodyElements.size()) { - BodyElementType type = bodyElements.get(pos).getElementType(); - if (type == BodyElementType.TABLE){ + BodyElementType type = bodyElements.get(pos).getElementType(); + if (type == BodyElementType.TABLE) { int tablePos = getTablePos(pos); tables.remove(tablePos); ctDocument.getBody().removeTbl(tablePos); @@ -830,13 +837,14 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { ctDocument.getBody().removeP(paraPos); } bodyElements.remove(pos); - return true; + return true; } return false; } /** * copies content of a paragraph to a existing paragraph in the list paragraphs at position pos + * * @param paragraph * @param pos */ @@ -859,6 +867,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Create an empty table with one row and one column as default. + * * @return a new table */ public XWPFTable createTable() { @@ -870,19 +879,20 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Create an empty table with a number of rows and cols specified + * * @param rows * @param cols * @return table */ public XWPFTable createTable(int rows, int cols) { - XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols); - bodyElements.add(table); - tables.add(table); - return table; + XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols); + bodyElements.add(table); + tables.add(table); + return table; } /** - * + * */ public void createTOC() { CTSdtBlock block = this.getDocument().getBody().addNewSdt(); @@ -900,7 +910,9 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { } } - /**Replace content of table in array tables at position pos with a + /** + * Replace content of table in array tables at position pos with a + * * @param pos * @param table */ @@ -919,7 +931,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * <w:settings ... > * <w:documentProtection w:edit="readOnly" w:enforcement="1"/> * - * + * * @return true if documentProtection is enforced with option readOnly */ public boolean isEnforcedReadonlyProtection() { @@ -936,7 +948,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * <w:settings ... > * <w:documentProtection w:edit="forms" w:enforcement="1"/> * - * + * * @return true if documentProtection is enforced with option forms */ public boolean isEnforcedFillingFormsProtection() { @@ -953,7 +965,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * <w:settings ... > * <w:documentProtection w:edit="comments" w:enforcement="1"/> * - * + * * @return true if documentProtection is enforced with option comments */ public boolean isEnforcedCommentsProtection() { @@ -970,7 +982,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * <w:settings ... > * <w:documentProtection w:edit="trackedChanges" w:enforcement="1"/> * - * + * * @return true if documentProtection is enforced with option trackedChanges */ public boolean isEnforcedTrackedChangesProtection() { @@ -1002,21 +1014,21 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { *
    * sample snippet from settings.xml *
    -     *   <w:documentProtection w:edit="readOnly" w:enforcement="1" 
    +     *   <w:documentProtection w:edit="readOnly" w:enforcement="1"
          *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
          *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
          *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
          *   />
          * 
    - * + * * @param password the plaintext password, if null no password will be applied * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 + * if null, it will default default to sha1 */ public void enforceReadonlyProtection(String password, HashAlgorithm hashAlgo) { settings.setEnforcementEditValue(STDocProtect.READ_ONLY, password, hashAlgo); } - + /** * Enforce the Filling Forms protection.
    * In the documentProtection tag inside settings.xml file,
    @@ -1038,21 +1050,21 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { *
    * sample snippet from settings.xml *
    -     *   <w:documentProtection w:edit="forms" w:enforcement="1" 
    +     *   <w:documentProtection w:edit="forms" w:enforcement="1"
          *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
          *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
          *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
          *   />
          * 
    - * + * * @param password the plaintext password, if null no password will be applied * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 + * if null, it will default default to sha1 */ public void enforceFillingFormsProtection(String password, HashAlgorithm hashAlgo) { settings.setEnforcementEditValue(STDocProtect.FORMS, password, hashAlgo); } - + /** * Enforce the Comments protection.
    * In the documentProtection tag inside settings.xml file,
    @@ -1074,21 +1086,21 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { *
    * sample snippet from settings.xml *
    -     *   <w:documentProtection w:edit="comments" w:enforcement="1" 
    +     *   <w:documentProtection w:edit="comments" w:enforcement="1"
          *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
          *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
          *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
          *   />
          * 
    - * + * * @param password the plaintext password, if null no password will be applied * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 + * if null, it will default default to sha1 */ public void enforceCommentsProtection(String password, HashAlgorithm hashAlgo) { settings.setEnforcementEditValue(STDocProtect.COMMENTS, password, hashAlgo); } - + /** * Enforce the Tracked Changes protection.
    * In the documentProtection tag inside settings.xml file,
    @@ -1110,16 +1122,16 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { *
    * sample snippet from settings.xml *
    -     *   <w:documentProtection w:edit="trackedChanges" w:enforcement="1" 
    +     *   <w:documentProtection w:edit="trackedChanges" w:enforcement="1"
          *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
          *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
          *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
          *   />
          * 
    - * + * * @param password the plaintext password, if null no password will be applied * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 + * if null, it will default default to sha1 */ public void enforceTrackedChangesProtection(String password, HashAlgorithm hashAlgo) { settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES, password, hashAlgo); @@ -1134,7 +1146,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { public boolean validateProtectionPassword(String password) { return settings.validateProtectionPassword(password); } - + /** * Remove protection enforcement.
    * In the documentProtection tag inside settings.xml file
    @@ -1148,38 +1160,39 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * Enforces fields update on document open (in Word). * In the settings.xml file
    * sets the updateSettings value to true (w:updateSettings w:val="true") - * - * NOTICES: - *
      - *
    • Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" - * (if "Update automatic links at open" is enabled)
    • - *
    • Flag is removed after saving with changes in Word
    • - *
    + *

    + * NOTICES: + *

      + *
    • Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" + * (if "Update automatic links at open" is enabled)
    • + *
    • Flag is removed after saving with changes in Word
    • + *
    */ public void enforceUpdateFields() { settings.setUpdateFields(); } - - /** - * Check if revision tracking is turned on. - * - * @return true if revision tracking is turned on - */ - public boolean isTrackRevisions() { - return settings.isTrackRevisions(); - } - - /** - * Enable or disable revision tracking. - * - * @param enable true to turn on revision tracking, false to turn off revision tracking - */ - public void setTrackRevisions(boolean enable) { - settings.setTrackRevisions(enable); - } + + /** + * Check if revision tracking is turned on. + * + * @return true if revision tracking is turned on + */ + public boolean isTrackRevisions() { + return settings.isTrackRevisions(); + } + + /** + * Enable or disable revision tracking. + * + * @param enable true to turn on revision tracking, false to turn off revision tracking + */ + public void setTrackRevisions(boolean enable) { + settings.setTrackRevisions(enable); + } /** * inserts an existing XWPFTable to the arrays bodyElements and tables + * * @param pos * @param table */ @@ -1199,6 +1212,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Returns all Pictures, which are referenced from the document itself. + * * @return a {@link List} of {@link XWPFPictureData}. The returned {@link List} is unmodifiable. Use #a */ public List getAllPictures() { @@ -1223,14 +1237,12 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { list = new ArrayList(1); packagePictures.put(picData.getChecksum(), list); } - if (!list.contains(picData)) - { + if (!list.contains(picData)) { list.add(picData); } } - - XWPFPictureData findPackagePictureData(byte[] pictureData, int format) - { + + XWPFPictureData findPackagePictureData(byte[] pictureData, int format) { long checksum = IOUtils.calculateChecksum(pictureData); XWPFPictureData xwpfPicData = null; /* @@ -1246,20 +1258,18 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { xwpfPicData = curElem; } } - } + } return xwpfPicData; } - public String addPictureData(byte[] pictureData,int format) throws InvalidFormatException - { + public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException { XWPFPictureData xwpfPicData = findPackagePictureData(pictureData, format); POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format]; - - if (xwpfPicData == null) - { + + if (xwpfPicData == null) { /* Part doesn't exist, create a new one */ int idx = getNextPicNameNumber(format); - xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(),idx); + xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx); /* write bytes to new part */ PackagePart picDataPart = xwpfPicData.getPackagePart(); OutputStream out = null; @@ -1278,11 +1288,9 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { registerPackagePictureData(xwpfPicData); pictures.add(xwpfPicData); - + return getRelationId(xwpfPicData); - } - else if (!getRelations().contains(xwpfPicData)) - { + } else if (!getRelations().contains(xwpfPicData)) { /* * Part already existed, but was not related so far. Create * relationship to the already existing part and update @@ -1293,21 +1301,18 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { TargetMode targetMode = TargetMode.INTERNAL; PackagePartName partName = picDataPart.getPartName(); String relation = relDesc.getRelation(); - PackageRelationship relShip = getPackagePart().addRelationship(partName,targetMode,relation); + PackageRelationship relShip = getPackagePart().addRelationship(partName, targetMode, relation); String id = relShip.getId(); - addRelation(id,xwpfPicData); + addRelation(id, xwpfPicData); pictures.add(xwpfPicData); return id; - } - else - { + } else { /* Part already existed, get relation id and return it */ return getRelationId(xwpfPicData); } } - - public String addPictureData(InputStream is,int format) throws InvalidFormatException - { + + public String addPictureData(InputStream is, int format) throws InvalidFormatException { try { byte[] data = IOUtils.toByteArray(is); return addPictureData(data, format); @@ -1318,9 +1323,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get the next free ImageNumber + * * @param format * @return the next free ImageNumber - * @throws InvalidFormatException + * @throws InvalidFormatException */ public int getNextPicNameNumber(int format) throws InvalidFormatException { int img = getAllPackagePictures().size() + 1; @@ -1336,6 +1342,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * returns the PictureData by blipID + * * @param blipID * @return XWPFPictureData of a specificID */ @@ -1350,6 +1357,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * getNumbering + * * @return numbering */ public XWPFNumbering getNumbering() { @@ -1358,6 +1366,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get Styles + * * @return styles for this document */ public XWPFStyles getStyles() { @@ -1366,7 +1375,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get the paragraph with the CTP class p - * + * * @param p * @return the paragraph with the CTP class p */ @@ -1382,9 +1391,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get a table by its CTTbl-Object + * * @param ctTbl - * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) * @return a table by its CTTbl-Object or null + * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) */ @Override public XWPFTable getTable(CTTbl ctTbl) { @@ -1406,6 +1416,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Returns the paragraph that of position pos + * * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) */ @Override @@ -1420,6 +1431,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * returns the Part, to which the body belongs, which you need for adding relationship to other parts * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell * belongs. + * * @see org.apache.poi.xwpf.usermodel.IBody#getPart() */ @Override @@ -1441,6 +1453,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get the TableCell which belongs to the TableCell + * * @param cell */ @Override @@ -1448,19 +1461,19 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { XmlCursor cursor = cell.newCursor(); cursor.toParent(); XmlObject o = cursor.getObject(); - if(!(o instanceof CTRow)){ + if (!(o instanceof CTRow)) { return null; } - CTRow row = (CTRow)o; + CTRow row = (CTRow) o; cursor.toParent(); o = cursor.getObject(); cursor.dispose(); - if(! (o instanceof CTTbl)){ + if (!(o instanceof CTTbl)) { return null; } CTTbl tbl = (CTTbl) o; XWPFTable table = getTable(tbl); - if(table == null){ + if (table == null) { return null; } XWPFTableRow tableRow = table.getRow(row); diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java index c6b2c2d3e4..4fb02ce9b8 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java @@ -28,30 +28,29 @@ import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -/** - * @author Yegor Kozlov - */ -public final class XWPFFactory extends POIXMLFactory { - - private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class); - - private XWPFFactory(){ - - } - - private static final XWPFFactory inst = new XWPFFactory(); - - public static XWPFFactory getInstance(){ - return inst; - } - - @Override - public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part){ - POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType()); - if(descriptor == null || descriptor.getRelationClass() == null){ - logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType()); - return new POIXMLDocumentPart(part, rel); - } +/** + * @author Yegor Kozlov + */ +public final class XWPFFactory extends POIXMLFactory { + + private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class); + private static final XWPFFactory inst = new XWPFFactory(); + + private XWPFFactory() { + + } + + public static XWPFFactory getInstance() { + return inst; + } + + @Override + public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part) { + POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType()); + if (descriptor == null || descriptor.getRelationClass() == null) { + logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType()); + return new POIXMLDocumentPart(part, rel); + } try { Class cls = descriptor.getRelationClass(); @@ -59,23 +58,23 @@ public final class XWPFFactory extends POIXMLFactory { Constructor constructor = cls.getDeclaredConstructor(POIXMLDocumentPart.class, PackagePart.class, PackageRelationship.class); return constructor.newInstance(parent, part, rel); } catch (NoSuchMethodException e) { - Constructor constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class); - return constructor.newInstance(part, rel); - } - } catch (Exception e){ - throw new POIXMLException(e); - } - } - - @Override - public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){ - try { - Class cls = descriptor.getRelationClass(); - Constructor constructor = cls.getDeclaredConstructor(); - return constructor.newInstance(); - } catch (Exception e){ - throw new POIXMLException(e); - } - } + Constructor constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class); + return constructor.newInstance(part, rel); + } + } catch (Exception e) { + throw new POIXMLException(e); + } + } + + @Override + public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor) { + try { + Class cls = descriptor.getRelationClass(); + Constructor constructor = cls.getDeclaredConstructor(); + return constructor.newInstance(); + } catch (Exception e) { + throw new POIXMLException(e); + } + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java index 8485f1d6c5..8ae33260f3 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java @@ -53,16 +53,16 @@ public class XWPFFooter extends XWPFHeaderFooter { while (cursor.toNextSelection()) { XmlObject o = cursor.getObject(); if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP)o, this); + XWPFParagraph p = new XWPFParagraph((CTP) o, this); paragraphs.add(p); bodyElements.add(p); } if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl)o, this); + XWPFTable t = new XWPFTable((CTTbl) o, this); tables.add(t); bodyElements.add(t); } - + } cursor.dispose(); } @@ -78,7 +78,7 @@ public class XWPFFooter extends XWPFHeaderFooter { protected void commit() throws IOException { XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "ftr")); - Map map = new HashMap(); + Map map = new HashMap(); map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve"); map.put("urn:schemas-microsoft-com:office:office", "o"); map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); @@ -95,8 +95,8 @@ public class XWPFFooter extends XWPFHeaderFooter { out.close(); } - @Override - protected void onDocumentRead() throws IOException{ + @Override + protected void onDocumentRead() throws IOException { super.onDocumentRead(); FtrDocument ftrDocument = null; InputStream is; @@ -111,19 +111,19 @@ public class XWPFFooter extends XWPFHeaderFooter { while (cursor.toNextSelection()) { XmlObject o = cursor.getObject(); if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP)o, this); + XWPFParagraph p = new XWPFParagraph((CTP) o, this); paragraphs.add(p); bodyElements.add(p); } if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl)o, this); + XWPFTable t = new XWPFTable((CTTbl) o, this); tables.add(t); bodyElements.add(t); } - if (o instanceof CTSdtBlock){ - XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); - bodyElements.add(c); - } + if (o instanceof CTSdtBlock) { + XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); + bodyElements.add(c); + } } cursor.dispose(); } catch (Exception e) { @@ -133,6 +133,7 @@ public class XWPFFooter extends XWPFHeaderFooter { /** * get the PartType of the body + * * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() */ public BodyType getPartType() { diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java index 5f0367d6bf..7b51ed4543 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java @@ -27,64 +27,64 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; - -public class XWPFFootnote implements Iterable,IBody { - private List paragraphs = new ArrayList(); - private List tables= new ArrayList(); - private List pictures = new ArrayList(); - private List bodyElements = new ArrayList(); - +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; + +public class XWPFFootnote implements Iterable, IBody { + private List paragraphs = new ArrayList(); + private List tables = new ArrayList(); + private List pictures = new ArrayList(); + private List bodyElements = new ArrayList(); + private CTFtnEdn ctFtnEdn; private XWPFFootnotes footnotes; - private XWPFDocument document; - - public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) { - footnotes = xFootnotes; - ctFtnEdn = note; - document = xFootnotes.getXWPFDocument(); - init(); - } - - public XWPFFootnote(XWPFDocument document, CTFtnEdn body) { - ctFtnEdn = body; - this.document = document; - init(); - } - - private void init(){ - XmlCursor cursor = ctFtnEdn.newCursor(); - //copied from XWPFDocument...should centralize this code - //to avoid duplication - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - bodyElements.add(p); - paragraphs.add(p); - } else if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - bodyElements.add(t); - tables.add(t); - } else if (o instanceof CTSdtBlock){ - XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); - bodyElements.add(c); - } - - } - cursor.dispose(); - } - - public List getParagraphs() { - return paragraphs; - } - - public Iterator iterator(){ - return paragraphs.iterator(); - } - + private XWPFDocument document; + + public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) { + footnotes = xFootnotes; + ctFtnEdn = note; + document = xFootnotes.getXWPFDocument(); + init(); + } + + public XWPFFootnote(XWPFDocument document, CTFtnEdn body) { + ctFtnEdn = body; + this.document = document; + init(); + } + + private void init() { + XmlCursor cursor = ctFtnEdn.newCursor(); + //copied from XWPFDocument...should centralize this code + //to avoid duplication + cursor.selectPath("./*"); + while (cursor.toNextSelection()) { + XmlObject o = cursor.getObject(); + if (o instanceof CTP) { + XWPFParagraph p = new XWPFParagraph((CTP) o, this); + bodyElements.add(p); + paragraphs.add(p); + } else if (o instanceof CTTbl) { + XWPFTable t = new XWPFTable((CTTbl) o, this); + bodyElements.add(t); + tables.add(t); + } else if (o instanceof CTSdtBlock) { + XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); + bodyElements.add(c); + } + + } + cursor.dispose(); + } + + public List getParagraphs() { + return paragraphs; + } + + public Iterator iterator() { + return paragraphs.iterator(); + } + public List getTables() { return tables; } @@ -95,226 +95,231 @@ public class XWPFFootnote implements Iterable,IBody { public List getBodyElements() { return bodyElements; - } - - public CTFtnEdn getCTFtnEdn() { - return ctFtnEdn; - } - - public void setCTFtnEdn(CTFtnEdn footnote) { - ctFtnEdn = footnote; - } - - /** + } + + public CTFtnEdn getCTFtnEdn() { + return ctFtnEdn; + } + + public void setCTFtnEdn(CTFtnEdn footnote) { + ctFtnEdn = footnote; + } + + /** * @param pos in table array * @return The table at position pos - * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) - */ - public XWPFTable getTableArray(int pos) { - if(pos > 0 && pos < tables.size()){ - return tables.get(pos); - } - return null; + * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) + */ + public XWPFTable getTableArray(int pos) { + if (pos > 0 && pos < tables.size()) { + return tables.get(pos); + } + return null; } - - /** - * inserts an existing XWPFTable to the arrays bodyElements and tables - * @param pos - * @param table - * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table) + + /** + * inserts an existing XWPFTable to the arrays bodyElements and tables + * + * @param pos + * @param table + * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table) */ @SuppressWarnings("deprecation") public void insertTable(int pos, XWPFTable table) { - bodyElements.add(pos, table); - int i = 0; - for (CTTbl tbl : ctFtnEdn.getTblArray()) { - if(tbl == table.getCTTbl()){ - break; - } - i++; + bodyElements.add(pos, table); + int i = 0; + for (CTTbl tbl : ctFtnEdn.getTblArray()) { + if (tbl == table.getCTTbl()) { + break; + } + i++; } tables.add(i, table); } - /** - * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header - * the method will return this table - * if there is no corresponding {@link XWPFTable} the method will return null - * @param ctTable - * @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable) - */ - public XWPFTable getTable(CTTbl ctTable){ - for (XWPFTable table : tables) { - if(table==null) - return null; - if(table.getCTTbl().equals(ctTable)) - return table; - } - return null; + /** + * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header + * the method will return this table + * if there is no corresponding {@link XWPFTable} the method will return null + * + * @param ctTable + * @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable) + */ + public XWPFTable getTable(CTTbl ctTable) { + for (XWPFTable table : tables) { + if (table == null) + return null; + if (table.getCTTbl().equals(ctTable)) + return table; + } + return null; } - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer - * XWPFParagraph with the correspondig CTP p - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p) - */ - public XWPFParagraph getParagraph(CTP p){ - for (XWPFParagraph paragraph : paragraphs) { - if(paragraph.getCTP().equals(p)) - return paragraph; - } - return null; + /** + * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer + * the method will return this paragraph + * if there is no corresponding {@link XWPFParagraph} the method will return null + * + * @param p is instance of CTP and is searching for an XWPFParagraph + * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer + * XWPFParagraph with the correspondig CTP p + * @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p) + */ + public XWPFParagraph getParagraph(CTP p) { + for (XWPFParagraph paragraph : paragraphs) { + if (paragraph.getCTP().equals(p)) + return paragraph; + } + return null; } - - /** - * Returns the paragraph that holds - * the text of the header or footer. - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos) - */ - public XWPFParagraph getParagraphArray(int pos) { + + /** + * Returns the paragraph that holds + * the text of the header or footer. + * + * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos) + */ + public XWPFParagraph getParagraphArray(int pos) { return paragraphs.get(pos); } - - /** - * get the TableCell which belongs to the TableCell - * @param cell - * @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell) - */ + + /** + * get the TableCell which belongs to the TableCell + * + * @param cell + * @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell) + */ public XWPFTableCell getTableCell(CTTc cell) { - XmlCursor cursor = cell.newCursor(); - cursor.toParent(); - XmlObject o = cursor.getObject(); - if(!(o instanceof CTRow)){ - return null; - } - CTRow row = (CTRow)o; - cursor.toParent(); - o = cursor.getObject(); - cursor.dispose(); - if(! (o instanceof CTTbl)){ - return null; - } - CTTbl tbl = (CTTbl) o; - XWPFTable table = getTable(tbl); - if(table == null){ - return null; - } - XWPFTableRow tableRow = table.getRow(row); - if(row == null){ - return null; - } - return tableRow.getTableCell(cell); + XmlCursor cursor = cell.newCursor(); + cursor.toParent(); + XmlObject o = cursor.getObject(); + if (!(o instanceof CTRow)) { + return null; + } + CTRow row = (CTRow) o; + cursor.toParent(); + o = cursor.getObject(); + cursor.dispose(); + if (!(o instanceof CTTbl)) { + return null; + } + CTTbl tbl = (CTTbl) o; + XWPFTable table = getTable(tbl); + if (table == null) { + return null; + } + XWPFTableRow tableRow = table.getRow(row); + if (row == null) { + return null; + } + return tableRow.getTableCell(cell); } - - /** - * verifies that cursor is on the right position - * @param cursor - */ - private boolean isCursorInFtn(XmlCursor cursor) { - XmlCursor verify = cursor.newCursor(); - verify.toParent(); - if(verify.getObject() == this.ctFtnEdn){ - return true; - } - return false; - } - - public POIXMLDocumentPart getOwner(){ - return footnotes; - } - - /** - * - * @param cursor - * @return the inserted table - * @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor) - */ - public XWPFTable insertNewTbl(XmlCursor cursor) { - if(isCursorInFtn(cursor)){ - String uri = CTTbl.type.getName().getNamespaceURI(); - String localPart = "tbl"; - cursor.beginElement(localPart,uri); - cursor.toParent(); - CTTbl t = (CTTbl)cursor.getObject(); - XWPFTable newT = new XWPFTable(t, this); - cursor.removeXmlContents(); - XmlObject o = null; - while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){ - o = cursor.getObject(); - } - if(!(o instanceof CTTbl)){ - tables.add(0, newT); - } - else{ - int pos = tables.indexOf(getTable((CTTbl)o))+1; - tables.add(pos,newT); - } - int i=0; - cursor = t.newCursor(); - while(cursor.toPrevSibling()){ - o =cursor.getObject(); - if(o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newT); + + /** + * verifies that cursor is on the right position + * + * @param cursor + */ + private boolean isCursorInFtn(XmlCursor cursor) { + XmlCursor verify = cursor.newCursor(); + verify.toParent(); + if (verify.getObject() == this.ctFtnEdn) { + return true; + } + return false; + } + + public POIXMLDocumentPart getOwner() { + return footnotes; + } + + /** + * @param cursor + * @return the inserted table + * @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor) + */ + public XWPFTable insertNewTbl(XmlCursor cursor) { + if (isCursorInFtn(cursor)) { + String uri = CTTbl.type.getName().getNamespaceURI(); + String localPart = "tbl"; + cursor.beginElement(localPart, uri); + cursor.toParent(); + CTTbl t = (CTTbl) cursor.getObject(); + XWPFTable newT = new XWPFTable(t, this); + cursor.removeXmlContents(); + XmlObject o = null; + while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { + o = cursor.getObject(); + } + if (!(o instanceof CTTbl)) { + tables.add(0, newT); + } else { + int pos = tables.indexOf(getTable((CTTbl) o)) + 1; + tables.add(pos, newT); + } + int i = 0; + cursor = t.newCursor(); + while (cursor.toPrevSibling()) { + o = cursor.getObject(); + if (o instanceof CTP || o instanceof CTTbl) + i++; + } + bodyElements.add(i, newT); cursor = t.newCursor(); cursor.toEndToken(); return newT; } return null; } - - /** - * add a new paragraph at position of the cursor - * @param cursor - * @return the inserted paragraph - * @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor) - */ - public XWPFParagraph insertNewParagraph(XmlCursor cursor){ - if(isCursorInFtn(cursor)){ - String uri = CTP.type.getName().getNamespaceURI(); - String localPart = "p"; - cursor.beginElement(localPart,uri); - cursor.toParent(); - CTP p = (CTP)cursor.getObject(); - XWPFParagraph newP = new XWPFParagraph(p, this); - XmlObject o = null; - while(!(o instanceof CTP)&&(cursor.toPrevSibling())){ - o = cursor.getObject(); - } - if((!(o instanceof CTP)) || (CTP)o == p){ - paragraphs.add(0, newP); - } - else{ - int pos = paragraphs.indexOf(getParagraph((CTP)o))+1; - paragraphs.add(pos,newP); - } - int i=0; - cursor.toCursor(p.newCursor()); - while(cursor.toPrevSibling()){ - o =cursor.getObject(); - if(o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newP); + + /** + * add a new paragraph at position of the cursor + * + * @param cursor + * @return the inserted paragraph + * @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor) + */ + public XWPFParagraph insertNewParagraph(XmlCursor cursor) { + if (isCursorInFtn(cursor)) { + String uri = CTP.type.getName().getNamespaceURI(); + String localPart = "p"; + cursor.beginElement(localPart, uri); + cursor.toParent(); + CTP p = (CTP) cursor.getObject(); + XWPFParagraph newP = new XWPFParagraph(p, this); + XmlObject o = null; + while (!(o instanceof CTP) && (cursor.toPrevSibling())) { + o = cursor.getObject(); + } + if ((!(o instanceof CTP)) || (CTP) o == p) { + paragraphs.add(0, newP); + } else { + int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; + paragraphs.add(pos, newP); + } + int i = 0; + cursor.toCursor(p.newCursor()); + while (cursor.toPrevSibling()) { + o = cursor.getObject(); + if (o instanceof CTP || o instanceof CTTbl) + i++; + } + bodyElements.add(i, newP); cursor.toCursor(p.newCursor()); cursor.toEndToken(); return newP; } return null; } - - /** - * add a new table to the end of the footnote - * @param table - * @return the added XWPFTable - */ + + /** + * add a new table to the end of the footnote + * + * @param table + * @return the added XWPFTable + */ public XWPFTable addNewTbl(CTTbl table) { CTTbl newTable = ctFtnEdn.addNewTbl(); newTable.set(table); @@ -322,12 +327,13 @@ public class XWPFFootnote implements Iterable,IBody { tables.add(xTable); return xTable; } - - /** - * add a new paragraph to the end of the footnote - * @param paragraph - * @return the added XWPFParagraph - */ + + /** + * add a new paragraph to the end of the footnote + * + * @param paragraph + * @return the added XWPFParagraph + */ public XWPFParagraph addNewParagraph(CTP paragraph) { CTP newPara = ctFtnEdn.addNewP(); newPara.set(paragraph); @@ -336,26 +342,28 @@ public class XWPFFootnote implements Iterable,IBody { return xPara; } - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument() - */ - public XWPFDocument getXWPFDocument() { - return document; - } - - /** - * returns the Part, to which the body belongs, which you need for adding relationship to other parts - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public POIXMLDocumentPart getPart() { + /** + * @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument() + */ + public XWPFDocument getXWPFDocument() { + return document; + } + + /** + * returns the Part, to which the body belongs, which you need for adding relationship to other parts + * + * @see org.apache.poi.xwpf.usermodel.IBody#getPart() + */ + public POIXMLDocumentPart getPart() { return footnotes; } - - /** - * get the PartType of the body - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { + + /** + * get the PartType of the body + * + * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() + */ + public BodyType getPartType() { return BodyType.FOOTNOTE; } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java index 8647454f28..c84cab66c6 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java @@ -31,32 +31,31 @@ import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFootnotes; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument; - -/** - * Looks after the collection of Footnotes for a document - */ -public class XWPFFootnotes extends POIXMLDocumentPart { - private List listFootnote = new ArrayList(); - private CTFootnotes ctFootnotes; - - protected XWPFDocument document; - - /** - * Construct XWPFFootnotes from a package part - * - * @param part the package part holding the data of the footnotes, - * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" - */ - public XWPFFootnotes(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{ - super(part, rel); - } - +import org.apache.poi.openxml4j.opc.PackageRelationship; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlOptions; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFootnotes; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument; + +/** + * Looks after the collection of Footnotes for a document + */ +public class XWPFFootnotes extends POIXMLDocumentPart { + protected XWPFDocument document; + private List listFootnote = new ArrayList(); + private CTFootnotes ctFootnotes; + + /** + * Construct XWPFFootnotes from a package part + * + * @param part the package part holding the data of the footnotes, + * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" + */ + public XWPFFootnotes(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException { + super(part, rel); + } + /** * Construct XWPFFootnotes from scratch for a new document. */ @@ -65,33 +64,33 @@ public class XWPFFootnotes extends POIXMLDocumentPart { /** * Read document - */ - @Override - @SuppressWarnings("deprecation") - protected void onDocumentRead () throws IOException { - FootnotesDocument notesDoc; - try { - InputStream is = getPackagePart().getInputStream(); + */ + @Override + @SuppressWarnings("deprecation") + protected void onDocumentRead() throws IOException { + FootnotesDocument notesDoc; + try { + InputStream is = getPackagePart().getInputStream(); notesDoc = FootnotesDocument.Factory.parse(is); ctFootnotes = notesDoc.getFootnotes(); } catch (XmlException e) { throw new POIXMLException(); - } - - // Find our footnotes - for(CTFtnEdn note : ctFootnotes.getFootnoteArray()) { - listFootnote.add(new XWPFFootnote(note, this)); - } - } + } + + // Find our footnotes + for (CTFtnEdn note : ctFootnotes.getFootnoteArray()) { + listFootnote.add(new XWPFFootnote(note, this)); + } + } @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes")); - Map map = new HashMap(); - map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); - map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); - xmlOptions.setSaveSuggestedPrefixes(map); + protected void commit() throws IOException { + XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); + xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes")); + Map map = new HashMap(); + map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); + map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); + xmlOptions.setSaveSuggestedPrefixes(map); PackagePart part = getPackagePart(); OutputStream out = part.getOutputStream(); ctFootnotes.save(out, xmlOptions); @@ -100,59 +99,62 @@ public class XWPFFootnotes extends POIXMLDocumentPart { public List getFootnotesList() { return listFootnote; + } + + public XWPFFootnote getFootnoteById(int id) { + for (XWPFFootnote note : listFootnote) { + if (note.getCTFtnEdn().getId().intValue() == id) + return note; + } + return null; } - - public XWPFFootnote getFootnoteById(int id) { - for(XWPFFootnote note : listFootnote) { - if(note.getCTFtnEdn().getId().intValue() == id) - return note; - } - return null; - } - - /** - * Sets the ctFootnotes - * @param footnotes - */ - public void setFootnotes(CTFootnotes footnotes) { + + /** + * Sets the ctFootnotes + * + * @param footnotes + */ + public void setFootnotes(CTFootnotes footnotes) { ctFootnotes = footnotes; } - - /** - * add an XWPFFootnote to the document - * @param footnote - * @throws IOException - */ - public void addFootnote(XWPFFootnote footnote){ - listFootnote.add(footnote); - ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn()); - } - - /** - * add a footnote to the document - * @param note - * @throws IOException - */ - public XWPFFootnote addFootnote(CTFtnEdn note){ - CTFtnEdn newNote = ctFootnotes.addNewFootnote(); - newNote.set(note); - XWPFFootnote xNote = new XWPFFootnote(newNote, this); + + /** + * add an XWPFFootnote to the document + * + * @param footnote + * @throws IOException + */ + public void addFootnote(XWPFFootnote footnote) { + listFootnote.add(footnote); + ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn()); + } + + /** + * add a footnote to the document + * + * @param note + * @throws IOException + */ + public XWPFFootnote addFootnote(CTFtnEdn note) { + CTFtnEdn newNote = ctFootnotes.addNewFootnote(); + newNote.set(note); + XWPFFootnote xNote = new XWPFFootnote(newNote, this); listFootnote.add(xNote); - return xNote; - } - - public void setXWPFDocument(XWPFDocument doc) { - document = doc; - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public XWPFDocument getXWPFDocument() { - if ( document != null) { - return document; - } else { - return (XWPFDocument)getParent(); - } - } -} + return xNote; + } + + /** + * @see org.apache.poi.xwpf.usermodel.IBody#getPart() + */ + public XWPFDocument getXWPFDocument() { + if (document != null) { + return document; + } else { + return (XWPFDocument) getParent(); + } + } + + public void setXWPFDocument(XWPFDocument doc) { + document = doc; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java index a07bf41417..2a31247fd0 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java @@ -69,14 +69,14 @@ public class XWPFHeader extends XWPFHeaderFooter { cursor.dispose(); } - /** + /** * save and commit footer */ @Override protected void commit() throws IOException { XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "hdr")); - Map map = new HashMap(); + Map map = new HashMap(); map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve"); map.put("urn:schemas-microsoft-com:office:office", "o"); map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); @@ -95,11 +95,12 @@ public class XWPFHeader extends XWPFHeaderFooter { /** * reads the document - * @throws IOException + * + * @throws IOException */ - @Override + @Override protected void onDocumentRead() throws IOException { - super.onDocumentRead(); + super.onDocumentRead(); HdrDocument hdrDocument = null; InputStream is; try { @@ -113,17 +114,17 @@ public class XWPFHeader extends XWPFHeaderFooter { while (cursor.toNextSelection()) { XmlObject o = cursor.getObject(); if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP)o, this); + XWPFParagraph p = new XWPFParagraph((CTP) o, this); paragraphs.add(p); bodyElements.add(p); } if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl)o, this); + XWPFTable t = new XWPFTable((CTTbl) o, this); tables.add(t); bodyElements.add(t); } - if (o instanceof CTSdtBlock){ - XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); + if (o instanceof CTSdtBlock) { + XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); bodyElements.add(c); } } @@ -135,6 +136,7 @@ public class XWPFHeader extends XWPFHeaderFooter { /** * get the PartType of the body + * * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() */ public BodyType getPartType() { diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java index e6dee2fef3..2f96a681c2 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java @@ -46,7 +46,7 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; */ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBody { List paragraphs = new ArrayList(1); - List tables= new ArrayList(1); + List tables = new ArrayList(1); List pictures = new ArrayList(); List bodyElements = new ArrayList(1); @@ -54,7 +54,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo XWPFDocument document; XWPFHeaderFooter(XWPFDocument doc, CTHdrFtr hdrFtr) { - if (doc==null) { + if (doc == null) { throw new NullPointerException(); } @@ -70,17 +70,17 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo public XWPFHeaderFooter(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel) throws IOException { super(parent, part, rel); - this.document = (XWPFDocument)getParent(); + this.document = (XWPFDocument) getParent(); - if (this.document==null) { + if (this.document == null) { throw new NullPointerException(); } } @Override protected void onDocumentRead() throws IOException { - for (POIXMLDocumentPart poixmlDocumentPart : getRelations()){ - if(poixmlDocumentPart instanceof XWPFPictureData){ + for (POIXMLDocumentPart poixmlDocumentPart : getRelations()) { + if (poixmlDocumentPart instanceof XWPFPictureData) { XWPFPictureData xwpfPicData = (XWPFPictureData) poixmlDocumentPart; pictures.add(xwpfPicData); document.registerPackagePictureData(xwpfPicData); @@ -93,16 +93,16 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo return headerFooter; } - public List getBodyElements(){ + public List getBodyElements() { return Collections.unmodifiableList(bodyElements); } /** * Returns the paragraph(s) that holds - * the text of the header or footer. + * the text of the header or footer. * Normally there is only the one paragraph, but - * there could be more in certain cases, or - * a table. + * there could be more in certain cases, or + * a table. */ public List getParagraphs() { return Collections.unmodifiableList(paragraphs); @@ -111,29 +111,28 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * Return the table(s) that holds the text - * of the header or footer, for complex cases - * where a paragraph isn't used. + * of the header or footer, for complex cases + * where a paragraph isn't used. * Normally there's just one paragraph, but some - * complex headers/footers have a table or two - * in addition. + * complex headers/footers have a table or two + * in addition. */ - public List getTables()throws ArrayIndexOutOfBoundsException { + public List getTables() throws ArrayIndexOutOfBoundsException { return Collections.unmodifiableList(tables); } - /** * Returns the textual content of the header/footer, - * by flattening out the text of its paragraph(s) + * by flattening out the text of its paragraph(s) */ public String getText() { StringBuffer t = new StringBuffer(); - //TODO: simplify this to get ibody elements in order - for(int i=0; i 0) { + if (text != null && text.length() > 0) { t.append(text); t.append('\n'); } @@ -141,26 +140,26 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo } List tables = getTables(); - for(int i=0; i 0) { + if (text != null && text.length() > 0) { t.append(text); t.append('\n'); } } - - for (IBodyElement bodyElement : getBodyElements()){ - if (bodyElement instanceof XWPFSDT){ - t.append(((XWPFSDT) bodyElement).getContent().getText()+'\n'); - } - } - return t.toString(); + + for (IBodyElement bodyElement : getBodyElements()) { + if (bodyElement instanceof XWPFSDT) { + t.append(((XWPFSDT) bodyElement).getContent().getText() + '\n'); + } + } + return t.toString(); } /** * set a new headerFooter */ - public void setHeaderFooter(CTHdrFtr headerFooter){ + public void setHeaderFooter(CTHdrFtr headerFooter) { this.headerFooter = headerFooter; readHdrFtr(); } @@ -168,14 +167,15 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header * the method will return this table - * if there is no corresponding {@link XWPFTable} the method will return null + * if there is no corresponding {@link XWPFTable} the method will return null + * * @param ctTable */ - public XWPFTable getTable(CTTbl ctTable){ + public XWPFTable getTable(CTTbl ctTable) { for (XWPFTable table : tables) { - if(table==null) + if (table == null) return null; - if(table.getCTTbl().equals(ctTable)) + if (table.getCTTbl().equals(ctTable)) return table; } return null; @@ -184,14 +184,15 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null + * if there is no corresponding {@link XWPFParagraph} the method will return null + * * @param p is instance of CTP and is searching for an XWPFParagraph * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer - * XWPFParagraph with the correspondig CTP p + * XWPFParagraph with the correspondig CTP p */ - public XWPFParagraph getParagraph(CTP p){ + public XWPFParagraph getParagraph(CTP p) { for (XWPFParagraph paragraph : paragraphs) { - if(paragraph.getCTP().equals(p)) + if (paragraph.getCTP().equals(p)) return paragraph; } return null; @@ -200,7 +201,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * Returns the paragraph that holds - * the text of the header or footer. + * the text of the header or footer. */ public XWPFParagraph getParagraphArray(int pos) { @@ -209,9 +210,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * get a List of all Paragraphs - * @return a list of {@link XWPFParagraph} + * + * @return a list of {@link XWPFParagraph} */ - public List getListParagraph(){ + public List getListParagraph() { return paragraphs; } @@ -221,9 +223,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * get all Pictures in this package + * * @return all Pictures in this package */ - public List getAllPackagePictures(){ + public List getAllPackagePictures() { return document.getAllPackagePictures(); } @@ -231,22 +234,19 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * Adds a picture to the document. * - * @param pictureData The picture data - * @param format The format of the picture. - * + * @param pictureData The picture data + * @param format The format of the picture. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . - * @throws InvalidFormatException + * @throws InvalidFormatException */ - public String addPictureData(byte[] pictureData,int format) throws InvalidFormatException - { + public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException { XWPFPictureData xwpfPicData = document.findPackagePictureData(pictureData, format); POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format]; - if (xwpfPicData == null) - { + if (xwpfPicData == null) { /* Part doesn't exist, create a new one */ int idx = document.getNextPicNameNumber(format); - xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(),idx); + xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx); /* write bytes to new part */ PackagePart picDataPart = xwpfPicData.getPackagePart(); OutputStream out = null; @@ -266,9 +266,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo document.registerPackagePictureData(xwpfPicData); pictures.add(xwpfPicData); return getRelationId(xwpfPicData); - } - else if (!getRelations().contains(xwpfPicData)) - { + } else if (!getRelations().contains(xwpfPicData)) { /* * Part already existed, but was not related so far. Create * relationship to the already existing part and update @@ -279,14 +277,12 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo TargetMode targetMode = TargetMode.INTERNAL; PackagePartName partName = picDataPart.getPartName(); String relation = relDesc.getRelation(); - PackageRelationship relShip = getPackagePart().addRelationship(partName,targetMode,relation); + PackageRelationship relShip = getPackagePart().addRelationship(partName, targetMode, relation); String id = relShip.getId(); - addRelation(id,xwpfPicData); + addRelation(id, xwpfPicData); pictures.add(xwpfPicData); return id; - } - else - { + } else { /* Part already existed, get relation id and return it */ return getRelationId(xwpfPicData); } @@ -295,61 +291,61 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * Adds a picture to the document. * - * @param is The stream to read image from - * @param format The format of the picture. - * + * @param is The stream to read image from + * @param format The format of the picture. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . - * @throws InvalidFormatException - * @throws IOException + * @throws InvalidFormatException + * @throws IOException */ - public String addPictureData(InputStream is, int format) throws InvalidFormatException,IOException { + public String addPictureData(InputStream is, int format) throws InvalidFormatException, IOException { byte[] data = IOUtils.toByteArray(is); - return addPictureData(data,format); + return addPictureData(data, format); } /** * returns the PictureData by blipID + * * @param blipID * @return XWPFPictureData of a specificID - * @throws Exception + * @throws Exception */ public XWPFPictureData getPictureDataByID(String blipID) { POIXMLDocumentPart relatedPart = getRelationById(blipID); if (relatedPart != null && relatedPart instanceof XWPFPictureData) { return (XWPFPictureData) relatedPart; } - return null; + return null; } /** * add a new paragraph at position of the cursor + * * @param cursor * @return the inserted paragraph */ - public XWPFParagraph insertNewParagraph(XmlCursor cursor){ - if(isCursorInHdrF(cursor)){ + public XWPFParagraph insertNewParagraph(XmlCursor cursor) { + if (isCursorInHdrF(cursor)) { String uri = CTP.type.getName().getNamespaceURI(); String localPart = "p"; - cursor.beginElement(localPart,uri); + cursor.beginElement(localPart, uri); cursor.toParent(); - CTP p = (CTP)cursor.getObject(); + CTP p = (CTP) cursor.getObject(); XWPFParagraph newP = new XWPFParagraph(p, this); XmlObject o = null; - while(!(o instanceof CTP)&&(cursor.toPrevSibling())){ + while (!(o instanceof CTP) && (cursor.toPrevSibling())) { o = cursor.getObject(); } - if((!(o instanceof CTP)) || (CTP)o == p){ + if ((!(o instanceof CTP)) || (CTP) o == p) { paragraphs.add(0, newP); + } else { + int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; + paragraphs.add(pos, newP); } - else{ - int pos = paragraphs.indexOf(getParagraph((CTP)o))+1; - paragraphs.add(pos,newP); - } - int i=0; + int i = 0; cursor.toCursor(p.newCursor()); - while(cursor.toPrevSibling()){ - o =cursor.getObject(); - if(o instanceof CTP || o instanceof CTTbl) + while (cursor.toPrevSibling()) { + o = cursor.getObject(); + if (o instanceof CTP || o instanceof CTTbl) i++; } bodyElements.add(i, newP); @@ -362,35 +358,33 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** - * * @param cursor * @return the inserted table */ public XWPFTable insertNewTbl(XmlCursor cursor) { - if(isCursorInHdrF(cursor)){ + if (isCursorInHdrF(cursor)) { String uri = CTTbl.type.getName().getNamespaceURI(); String localPart = "tbl"; - cursor.beginElement(localPart,uri); + cursor.beginElement(localPart, uri); cursor.toParent(); - CTTbl t = (CTTbl)cursor.getObject(); + CTTbl t = (CTTbl) cursor.getObject(); XWPFTable newT = new XWPFTable(t, this); cursor.removeXmlContents(); XmlObject o = null; - while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){ + while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { o = cursor.getObject(); } - if(!(o instanceof CTTbl)){ + if (!(o instanceof CTTbl)) { tables.add(0, newT); + } else { + int pos = tables.indexOf(getTable((CTTbl) o)) + 1; + tables.add(pos, newT); } - else{ - int pos = tables.indexOf(getTable((CTTbl)o))+1; - tables.add(pos,newT); - } - int i=0; + int i = 0; cursor = t.newCursor(); - while(cursor.toPrevSibling()){ - o =cursor.getObject(); - if(o instanceof CTP || o instanceof CTTbl) + while (cursor.toPrevSibling()) { + o = cursor.getObject(); + if (o instanceof CTP || o instanceof CTTbl) i++; } bodyElements.add(i, newT); @@ -403,29 +397,31 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * verifies that cursor is on the right position + * * @param cursor */ private boolean isCursorInHdrF(XmlCursor cursor) { XmlCursor verify = cursor.newCursor(); verify.toParent(); - if(verify.getObject() == this.headerFooter){ + if (verify.getObject() == this.headerFooter) { return true; } return false; } - public POIXMLDocumentPart getOwner(){ + public POIXMLDocumentPart getOwner() { return this; } /** * Returns the table at position pos + * * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) */ public XWPFTable getTableArray(int pos) { - if(pos > 0 && pos < tables.size()){ + if (pos > 0 && pos < tables.size()) { return tables.get(pos); } return null; @@ -433,6 +429,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * inserts an existing XWPFTable to the arrays bodyElements and tables + * * @param pos * @param table */ @@ -441,7 +438,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo bodyElements.add(pos, table); int i = 0; for (CTTbl tbl : headerFooter.getTblArray()) { - if(tbl == table.getCTTbl()){ + if (tbl == table.getCTTbl()) { break; } i++; @@ -450,10 +447,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo } - public void readHdrFtr(){ + public void readHdrFtr() { bodyElements = new ArrayList(); paragraphs = new ArrayList(); - tables= new ArrayList(); + tables = new ArrayList(); // parse the document with cursor and add // the XmlObject to its lists XmlCursor cursor = headerFooter.newCursor(); @@ -461,12 +458,12 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo while (cursor.toNextSelection()) { XmlObject o = cursor.getObject(); if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP)o, this); + XWPFParagraph p = new XWPFParagraph((CTP) o, this); paragraphs.add(p); bodyElements.add(p); } if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl)o, this); + XWPFTable t = new XWPFTable((CTTbl) o, this); tables.add(t); bodyElements.add(t); } @@ -476,48 +473,50 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo /** * get the TableCell which belongs to the TableCell + * * @param cell */ public XWPFTableCell getTableCell(CTTc cell) { XmlCursor cursor = cell.newCursor(); cursor.toParent(); XmlObject o = cursor.getObject(); - if(!(o instanceof CTRow)){ + if (!(o instanceof CTRow)) { return null; } - CTRow row = (CTRow)o; + CTRow row = (CTRow) o; cursor.toParent(); o = cursor.getObject(); cursor.dispose(); - if(! (o instanceof CTTbl)){ + if (!(o instanceof CTTbl)) { return null; } CTTbl tbl = (CTTbl) o; XWPFTable table = getTable(tbl); - if(table == null){ + if (table == null) { return null; } XWPFTableRow tableRow = table.getRow(row); - if(row == null){ + if (row == null) { return null; } return tableRow.getTableCell(cell); } - public void setXWPFDocument(XWPFDocument doc) { - document = doc; - } - public XWPFDocument getXWPFDocument() { - if (document!=null) { + if (document != null) { return document; } else { - return (XWPFDocument)getParent(); + return (XWPFDocument) getParent(); } } + public void setXWPFDocument(XWPFDocument doc) { + document = doc; + } + /** * returns the Part, to which the body belongs, which you need for adding relationship to other parts + * * @see org.apache.poi.xwpf.usermodel.IBody#getPart() */ public POIXMLDocumentPart getPart() { diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java index f9f2f9d329..c00f75a890 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java @@ -18,26 +18,22 @@ package org.apache.poi.xwpf.usermodel; /** * Sketch of XWPF hyperlink class - * -* @author Yury Batrakov (batrakov at gmail.com) - * + * + * @author Yury Batrakov (batrakov at gmail.com) */ -public class XWPFHyperlink -{ +public class XWPFHyperlink { String id, url; - public XWPFHyperlink(String id, String url) - { + + public XWPFHyperlink(String id, String url) { this.id = id; this.url = url; } - - public String getId() - { + + public String getId() { return id; } - - public String getURL() - { + + public String getURL() { return url; } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java index 2461d33242..4c8158a411 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java @@ -20,45 +20,45 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; /** - * A run of text with a Hyperlink applied to it. - * Any given Hyperlink may be made up of multiple of these. - */ -public class XWPFHyperlinkRun extends XWPFRun -{ - private CTHyperlink hyperlink; - - public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) { - super(run, p); - this.hyperlink = hyperlink; - } - - public CTHyperlink getCTHyperlink() { - return hyperlink; - } - - public String getAnchor() { - return hyperlink.getAnchor(); - } - - /** - * Returns the ID of the hyperlink, if one is set. - */ - public String getHyperlinkId() { - return hyperlink.getId(); - } - public void setHyperlinkId(String id) { - hyperlink.setId(id); - } - - /** - * If this Hyperlink is an external reference hyperlink, - * return the object for it. - */ - public XWPFHyperlink getHyperlink(XWPFDocument document) { - String id = getHyperlinkId(); - if(id == null) - return null; - - return document.getHyperlinkByID(id); - } -} + * A run of text with a Hyperlink applied to it. + * Any given Hyperlink may be made up of multiple of these. + */ +public class XWPFHyperlinkRun extends XWPFRun { + private CTHyperlink hyperlink; + + public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) { + super(run, p); + this.hyperlink = hyperlink; + } + + public CTHyperlink getCTHyperlink() { + return hyperlink; + } + + public String getAnchor() { + return hyperlink.getAnchor(); + } + + /** + * Returns the ID of the hyperlink, if one is set. + */ + public String getHyperlinkId() { + return hyperlink.getId(); + } + + public void setHyperlinkId(String id) { + hyperlink.setId(id); + } + + /** + * If this Hyperlink is an external reference hyperlink, + * return the object for it. + */ + public XWPFHyperlink getHyperlink(XWPFDocument document) { + String id = getHyperlinkId(); + if (id == null) + return null; + + return document.getHyperlinkByID(id); + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java index e942991984..ab802ffbcf 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java @@ -17,38 +17,38 @@ package org.apache.poi.xwpf.usermodel; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; - -public class XWPFLatentStyles { - private CTLatentStyles latentStyles; - protected XWPFStyles styles; //LatentStyle shall know styles - - protected XWPFLatentStyles(){ - } - - protected XWPFLatentStyles(CTLatentStyles latentStyles){ - this(latentStyles,null); - } - - protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) { - this.latentStyles=latentStyles; - this.styles=styles; - } - - public int getNumberOfStyles() { +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; + +public class XWPFLatentStyles { + protected XWPFStyles styles; //LatentStyle shall know styles + private CTLatentStyles latentStyles; + + protected XWPFLatentStyles() { + } + + protected XWPFLatentStyles(CTLatentStyles latentStyles) { + this(latentStyles, null); + } + + protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) { + this.latentStyles = latentStyles; + this.styles = styles; + } + + public int getNumberOfStyles() { return latentStyles.sizeOfLsdExceptionArray(); } /** - * checks whether specific LatentStyleID is a latentStyle - */ - @SuppressWarnings("deprecation") - protected boolean isLatentStyle(String latentStyleID){ - for ( CTLsdException lsd: latentStyles.getLsdExceptionArray()) { - if(lsd.getName().equals(latentStyleID)) { - return true; - } - } - return false; - } -} + * checks whether specific LatentStyleID is a latentStyle + */ + @SuppressWarnings("deprecation") + protected boolean isLatentStyle(String latentStyleID) { + for (CTLsdException lsd : latentStyles.getLsdExceptionArray()) { + if (lsd.getName().equals(latentStyleID)) { + return true; + } + } + return false; + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java index 300936d2a0..b1ae7ed8cf 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java @@ -18,48 +18,47 @@ package org.apache.poi.xwpf.usermodel; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; - -/** - * @author Philipp Epp - * - */ -public class XWPFNum { - private CTNum ctNum; - protected XWPFNumbering numbering; - - public XWPFNum(){ - this.ctNum = null; - this.numbering = null; - } - - public XWPFNum(CTNum ctNum){ - this.ctNum = ctNum; - this.numbering = null; - } - - public XWPFNum(XWPFNumbering numbering){ - this.ctNum = null; - this.numbering = numbering; - } - - public XWPFNum(CTNum ctNum, XWPFNumbering numbering){ - this.ctNum = ctNum; - this.numbering = numbering; - } - - public XWPFNumbering getNumbering(){ - return numbering; - } - - public CTNum getCTNum(){ - return ctNum; - } - - public void setNumbering(XWPFNumbering numbering){ - this.numbering = numbering; - } - - public void setCTNum(CTNum ctNum){ - this.ctNum = ctNum; - } + +/** + * @author Philipp Epp + */ +public class XWPFNum { + protected XWPFNumbering numbering; + private CTNum ctNum; + + public XWPFNum() { + this.ctNum = null; + this.numbering = null; + } + + public XWPFNum(CTNum ctNum) { + this.ctNum = ctNum; + this.numbering = null; + } + + public XWPFNum(XWPFNumbering numbering) { + this.ctNum = null; + this.numbering = numbering; + } + + public XWPFNum(CTNum ctNum, XWPFNumbering numbering) { + this.ctNum = ctNum; + this.numbering = numbering; + } + + public XWPFNumbering getNumbering() { + return numbering; + } + + public void setNumbering(XWPFNumbering numbering) { + this.numbering = numbering; + } + + public CTNum getCTNum() { + return ctNum; + } + + public void setCTNum(CTNum ctNum) { + this.ctNum = ctNum; + } } \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java index 1bc8af5aed..842bb44346 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java @@ -38,71 +38,69 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering; import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument; - -/** - * @author Philipp Epp - * - */ -public class XWPFNumbering extends POIXMLDocumentPart { - protected List abstractNums = new ArrayList(); - protected List nums = new ArrayList(); - - private CTNumbering ctNumbering; - boolean isNew; - - /** - *create a new styles object with an existing document - */ - public XWPFNumbering(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{ - super(part, rel); - isNew = true; - } - - /** - * create a new XWPFNumbering object for use in a new document - */ - public XWPFNumbering(){ - abstractNums = new ArrayList(); - nums = new ArrayList(); - isNew = true; - } - - /** - * read numbering form an existing package - */ - @Override - @SuppressWarnings("deprecation") - protected void onDocumentRead() throws IOException{ - NumberingDocument numberingDoc = null; - InputStream is; - is = getPackagePart().getInputStream(); - try { - numberingDoc = NumberingDocument.Factory.parse(is); - ctNumbering = numberingDoc.getNumbering(); - //get any Nums - for(CTNum ctNum : ctNumbering.getNumArray()) { - nums.add(new XWPFNum(ctNum, this)); - } - for(CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()){ - abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this)); - } - isNew = false; - } catch (XmlException e) { - throw new POIXMLException(); - } - } - - /** - * save and commit numbering - */ - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering")); - Map map = new HashMap(); - map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve"); - map.put("urn:schemas-microsoft-com:office:office", "o"); - map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); + +/** + * @author Philipp Epp + */ +public class XWPFNumbering extends POIXMLDocumentPart { + protected List abstractNums = new ArrayList(); + protected List nums = new ArrayList(); + boolean isNew; + private CTNumbering ctNumbering; + + /** + * create a new styles object with an existing document + */ + public XWPFNumbering(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException { + super(part, rel); + isNew = true; + } + + /** + * create a new XWPFNumbering object for use in a new document + */ + public XWPFNumbering() { + abstractNums = new ArrayList(); + nums = new ArrayList(); + isNew = true; + } + + /** + * read numbering form an existing package + */ + @Override + @SuppressWarnings("deprecation") + protected void onDocumentRead() throws IOException { + NumberingDocument numberingDoc = null; + InputStream is; + is = getPackagePart().getInputStream(); + try { + numberingDoc = NumberingDocument.Factory.parse(is); + ctNumbering = numberingDoc.getNumbering(); + //get any Nums + for (CTNum ctNum : ctNumbering.getNumArray()) { + nums.add(new XWPFNum(ctNum, this)); + } + for (CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()) { + abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this)); + } + isNew = false; + } catch (XmlException e) { + throw new POIXMLException(); + } + } + + /** + * save and commit numbering + */ + @Override + protected void commit() throws IOException { + XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); + xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering")); + Map map = new HashMap(); + map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve"); + map.put("urn:schemas-microsoft-com:office:office", "o"); + map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); map.put("http://schemas.openxmlformats.org/officeDocument/2006/math", "m"); map.put("urn:schemas-microsoft-com:vml", "v"); map.put("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "wp"); @@ -114,169 +112,182 @@ public class XWPFNumbering extends POIXMLDocumentPart { OutputStream out = part.getOutputStream(); ctNumbering.save(out, xmlOptions); out.close(); - } - - - /** - * Sets the ctNumbering - * @param numbering - */ - public void setNumbering(CTNumbering numbering){ - ctNumbering = numbering; - } - - - /** - * Checks whether number with numID exists - * @param numID - * @return boolean true if num exist, false if num not exist - */ - public boolean numExist(BigInteger numID){ - for (XWPFNum num : nums) { - if (num.getCTNum().getNumId().equals(numID)) - return true; - } - return false; - } - - /** - * add a new number to the numbering document - * @param num - */ - public BigInteger addNum(XWPFNum num){ - ctNumbering.addNewNum(); - int pos = ctNumbering.sizeOfNumArray() - 1; - ctNumbering.setNumArray(pos, num.getCTNum()); - nums.add(num); - return num.getCTNum().getNumId(); - } - - /** - * Add a new num with an abstractNumID - * @return return NumId of the added num - */ - public BigInteger addNum(BigInteger abstractNumID){ - CTNum ctNum = this.ctNumbering.addNewNum(); - ctNum.addNewAbstractNumId(); - ctNum.getAbstractNumId().setVal(abstractNumID); - ctNum.setNumId(BigInteger.valueOf(nums.size()+1)); - XWPFNum num = new XWPFNum(ctNum, this); - nums.add(num); - return ctNum.getNumId(); - } - - /** - * Add a new num with an abstractNumID and a numID - * @param abstractNumID - * @param numID - */ - public void addNum(BigInteger abstractNumID, BigInteger numID){ - CTNum ctNum = this.ctNumbering.addNewNum(); - ctNum.addNewAbstractNumId(); - ctNum.getAbstractNumId().setVal(abstractNumID); - ctNum.setNumId(numID); - XWPFNum num = new XWPFNum(ctNum, this); - nums.add(num); - } - - /** - * get Num by NumID - * @param numID - * @return abstractNum with NumId if no Num exists with that NumID - * null will be returned - */ - public XWPFNum getNum(BigInteger numID){ - for(XWPFNum num: nums){ - if(num.getCTNum().getNumId().equals(numID)) - return num; - } - return null; - } - /** - * get AbstractNum by abstractNumID - * @param abstractNumID - * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID - * null will be returned - */ - public XWPFAbstractNum getAbstractNum(BigInteger abstractNumID){ - for(XWPFAbstractNum abstractNum: abstractNums){ - if(abstractNum.getAbstractNum().getAbstractNumId().equals(abstractNumID)){ - return abstractNum; - } - } - return null; - } - /** - * Compare AbstractNum with abstractNums of this numbering document. - * If the content of abstractNum equals with an abstractNum of the List in numbering - * the BigInteger Value of it will be returned. - * If no equal abstractNum is existing null will be returned - * - * @param abstractNum - * @return BigInteger - */ - public BigInteger getIdOfAbstractNum(XWPFAbstractNum abstractNum){ - CTAbstractNum copy = (CTAbstractNum) abstractNum.getCTAbstractNum().copy(); - XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this); - int i; - for (i = 0; i < abstractNums.size(); i++) { - newAbstractNum.getCTAbstractNum().setAbstractNumId(BigInteger.valueOf(i)); - newAbstractNum.setNumbering(this); - if(newAbstractNum.getCTAbstractNum().valueEquals(abstractNums.get(i).getCTAbstractNum())){ - return newAbstractNum.getCTAbstractNum().getAbstractNumId(); - } - } - return null; - } - - - /** - * add a new AbstractNum and return its AbstractNumID - * @param abstractNum - */ - public BigInteger addAbstractNum(XWPFAbstractNum abstractNum){ - int pos = abstractNums.size(); - if(abstractNum.getAbstractNum() != null){ // Use the current CTAbstractNum if it exists - ctNumbering.addNewAbstractNum().set(abstractNum.getAbstractNum()); - } else { - ctNumbering.addNewAbstractNum(); - abstractNum.getAbstractNum().setAbstractNumId(BigInteger.valueOf(pos)); - ctNumbering.setAbstractNumArray(pos, abstractNum.getAbstractNum()); - } - abstractNums.add(abstractNum); - return abstractNum.getCTAbstractNum().getAbstractNumId(); - } - - /** - * remove an existing abstractNum - * @param abstractNumID - * @return true if abstractNum with abstractNumID exists in NumberingArray, - * false if abstractNum with abstractNumID not exists - */ - public boolean removeAbstractNum(BigInteger abstractNumID){ - if(abstractNumID.byteValue()A Paragraph within a Document, Table, Header etc.

    - * + *

    A Paragraph within a Document, Table, Header etc.

    + *

    *

    A paragraph has a lot of styling information, but the - * actual text (possibly along with more styling) is held on - * the child {@link XWPFRun}s.

    + * actual text (possibly along with more styling) is held on + * the child {@link XWPFRun}s.

    */ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Paragraph { private final CTP paragraph; protected IBody part; - /** For access to the document's hyperlink, comments, tables etc */ + /** + * For access to the document's hyperlink, comments, tables etc + */ protected XWPFDocument document; protected List runs; protected List iruns; @@ -77,10 +80,10 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para public XWPFParagraph(CTP prgrph, IBody part) { this.paragraph = prgrph; this.part = part; - + this.document = part.getXWPFDocument(); - if (document==null) { + if (document == null) { throw new NullPointerException(); } @@ -90,7 +93,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para buildRunsInOrderFromXml(paragraph); // Look for bits associated with the runs - for(XWPFRun run : runs) { + for (XWPFRun run : runs) { CTR r = run.getCTR(); // Check for bits that only apply when attached to a core document @@ -99,13 +102,13 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para c.selectPath("child::*"); while (c.toNextSelection()) { XmlObject o = c.getObject(); - if(o instanceof CTFtnEdnRef) { - CTFtnEdnRef ftn = (CTFtnEdnRef)o; + if (o instanceof CTFtnEdnRef) { + CTFtnEdnRef ftn = (CTFtnEdnRef) o; footnoteText.append(" [").append(ftn.getId()).append(": "); XWPFFootnote footnote = - ftn.getDomNode().getLocalName().equals("footnoteReference") ? - document.getFootnoteByID(ftn.getId().intValue()) : - document.getEndnoteByID(ftn.getId().intValue()); + ftn.getDomNode().getLocalName().equals("footnoteReference") ? + document.getFootnoteByID(ftn.getId().intValue()) : + document.getEndnoteByID(ftn.getId().intValue()); boolean first = true; for (XWPFParagraph p : footnote.getParagraphs()) { @@ -125,8 +128,8 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * Identifies (in order) the parts of the paragraph / - * sub-paragraph that correspond to character text - * runs, and builds the appropriate runs for these. + * sub-paragraph that correspond to character text + * runs, and builds the appropriate runs for these. */ private void buildRunsInOrderFromXml(XmlObject object) { XmlCursor c = object.newCursor(); @@ -134,71 +137,72 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para while (c.toNextSelection()) { XmlObject o = c.getObject(); if (o instanceof CTR) { - XWPFRun r = new XWPFRun((CTR) o, this); - runs.add(r); - iruns.add(r); - } - if (o instanceof CTHyperlink) { - CTHyperlink link = (CTHyperlink) o; - for (CTR r : link.getRArray()) { - XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this); - runs.add(hr); - iruns.add(hr); - } - } - if (o instanceof CTSdtBlock) { - XWPFSDT cc = new XWPFSDT((CTSdtBlock) o, part); - iruns.add(cc); - } - if (o instanceof CTSdtRun) { - XWPFSDT cc = new XWPFSDT((CTSdtRun) o, part); - iruns.add(cc); - } - if (o instanceof CTRunTrackChange) { - for (CTR r : ((CTRunTrackChange) o).getRArray()) { - XWPFRun cr = new XWPFRun(r, this); - runs.add(cr); - iruns.add(cr); - } - } - if (o instanceof CTSimpleField) { - for (CTR r : ((CTSimpleField) o).getRArray()) { - XWPFRun cr = new XWPFRun(r, this); - runs.add(cr); - iruns.add(cr); - } - } + XWPFRun r = new XWPFRun((CTR) o, this); + runs.add(r); + iruns.add(r); + } + if (o instanceof CTHyperlink) { + CTHyperlink link = (CTHyperlink) o; + for (CTR r : link.getRArray()) { + XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this); + runs.add(hr); + iruns.add(hr); + } + } + if (o instanceof CTSdtBlock) { + XWPFSDT cc = new XWPFSDT((CTSdtBlock) o, part); + iruns.add(cc); + } + if (o instanceof CTSdtRun) { + XWPFSDT cc = new XWPFSDT((CTSdtRun) o, part); + iruns.add(cc); + } + if (o instanceof CTRunTrackChange) { + for (CTR r : ((CTRunTrackChange) o).getRArray()) { + XWPFRun cr = new XWPFRun(r, this); + runs.add(cr); + iruns.add(cr); + } + } + if (o instanceof CTSimpleField) { + for (CTR r : ((CTSimpleField) o).getRArray()) { + XWPFRun cr = new XWPFRun(r, this); + runs.add(cr); + iruns.add(cr); + } + } if (o instanceof CTSmartTagRun) { - // Smart Tags can be nested many times. + // Smart Tags can be nested many times. // This implementation does not preserve the tagging information buildRunsInOrderFromXml(o); } } c.dispose(); } - + @Internal public CTP getCTP() { return paragraph; } - public List getRuns(){ + public List getRuns() { return Collections.unmodifiableList(runs); } - + /** * Return literal runs and sdt/content control objects. + * * @return List */ public List getIRuns() { return Collections.unmodifiableList(iruns); } - - public boolean isEmpty(){ + + public boolean isEmpty() { return !paragraph.getDomNode().hasChildNodes(); } - public XWPFDocument getDocument(){ + public XWPFDocument getDocument() { return document; } @@ -209,8 +213,8 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para public String getText() { StringBuffer out = new StringBuffer(); for (IRunElement run : iruns) { - if (run instanceof XWPFSDT){ - out.append(((XWPFSDT)run).getContent().getText()); + if (run instanceof XWPFSDT) { + out.append(((XWPFSDT) run).getContent().getText()); } else { out.append(run.toString()); } @@ -221,43 +225,63 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * Return styleID of the paragraph if style exist for this paragraph - * if not, null will be returned - * @return styleID as String + * if not, null will be returned + * + * @return styleID as String */ public String getStyleID() { if (paragraph.getPPr() != null) { - if(paragraph.getPPr().getPStyle()!= null) { - if (paragraph.getPPr().getPStyle().getVal()!= null) + if (paragraph.getPPr().getPStyle() != null) { + if (paragraph.getPPr().getPStyle().getVal() != null) return paragraph.getPPr().getPStyle().getVal(); } } return null; - } + } + /** * If style exist for this paragraph * NumId of the paragraph will be returned. - * If style not exist null will be returned - * @return NumID as BigInteger + * If style not exist null will be returned + * + * @return NumID as BigInteger */ - public BigInteger getNumID(){ - if(paragraph.getPPr()!=null){ - if(paragraph.getPPr().getNumPr()!=null){ - if(paragraph.getPPr().getNumPr().getNumId()!=null) + public BigInteger getNumID() { + if (paragraph.getPPr() != null) { + if (paragraph.getPPr().getNumPr() != null) { + if (paragraph.getPPr().getNumPr().getNumId() != null) return paragraph.getPPr().getNumPr().getNumId().getVal(); } } return null; } + /** + * setNumID of Paragraph + * + * @param numPos + */ + public void setNumID(BigInteger numPos) { + if (paragraph.getPPr() == null) + paragraph.addNewPPr(); + if (paragraph.getPPr().getNumPr() == null) + paragraph.getPPr().addNewNumPr(); + if (paragraph.getPPr().getNumPr().getNumId() == null) { + paragraph.getPPr().getNumPr().addNewNumId(); + } + paragraph.getPPr().getNumPr().getNumId().setVal(numPos); + } + /** * Returns Ilvl of the numeric style for this paragraph. * Returns null if this paragraph does not have numeric style. + * * @return Ilvl as BigInteger */ public BigInteger getNumIlvl() { - if(paragraph.getPPr()!=null){ - if(paragraph.getPPr().getNumPr()!=null){ - if(paragraph.getPPr().getNumPr().getIlvl()!=null) + if (paragraph.getPPr() != null) { + if (paragraph.getPPr().getNumPr() != null) { + if (paragraph.getPPr().getNumPr().getIlvl() != null) return paragraph.getPPr().getNumPr().getIlvl().getVal(); } } @@ -266,28 +290,28 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * Returns numbering format for this paragraph, eg bullet or - * lowerLetter. + * lowerLetter. * Returns null if this paragraph does not have numeric style. */ public String getNumFmt() { BigInteger numID = getNumID(); XWPFNumbering numbering = document.getNumbering(); - if(numID != null && numbering != null) { + if (numID != null && numbering != null) { XWPFNum num = numbering.getNum(numID); - if(num != null) { + if (num != null) { BigInteger ilvl = getNumIlvl(); BigInteger abstractNumId = num.getCTNum().getAbstractNumId().getVal(); CTAbstractNum anum = numbering.getAbstractNum(abstractNumId).getAbstractNum(); CTLvl level = null; - for(int i = 0; i < anum.sizeOfLvlArray(); i++) { + for (int i = 0; i < anum.sizeOfLvlArray(); i++) { CTLvl lvl = anum.getLvlArray(i); - if(lvl.getIlvl().equals(ilvl)) { + if (lvl.getIlvl().equals(ilvl)) { level = lvl; break; } } - if(level != null && level.getNumFmt() != null - && level.getNumFmt().getVal() != null) + if (level != null && level.getNumFmt() != null + && level.getNumFmt().getVal() != null) return level.getNumFmt().getVal().toString(); } } @@ -302,9 +326,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para public String getNumLevelText() { BigInteger numID = getNumID(); XWPFNumbering numbering = document.getNumbering(); - if(numID != null && numbering != null) { + if (numID != null && numbering != null) { XWPFNum num = numbering.getNum(numID); - if(num != null) { + if (num != null) { BigInteger ilvl = getNumIlvl(); CTNum ctNum = num.getCTNum(); if (ctNum == null) @@ -329,68 +353,54 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para return null; CTLvl level = null; - for(int i = 0; i < anum.sizeOfLvlArray(); i++) { + for (int i = 0; i < anum.sizeOfLvlArray(); i++) { CTLvl lvl = anum.getLvlArray(i); - if(lvl != null && lvl.getIlvl() != null && lvl.getIlvl().equals(ilvl)) { + if (lvl != null && lvl.getIlvl() != null && lvl.getIlvl().equals(ilvl)) { level = lvl; break; } } - if(level != null && level.getLvlText() != null - && level.getLvlText().getVal() != null) + if (level != null && level.getLvlText() != null + && level.getLvlText().getVal() != null) return level.getLvlText().getVal().toString(); } } return null; } - /** * Gets the numstartOverride for the paragraph numbering for this paragraph. + * * @return returns the overridden start number or null if there is no override for this paragraph. */ public BigInteger getNumStartOverride() { BigInteger numID = getNumID(); XWPFNumbering numbering = document.getNumbering(); - if(numID != null && numbering != null) { + if (numID != null && numbering != null) { XWPFNum num = numbering.getNum(numID); - if(num != null) { + if (num != null) { CTNum ctNum = num.getCTNum(); if (ctNum == null) { return null; } BigInteger ilvl = getNumIlvl(); CTNumLvl level = null; - for(int i = 0; i < ctNum.sizeOfLvlOverrideArray(); i++) { + for (int i = 0; i < ctNum.sizeOfLvlOverrideArray(); i++) { CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(i); - if(ctNumLvl != null && ctNumLvl.getIlvl() != null && - ctNumLvl.getIlvl().equals(ilvl)) { + if (ctNumLvl != null && ctNumLvl.getIlvl() != null && + ctNumLvl.getIlvl().equals(ilvl)) { level = ctNumLvl; break; } } - if(level != null && level.getStartOverride() != null) { + if (level != null && level.getStartOverride() != null) { return level.getStartOverride().getVal(); } } } return null; } - /** - * setNumID of Paragraph - * @param numPos - */ - public void setNumID(BigInteger numPos) { - if(paragraph.getPPr()==null) - paragraph.addNewPPr(); - if(paragraph.getPPr().getNumPr()==null) - paragraph.getPPr().addNewNumPr(); - if(paragraph.getPPr().getNumPr().getNumId()==null){ - paragraph.getPPr().getNumPr().addNewNumId(); - } - paragraph.getPPr().getNumPr().getNumId().setVal(numPos); - } /** * Returns the text of the paragraph, but not of any objects in the @@ -398,7 +408,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para */ public String getParagraphText() { StringBuffer out = new StringBuffer(); - for(XWPFRun run : runs) { + for (XWPFRun run : runs) { out.append(run.toString()); } return out.toString(); @@ -409,7 +419,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para */ public String getPictureText() { StringBuffer out = new StringBuffer(); - for(XWPFRun run : runs) { + for (XWPFRun run : runs) { out.append(run.getPictureText()); } return out.toString(); @@ -418,7 +428,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * Returns the footnote text of the paragraph * - * @return the footnote text or empty string if the paragraph does not have footnotes + * @return the footnote text or empty string if the paragraph does not have footnotes */ public String getFootnoteText() { return footnoteText.toString(); @@ -471,6 +481,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para public int getFontAlignment() { return getAlignment().getValue(); } + public void setFontAlignment(int align) { ParagraphAlignment pAlign = ParagraphAlignment.valueOf(align); setAlignment(pAlign); @@ -498,7 +509,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para CTPPr pr = getCTPPr(); return (pr == null || !pr.isSetTextAlignment()) ? TextAlignment.AUTO : TextAlignment.valueOf(pr.getTextAlignment().getVal() - .intValue()); + .intValue()); } /** @@ -524,9 +535,27 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para CTPPr pr = getCTPPr(); CTTextAlignment textAlignment = pr.isSetTextAlignment() ? pr .getTextAlignment() : pr.addNewTextAlignment(); - STTextAlignment.Enum en = STTextAlignment.Enum - .forInt(valign.getValue()); - textAlignment.setVal(en); + STTextAlignment.Enum en = STTextAlignment.Enum + .forInt(valign.getValue()); + textAlignment.setVal(en); + } + + /** + * Specifies the border which shall be displayed above a set of paragraphs + * which have the same set of paragraph border settings. + * + * @return paragraphBorder - the top border for the paragraph + * @see #setBorderTop(Borders) + * @see Borders a list of all types of borders + */ + public Borders getBorderTop() { + CTPBdr border = getCTPBrd(false); + CTBorder ct = null; + if (border != null) { + ct = border.getTop(); + } + STBorder.Enum ptrn = (ct != null) ? ct.getVal() : STBorder.NONE; + return Borders.valueOf(ptrn.intValue()); } /** @@ -570,20 +599,20 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the border which shall be displayed above a set of paragraphs - * which have the same set of paragraph border settings. + * Specifies the border which shall be displayed below a set of + * paragraphs which have the same set of paragraph border settings. * - * @return paragraphBorder - the top border for the paragraph - * @see #setBorderTop(Borders) + * @return paragraphBorder - the bottom border for the paragraph + * @see #setBorderBottom(Borders) * @see Borders a list of all types of borders */ - public Borders getBorderTop() { + public Borders getBorderBottom() { CTPBdr border = getCTPBrd(false); CTBorder ct = null; if (border != null) { - ct = border.getTop(); + ct = border.getBottom(); } - STBorder.Enum ptrn = (ct != null) ? ct.getVal() : STBorder.NONE; + STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; return Borders.valueOf(ptrn.intValue()); } @@ -624,18 +653,18 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the border which shall be displayed below a set of - * paragraphs which have the same set of paragraph border settings. + * Specifies the border which shall be displayed on the left side of the + * page around the specified paragraph. * - * @return paragraphBorder - the bottom border for the paragraph - * @see #setBorderBottom(Borders) - * @see Borders a list of all types of borders + * @return ParagraphBorder - the left border for the paragraph + * @see #setBorderLeft(Borders) + * @see Borders for a list of all possible borders */ - public Borders getBorderBottom() { + public Borders getBorderLeft() { CTPBdr border = getCTPBrd(false); CTBorder ct = null; if (border != null) { - ct = border.getBottom(); + ct = border.getLeft(); } STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; return Borders.valueOf(ptrn.intValue()); @@ -673,18 +702,18 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the border which shall be displayed on the left side of the + * Specifies the border which shall be displayed on the right side of the * page around the specified paragraph. * - * @return ParagraphBorder - the left border for the paragraph - * @see #setBorderLeft(Borders) + * @return ParagraphBorder - the right border for the paragraph + * @see #setBorderRight(Borders) * @see Borders for a list of all possible borders */ - public Borders getBorderLeft() { + public Borders getBorderRight() { CTPBdr border = getCTPBrd(false); CTBorder ct = null; if (border != null) { - ct = border.getLeft(); + ct = border.getRight(); } STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; return Borders.valueOf(ptrn.intValue()); @@ -722,18 +751,18 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the border which shall be displayed on the right side of the - * page around the specified paragraph. + * Specifies the border which shall be displayed between each paragraph in a + * set of paragraphs which have the same set of paragraph border settings. * - * @return ParagraphBorder - the right border for the paragraph - * @see #setBorderRight(Borders) + * @return ParagraphBorder - the between border for the paragraph + * @see #setBorderBetween(Borders) * @see Borders for a list of all possible borders */ - public Borders getBorderRight() { + public Borders getBorderBetween() { CTPBdr border = getCTPBrd(false); CTBorder ct = null; if (border != null) { - ct = border.getRight(); + ct = border.getBetween(); } STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; return Borders.valueOf(ptrn.intValue()); @@ -775,21 +804,29 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the border which shall be displayed between each paragraph in a - * set of paragraphs which have the same set of paragraph border settings. + * Specifies that when rendering this document in a paginated + * view, the contents of this paragraph are rendered on the start of a new + * page in the document. + *

    + * If this element is omitted on a given paragraph, + * its value is determined by the setting previously set at any level of the + * style hierarchy (i.e. that previous setting remains unchanged). If this + * setting is never specified in the style hierarchy, then this property + * shall not be applied. Since the paragraph is specified to start on a new + * page, it begins page two even though it could have fit on page one. + *

    * - * @return ParagraphBorder - the between border for the paragraph - * @see #setBorderBetween(Borders) - * @see Borders for a list of all possible borders + * @return boolean - if page break is set */ - public Borders getBorderBetween() { - CTPBdr border = getCTPBrd(false); - CTBorder ct = null; - if (border != null) { - ct = border.getBetween(); + public boolean isPageBreak() { + CTPPr ppr = getCTPPr(); + CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr + .getPageBreakBefore() : null; + if (ct_pageBreak != null + && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) { + return true; } - STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; - return Borders.valueOf(ptrn.intValue()); + return false; } /** @@ -819,29 +856,14 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies that when rendering this document in a paginated - * view, the contents of this paragraph are rendered on the start of a new - * page in the document. - *

    - * If this element is omitted on a given paragraph, - * its value is determined by the setting previously set at any level of the - * style hierarchy (i.e. that previous setting remains unchanged). If this - * setting is never specified in the style hierarchy, then this property - * shall not be applied. Since the paragraph is specified to start on a new - * page, it begins page two even though it could have fit on page one. - *

    + * Specifies the spacing that should be added after the last line in this + * paragraph in the document in absolute units. * - * @return boolean - if page break is set + * @return int - value representing the spacing after the paragraph */ - public boolean isPageBreak() { - CTPPr ppr = getCTPPr(); - CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr - .getPageBreakBefore() : null; - if (ct_pageBreak != null - && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) { - return true; - } - return false; + public int getSpacingAfter() { + CTSpacing spacing = getCTSpacing(false); + return (spacing != null && spacing.isSetAfter()) ? spacing.getAfter().intValue() : -1; } /** @@ -869,11 +891,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para * Specifies the spacing that should be added after the last line in this * paragraph in the document in absolute units. * - * @return int - value representing the spacing after the paragraph + * @return bigInteger - value representing the spacing after the paragraph + * @see #setSpacingAfterLines(int) */ - public int getSpacingAfter() { + public int getSpacingAfterLines() { CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetAfter()) ? spacing.getAfter().intValue() : -1; + return (spacing != null && spacing.isSetAfterLines()) ? spacing.getAfterLines().intValue() : -1; } /** @@ -899,20 +922,18 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para spacing.setAfterLines(bi); } - /** - * Specifies the spacing that should be added after the last line in this + * Specifies the spacing that should be added above the first line in this * paragraph in the document in absolute units. * - * @return bigInteger - value representing the spacing after the paragraph - * @see #setSpacingAfterLines(int) + * @return the spacing that should be added above the first line + * @see #setSpacingBefore(int) */ - public int getSpacingAfterLines() { + public int getSpacingBefore() { CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetAfterLines()) ? spacing.getAfterLines().intValue() : -1; + return (spacing != null && spacing.isSetBefore()) ? spacing.getBefore().intValue() : -1; } - /** * Specifies the spacing that should be added above the first line in this * paragraph in the document in absolute units. @@ -930,15 +951,16 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the spacing that should be added above the first line in this - * paragraph in the document in absolute units. + * Specifies the spacing that should be added before the first line in this paragraph in the + * document in line units. + * The value of this attribute is specified in one hundredths of a line. * - * @return the spacing that should be added above the first line - * @see #setSpacingBefore(int) + * @return the spacing that should be added before the first line in this paragraph + * @see #setSpacingBeforeLines(int) */ - public int getSpacingBefore() { + public int getSpacingBeforeLines() { CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetBefore()) ? spacing.getBefore().intValue() : -1; + return (spacing != null && spacing.isSetBeforeLines()) ? spacing.getBeforeLines().intValue() : -1; } /** @@ -960,19 +982,20 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the spacing that should be added before the first line in this paragraph in the - * document in line units. - * The value of this attribute is specified in one hundredths of a line. + * Specifies how the spacing between lines is calculated as stored in the + * line attribute. If this attribute is omitted, then it shall be assumed to + * be of a value auto if a line attribute value is present. * - * @return the spacing that should be added before the first line in this paragraph - * @see #setSpacingBeforeLines(int) + * @return rule + * @see LineSpacingRule + * @see #setSpacingLineRule(LineSpacingRule) */ - public int getSpacingBeforeLines() { + public LineSpacingRule getSpacingLineRule() { CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetBeforeLines()) ? spacing.getBeforeLines().intValue() : -1; + return (spacing != null && spacing.isSetLineRule()) ? LineSpacingRule.valueOf(spacing + .getLineRule().intValue()) : LineSpacingRule.AUTO; } - /** * Specifies how the spacing between lines is calculated as stored in the * line attribute. If this attribute is omitted, then it shall be assumed to @@ -987,21 +1010,24 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies how the spacing between lines is calculated as stored in the - * line attribute. If this attribute is omitted, then it shall be assumed to - * be of a value auto if a line attribute value is present. + * Specifies the indentation which shall be placed between the left text + * margin for this paragraph and the left edge of that paragraph's content + * in a left to right paragraph, and the right text margin and the right + * edge of that paragraph's text in a right to left paragraph + *

    + * If this attribute is omitted, its value shall be assumed to be zero. + * Negative values are defined such that the text is moved past the text margin, + * positive values move the text inside the text margin. + *

    * - * @return rule - * @see LineSpacingRule - * @see #setSpacingLineRule(LineSpacingRule) + * @return indentation or null if indentation is not set */ - public LineSpacingRule getSpacingLineRule() { - CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetLineRule()) ? LineSpacingRule.valueOf(spacing - .getLineRule().intValue()) : LineSpacingRule.AUTO; + public int getIndentationLeft() { + CTInd indentation = getCTInd(false); + return (indentation != null && indentation.isSetLeft()) ? indentation.getLeft().intValue() + : -1; } - /** * Specifies the indentation which shall be placed between the left text * margin for this paragraph and the left edge of that paragraph's content @@ -1022,8 +1048,8 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the indentation which shall be placed between the left text - * margin for this paragraph and the left edge of that paragraph's content + * Specifies the indentation which shall be placed between the right text + * margin for this paragraph and the right edge of that paragraph's content * in a left to right paragraph, and the right text margin and the right * edge of that paragraph's text in a right to left paragraph *

    @@ -1034,12 +1060,13 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para * * @return indentation or null if indentation is not set */ - public int getIndentationLeft() { + + public int getIndentationRight() { CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetLeft()) ? indentation.getLeft().intValue() + return (indentation != null && indentation.isSetRight()) ? indentation.getRight().intValue() : -1; } - + /** * Specifies the indentation which shall be placed between the right text * margin for this paragraph and the right edge of that paragraph's content @@ -1060,23 +1087,21 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } /** - * Specifies the indentation which shall be placed between the right text - * margin for this paragraph and the right edge of that paragraph's content - * in a left to right paragraph, and the right text margin and the right - * edge of that paragraph's text in a right to left paragraph - *

    - * If this attribute is omitted, its value shall be assumed to be zero. - * Negative values are defined such that the text is moved past the text margin, - * positive values move the text inside the text margin. - *

    + * Specifies the indentation which shall be removed from the first line of + * the parent paragraph, by moving the indentation on the first line back + * towards the beginning of the direction of text flow. + * This indentation is + * specified relative to the paragraph indentation which is specified for + * all other lines in the parent paragraph. + * The firstLine and hanging + * attributes are mutually exclusive, if both are specified, then the + * firstLine value is ignored. * * @return indentation or null if indentation is not set */ - - public int getIndentationRight() { + public int getIndentationHanging() { CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetRight()) ? indentation.getRight().intValue() - : -1; + return (indentation != null && indentation.isSetHanging()) ? indentation.getHanging().intValue() : -1; } /** @@ -1099,24 +1124,6 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para indent.setHanging(bi); } - /** - * Specifies the indentation which shall be removed from the first line of - * the parent paragraph, by moving the indentation on the first line back - * towards the beginning of the direction of text flow. - * This indentation is - * specified relative to the paragraph indentation which is specified for - * all other lines in the parent paragraph. - * The firstLine and hanging - * attributes are mutually exclusive, if both are specified, then the - * firstLine value is ignored. - * - * @return indentation or null if indentation is not set - */ - public int getIndentationHanging() { - CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetHanging()) ? indentation.getHanging().intValue() : -1; - } - /** * Specifies the additional indentation which shall be applied to the first * line of the parent paragraph. This additional indentation is specified @@ -1126,15 +1133,16 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para * mutually exclusive, if both are specified, then the firstLine value is * ignored. * If the firstLineChars attribute is also specified, then this - * value is ignored. If this attribute is omitted, then its value shall be + * value is ignored. + * If this attribute is omitted, then its value shall be * assumed to be zero (if needed). * - * @param indentation + * @return indentation or null if indentation is not set */ - public void setIndentationFirstLine(int indentation) { - CTInd indent = getCTInd(true); - BigInteger bi = new BigInteger("" + indentation); - indent.setFirstLine(bi); + public int getIndentationFirstLine() { + CTInd indentation = getCTInd(false); + return (indentation != null && indentation.isSetFirstLine()) ? indentation.getFirstLine().intValue() + : -1; } /** @@ -1146,21 +1154,21 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para * mutually exclusive, if both are specified, then the firstLine value is * ignored. * If the firstLineChars attribute is also specified, then this - * value is ignored. - * If this attribute is omitted, then its value shall be + * value is ignored. If this attribute is omitted, then its value shall be * assumed to be zero (if needed). * - * @return indentation or null if indentation is not set + * @param indentation */ - public int getIndentationFirstLine() { - CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetFirstLine()) ? indentation.getFirstLine().intValue() - : -1; + public void setIndentationFirstLine(int indentation) { + CTInd indent = getCTInd(true); + BigInteger bi = new BigInteger("" + indentation); + indent.setFirstLine(bi); } public int getIndentFromLeft() { return getIndentFromLeft(); } + public void setIndentFromLeft(int dxaLeft) { setIndentationLeft(dxaLeft); } @@ -1168,6 +1176,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para public int getIndentFromRight() { return getIndentFromRight(); } + public void setIndentFromRight(int dxaRight) { setIndentationRight(dxaRight); } @@ -1175,10 +1184,30 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para public int getFirstLineIndent() { return getIndentationFirstLine(); } + public void setFirstLineIndent(int first) { setIndentationFirstLine(first); } + /** + * This element specifies whether a consumer shall break Latin text which + * exceeds the text extents of a line by breaking the word across two lines + * (breaking on the character level) or by moving the word to the following + * line (breaking on the word level). + * + * @return boolean + */ + public boolean isWordWrapped() { + CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr() + .getWordWrap() : null; + if (wordWrap != null) { + return (wordWrap.getVal() == STOnOff.ON + || wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true + : false; + } + return false; + } + /** * This element specifies whether a consumer shall break Latin text which * exceeds the text extents of a line by breaking the word across two lines @@ -1195,36 +1224,29 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para else wordWrap.unsetVal(); } + + public boolean isWordWrap() { + return isWordWrapped(); + } + @Deprecated public void setWordWrap(boolean wrap) { setWordWrapped(wrap); } /** - * This element specifies whether a consumer shall break Latin text which - * exceeds the text extents of a line by breaking the word across two lines - * (breaking on the character level) or by moving the word to the following - * line (breaking on the word level). - * - * @return boolean + * @return the style of the paragraph */ - public boolean isWordWrapped() { - CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr() - .getWordWrap() : null; - if (wordWrap != null) { - return (wordWrap.getVal() == STOnOff.ON - || wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true - : false; - } - return false; - } - public boolean isWordWrap() { - return isWordWrapped(); + public String getStyle() { + CTPPr pr = getCTPPr(); + CTString style = pr.isSetPStyle() ? pr.getPStyle() : null; + return style != null ? style.getVal() : null; } /** * This method provides a style to the paragraph * This is useful when, e.g. an Heading style has to be assigned + * * @param newStyle */ public void setStyle(String newStyle) { @@ -1232,15 +1254,6 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para CTString style = pr.getPStyle() != null ? pr.getPStyle() : pr.addNewPStyle(); style.setVal(newStyle); } - - /** - * @return the style of the paragraph - */ - public String getStyle() { - CTPPr pr = getCTPPr(); - CTString style = pr.isSetPStyle() ? pr.getPStyle() : null; - return style != null ? style.getVal() : null; - } /** * Get a copy of the currently used CTPBrd, if none is used, return @@ -1287,20 +1300,21 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para : paragraph.getPPr(); return pr; } - - + + /** - * add a new run at the end of the position of + * add a new run at the end of the position of * the content of parameter run + * * @param run */ - protected void addRun(CTR run){ + protected void addRun(CTR run) { int pos; pos = paragraph.sizeOfRArray(); paragraph.addNewR(); paragraph.setRArray(pos, run); } - + /** * Appends a new run to this paragraph * @@ -1315,14 +1329,15 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * insert a new Run in RunArray + * * @param pos - * @return the inserted run + * @return the inserted run */ - public XWPFRun insertNewRun(int pos){ + public XWPFRun insertNewRun(int pos) { if (pos >= 0 && pos <= paragraph.sizeOfRArray()) { CTR ctRun = paragraph.insertNewR(pos); XWPFRun newRun = new XWPFRun(ctRun, this); - + // To update the iruns, find where we're going // in the normal runs, and go in there int iPos = iruns.size(); @@ -1334,10 +1349,10 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para } } iruns.add(iPos, newRun); - + // Runs itself is easy to update runs.add(pos, newRun); - + return newRun; } return null; @@ -1347,42 +1362,43 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para * this methods parse the paragraph and search for the string searched. * If it finds the string, it will return true and the position of the String * will be saved in the parameter startPos. + * * @param searched * @param startPos */ - public TextSegement searchText(String searched,PositionInParagraph startPos) { - int startRun = startPos.getRun(), - startText = startPos.getText(), - startChar = startPos.getChar(); + public TextSegement searchText(String searched, PositionInParagraph startPos) { + int startRun = startPos.getRun(), + startText = startPos.getText(), + startChar = startPos.getChar(); int beginRunPos = 0, candCharPos = 0; boolean newList = false; CTR[] rArray = paragraph.getRArray(); - for (int runPos=startRun; runPos=startText){ - String candidate = ((CTText)o).getStringValue(); - if(runPos==startRun) - charPos= startChar; + if (o instanceof CTText) { + if (textPos >= startText) { + String candidate = ((CTText) o).getStringValue(); + if (runPos == startRun) + charPos = startChar; else charPos = 0; - - for(; charPos= 0 && pos < paragraph.sizeOfRArray()) { // Remove the run from our high level lists XWPFRun run = runs.get(pos); @@ -1468,23 +1483,24 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * returns the type of the BodyElement Paragraph + * * @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType() */ public BodyElementType getElementType() { return BodyElementType.PARAGRAPH; } - public IBody getBody() - { + public IBody getBody() { return part; } /** * returns the part of the bodyElement + * * @see org.apache.poi.xwpf.usermodel.IBody#getPart() */ public POIXMLDocumentPart getPart() { - if(part != null){ + if (part != null) { return part.getPart(); } return null; @@ -1492,7 +1508,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * returns the partType of the bodyPart which owns the bodyElement - * + * * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() */ public BodyType getPartType() { @@ -1501,7 +1517,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * adds a new Run to the Paragraph - * + * * @param r */ public void addRun(XWPFRun r) { @@ -1512,7 +1528,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para /** * return the XWPFRun-Element which owns the CTR run-Element - * + * * @param r */ public XWPFRun getRun(CTR r) { diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPicture.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPicture.java index eba552cc28..c69e8dd1b7 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPicture.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPicture.java @@ -28,51 +28,51 @@ import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; public class XWPFPicture { private CTPicture ctPic; - private String description; - private XWPFRun run; - - public XWPFPicture(CTPicture ctPic, XWPFRun run){ - this.run = run; - this.ctPic = ctPic; - description = ctPic.getNvPicPr().getCNvPr().getDescr(); + private String description; + private XWPFRun run; + + public XWPFPicture(CTPicture ctPic, XWPFRun run) { + this.run = run; + this.ctPic = ctPic; + description = ctPic.getNvPicPr().getCNvPr().getDescr(); } - - /** - * Link Picture with PictureData - * @param rel - */ - public void setPictureReference(PackageRelationship rel){ - ctPic.getBlipFill().getBlip().setEmbed(rel.getId()); - } - + + /** + * Link Picture with PictureData + * + * @param rel + */ + public void setPictureReference(PackageRelationship rel) { + ctPic.getBlipFill().getBlip().setEmbed(rel.getId()); + } + /** * Return the underlying CTPicture bean that holds all properties for this picture - * - * @return the underlying CTPicture bean - */ - public CTPicture getCTPicture(){ - return ctPic; - } - + * + * @return the underlying CTPicture bean + */ + public CTPicture getCTPicture() { + return ctPic; + } + /** - * Get the PictureData of the Picture, if present. - * Note - not all kinds of picture have data - */ - public XWPFPictureData getPictureData(){ - CTBlipFillProperties blipProps = ctPic.getBlipFill(); - - if(blipProps == null || !blipProps.isSetBlip()) { - // return null if Blip data is missing - return null; - } - - String blipId = blipProps.getBlip().getEmbed(); - POIXMLDocumentPart part = run.getParent().getPart(); - if (part != null) - { - POIXMLDocumentPart relatedPart = part.getRelationById(blipId); - if (relatedPart instanceof XWPFPictureData) { - return (XWPFPictureData) relatedPart; + * Get the PictureData of the Picture, if present. + * Note - not all kinds of picture have data + */ + public XWPFPictureData getPictureData() { + CTBlipFillProperties blipProps = ctPic.getBlipFill(); + + if (blipProps == null || !blipProps.isSetBlip()) { + // return null if Blip data is missing + return null; + } + + String blipId = blipProps.getBlip().getEmbed(); + POIXMLDocumentPart part = run.getParent().getPart(); + if (part != null) { + POIXMLDocumentPart relatedPart = part.getRelationById(blipId); + if (relatedPart instanceof XWPFPictureData) { + return (XWPFPictureData) relatedPart; } } return null; diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPictureData.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPictureData.java index d7f2253586..d685aefca0 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPictureData.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFPictureData.java @@ -40,12 +40,13 @@ import org.apache.poi.util.IOUtils; public class XWPFPictureData extends POIXMLDocumentPart { /** - * Relationships for each known picture type - */ - protected static final POIXMLRelation[] RELATIONS; - static { - RELATIONS = new POIXMLRelation[13]; - RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF; + * Relationships for each known picture type + */ + protected static final POIXMLRelation[] RELATIONS; + + static { + RELATIONS = new POIXMLRelation[13]; + RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF; RELATIONS[Document.PICTURE_TYPE_WMF] = XWPFRelation.IMAGE_WMF; RELATIONS[Document.PICTURE_TYPE_PICT] = XWPFRelation.IMAGE_PICT; RELATIONS[Document.PICTURE_TYPE_JPEG] = XWPFRelation.IMAGE_JPEG; @@ -59,24 +60,23 @@ public class XWPFPictureData extends POIXMLDocumentPart { } private Long checksum = null; - - /** - * Create a new XWPFGraphicData node - * - */ - protected XWPFPictureData() { - super(); + + /** + * Create a new XWPFGraphicData node + */ + protected XWPFPictureData() { + super(); } /** * Construct XWPFPictureData from a package part - * - * @param part the package part holding the drawing data, - * @param rel the package relationship holding this drawing, - * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/image - */ - public XWPFPictureData(PackagePart part, PackageRelationship rel) { - super(part, rel); + * + * @param part the package part holding the drawing data, + * @param rel the package relationship holding this drawing, + * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/image + */ + public XWPFPictureData(PackagePart part, PackageRelationship rel) { + super(part, rel); } @Override @@ -91,12 +91,13 @@ public class XWPFPictureData extends POIXMLDocumentPart { * You can grab the picture data directly from the underlying package part as follows: *
    * - * InputStream is = getPackagePart().getInputStream(); - * - *

    - * @return the Picture data. - */ - public byte[] getData() { + * InputStream is = getPackagePart().getInputStream(); + * + *

    + * + * @return the Picture data. + */ + public byte[] getData() { try { return IOUtils.toByteArray(getPackagePart().getInputStream()); } catch (IOException e) { @@ -115,21 +116,22 @@ public class XWPFPictureData extends POIXMLDocumentPart { return null; return name.substring(name.lastIndexOf('/') + 1); } - - /** - * Suggests a file extension for this image. - * @return the file extension. - */ - public String suggestFileExtension() { + + /** + * Suggests a file extension for this image. + * + * @return the file extension. + */ + public String suggestFileExtension() { return getPackagePart().getPartName().getExtension(); } - - /** - * Return an integer constant that specifies type of this picture - * - * @return an integer constant that specifies type of this picture - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF + + /** + * Return an integer constant that specifies type of this picture + * + * @return an integer constant that specifies type of this picture + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG @@ -217,13 +219,13 @@ public class XWPFPictureData extends POIXMLDocumentPart { if (!ownPackage.equals(foreignPackage)) { return false; - } - } - } - - Long foreignChecksum = picData.getChecksum(); - Long localChecksum = getChecksum(); - + } + } + } + + Long foreignChecksum = picData.getChecksum(); + Long localChecksum = getChecksum(); + if (!(localChecksum.equals(foreignChecksum))) { return false; } @@ -233,13 +235,13 @@ public class XWPFPictureData extends POIXMLDocumentPart { @Override public int hashCode() { return getChecksum().hashCode(); - } - - /** - * *PictureData objects store the actual content in the part directly without keeping a - * copy like all others therefore we need to handle them differently. - */ - @Override + } + + /** + * *PictureData objects store the actual content in the part directly without keeping a + * copy like all others therefore we need to handle them differently. + */ + @Override protected void prepareForCommit() { // do not clear the part here } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java index 06642faaab..fae051e74f 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java @@ -33,7 +33,6 @@ public final class XWPFRelation extends POIXMLRelation { */ protected static final Map _table = new HashMap(); - public static final XWPFRelation DOCUMENT = new XWPFRelation( "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", @@ -41,10 +40,10 @@ public final class XWPFRelation extends POIXMLRelation { null ); public static final XWPFRelation TEMPLATE = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", - "/word/document.xml", - null + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", + "/word/document.xml", + null ); public static final XWPFRelation MACRO_DOCUMENT = new XWPFRelation( "application/vnd.ms-word.document.macroEnabled.main+xml", @@ -64,12 +63,11 @@ public final class XWPFRelation extends POIXMLRelation { "/word/glossary/document.xml", null ); - public static final XWPFRelation NUMBERING = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", - "/word/numbering.xml", - XWPFNumbering.class + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", + "/word/numbering.xml", + XWPFNumbering.class ); public static final XWPFRelation FONT_TABLE = new XWPFRelation( "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", @@ -126,10 +124,10 @@ public final class XWPFRelation extends POIXMLRelation { null ); public static final XWPFRelation FOOTNOTE = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes", - "/word/footnotes.xml", - XWPFFootnotes.class + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes", + "/word/footnotes.xml", + XWPFFootnotes.class ); public static final XWPFRelation ENDNOTE = new XWPFRelation( null, @@ -137,52 +135,51 @@ public final class XWPFRelation extends POIXMLRelation { null, null ); - /** * Supported image formats */ public static final XWPFRelation IMAGE_EMF = new XWPFRelation( - "image/x-emf", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.emf", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_WMF = new XWPFRelation( - "image/x-wmf", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.wmf", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_PICT = new XWPFRelation( - "image/pict", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.pict", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_JPEG = new XWPFRelation( - "image/jpeg", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.jpeg", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_PNG = new XWPFRelation( - "image/png", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.png", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_DIB = new XWPFRelation( - "image/dib", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.dib", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_GIF = new XWPFRelation( - "image/gif", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.gif", - XWPFPictureData.class - ); + "image/x-emf", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.emf", + XWPFPictureData.class + ); + public static final XWPFRelation IMAGE_WMF = new XWPFRelation( + "image/x-wmf", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.wmf", + XWPFPictureData.class + ); + public static final XWPFRelation IMAGE_PICT = new XWPFRelation( + "image/pict", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.pict", + XWPFPictureData.class + ); + public static final XWPFRelation IMAGE_JPEG = new XWPFRelation( + "image/jpeg", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.jpeg", + XWPFPictureData.class + ); + public static final XWPFRelation IMAGE_PNG = new XWPFRelation( + "image/png", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.png", + XWPFPictureData.class + ); + public static final XWPFRelation IMAGE_DIB = new XWPFRelation( + "image/dib", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.dib", + XWPFPictureData.class + ); + public static final XWPFRelation IMAGE_GIF = new XWPFRelation( + "image/gif", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "/word/media/image#.gif", + XWPFPictureData.class + ); public static final XWPFRelation IMAGE_TIFF = new XWPFRelation( "image/tiff", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", @@ -207,14 +204,12 @@ public final class XWPFRelation extends POIXMLRelation { "/word/media/image#.wpg", XWPFPictureData.class ); - - public static final XWPFRelation IMAGES = new XWPFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - null, - null - ); - + public static final XWPFRelation IMAGES = new XWPFRelation( + null, + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + null, + null + ); private XWPFRelation(String type, String rel, String defaultName, Class cls) { super(type, rel, defaultName, cls); diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java index 07debb98c6..1c14bb274a 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java @@ -32,19 +32,52 @@ import org.apache.poi.wp.usermodel.CharacterRun; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlString; -import org.apache.xmlbeans.XmlToken; -import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; -import org.openxmlformats.schemas.drawingml.x2006.main.*; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; - +import org.apache.xmlbeans.XmlString; +import org.apache.xmlbeans.XmlToken; +import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; +import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; +import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; +import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; +import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; +import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; +import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; +import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; +import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; +import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; +import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; +import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTEmpty; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFFCheckBox; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHpsMeasure; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPTab; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedHpsMeasure; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedTwipsMeasure; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTUnderline; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalAlignRun; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; + /** * XWPFRun object defines a region of text with a common set of properties */ @@ -52,22 +85,12 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { private CTR run; private String pictureText; private IRunBody parent; - private List pictures; - - /** - * @see [MS-OI29500] Run Fonts - */ - public static enum FontCharRange { - ascii /* char 0-127 */, - cs /* complex symbol */, - eastAsia /* east asia */, - hAnsi /* high ansi */ - }; - - /** - * @param r the CTR bean which holds the run attributes - * @param p the parent paragraph - */ + private List pictures; + + /** + * @param r the CTR bean which holds the run attributes + * @param p the parent paragraph + */ @SuppressWarnings("deprecation") public XWPFRun(CTR r, IRunBody p) { this.run = r; @@ -92,13 +115,13 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { // Look for any text in any of our pictures or drawings StringBuilder text = new StringBuilder(); - List pictTextObjs = new ArrayList(); - pictTextObjs.addAll(Arrays.asList(r.getPictArray())); - pictTextObjs.addAll(Arrays.asList(r.getDrawingArray())); - for(XmlObject o : pictTextObjs) { - XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t"); - for (XmlObject t : ts) { - NodeList kids = t.getDomNode().getChildNodes(); + List pictTextObjs = new ArrayList(); + pictTextObjs.addAll(Arrays.asList(r.getPictArray())); + pictTextObjs.addAll(Arrays.asList(r.getDrawingArray())); + for (XmlObject o : pictTextObjs) { + XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t"); + for (XmlObject t : ts) { + NodeList kids = t.getDomNode().getChildNodes(); for (int n = 0; n < kids.getLength(); n++) { if (kids.item(n) instanceof Text) { if (text.length() > 0) @@ -110,112 +133,134 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { } pictureText = text.toString(); - // Do we have any embedded pictures? - // (They're a different CTPicture, under the drawingml namespace) - pictures = new ArrayList(); - for(XmlObject o : pictTextObjs) { - for(CTPicture pict : getCTPictures(o)) { - XWPFPicture picture = new XWPFPicture(pict, this); - pictures.add(picture); - } - } - } - /** - * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)} - */ - public XWPFRun(CTR r, XWPFParagraph p) { - this(r, (IRunBody)p); - } - - private List getCTPictures(XmlObject o) { - List pictures = new ArrayList(); - XmlObject[] picts = o.selectPath("declare namespace pic='"+CTPicture.type.getName().getNamespaceURI()+"' .//pic:pic"); - for(XmlObject pict : picts) { - if(pict instanceof XmlAnyTypeImpl) { - // Pesky XmlBeans bug - see Bugzilla #49934 - try { - pict = CTPicture.Factory.parse( pict.toString() ); - } catch(XmlException e) { - throw new POIXMLException(e); - } - } - if(pict instanceof CTPicture) { - pictures.add((CTPicture)pict); - } - } - return pictures; + // Do we have any embedded pictures? + // (They're a different CTPicture, under the drawingml namespace) + pictures = new ArrayList(); + for (XmlObject o : pictTextObjs) { + for (CTPicture pict : getCTPictures(o)) { + XWPFPicture picture = new XWPFPicture(pict, this); + pictures.add(picture); + } + } + } + + ; + + /** + * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)} + */ + public XWPFRun(CTR r, XWPFParagraph p) { + this(r, (IRunBody) p); + } + + /** + * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces + * + * @param xs the string to check + */ + static void preserveSpaces(XmlString xs) { + String text = xs.getStringValue(); + if (text != null && (text.startsWith(" ") || text.endsWith(" "))) { + XmlCursor c = xs.newCursor(); + c.toNextToken(); + c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve"); + c.dispose(); + } + } + + private List getCTPictures(XmlObject o) { + List pictures = new ArrayList(); + XmlObject[] picts = o.selectPath("declare namespace pic='" + CTPicture.type.getName().getNamespaceURI() + "' .//pic:pic"); + for (XmlObject pict : picts) { + if (pict instanceof XmlAnyTypeImpl) { + // Pesky XmlBeans bug - see Bugzilla #49934 + try { + pict = CTPicture.Factory.parse(pict.toString()); + } catch (XmlException e) { + throw new POIXMLException(e); + } + } + if (pict instanceof CTPicture) { + pictures.add((CTPicture) pict); + } + } + return pictures; } - - /** - * Get the currently used CTR object - * @return ctr object - */ - @Internal + + /** + * Get the currently used CTR object + * + * @return ctr object + */ + @Internal public CTR getCTR() { return run; } - - /** - * Get the currently referenced paragraph/SDT object - * @return current parent - */ - public IRunBody getParent() { - return parent; - } - /** - * Get the currently referenced paragraph, or null if a SDT object - * @deprecated use {@link XWPFRun#getParent()} instead - */ - public XWPFParagraph getParagraph() { - if (parent instanceof XWPFParagraph) - return (XWPFParagraph)parent; - return null; - } - - /** - * @return The {@link XWPFDocument} instance, this run belongs to, or - * null if parent structure (paragraph > document) is not properly set. - */ - public XWPFDocument getDocument() { - if (parent != null) { + + /** + * Get the currently referenced paragraph/SDT object + * + * @return current parent + */ + public IRunBody getParent() { + return parent; + } + + /** + * Get the currently referenced paragraph, or null if a SDT object + * + * @deprecated use {@link XWPFRun#getParent()} instead + */ + public XWPFParagraph getParagraph() { + if (parent instanceof XWPFParagraph) + return (XWPFParagraph) parent; + return null; + } + + /** + * @return The {@link XWPFDocument} instance, this run belongs to, or + * null if parent structure (paragraph > document) is not properly set. + */ + public XWPFDocument getDocument() { + if (parent != null) { return parent.getDocument(); } return null; } /** - * For isBold, isItalic etc - */ - private boolean isCTOnOff(CTOnOff onoff) { - if(! onoff.isSetVal()) - return true; - if(onoff.getVal() == STOnOff.ON) - return true; - if(onoff.getVal() == STOnOff.TRUE) - return true; - return false; - } + * For isBold, isItalic etc + */ + private boolean isCTOnOff(CTOnOff onoff) { + if (!onoff.isSetVal()) + return true; + if (onoff.getVal() == STOnOff.ON) + return true; + if (onoff.getVal() == STOnOff.TRUE) + return true; + return false; + } /** * Whether the bold property shall be applied to all non-complex script * characters in the contents of this run when displayed in a document * * @return true if the bold property is applied - */ - public boolean isBold() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetB()) { - return false; - } - return isCTOnOff(pr.getB()); + */ + public boolean isBold() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetB()) { + return false; + } + return isCTOnOff(pr.getB()); } - - /** - * Whether the bold property shall be applied to all non-complex script - * characters in the contents of this run when displayed in a document. - *

    - * This formatting property is a toggle property, which specifies that its - * behavior differs between its use within a style definition and its use as + + /** + * Whether the bold property shall be applied to all non-complex script + * characters in the contents of this run when displayed in a document. + *

    + * This formatting property is a toggle property, which specifies that its + * behavior differs between its use within a style definition and its use as * direct formatting. When used as part of a style definition, setting this * property shall toggle the current state of that property as specified up * to this point in the hierarchy (i.e. applied to not applied, and vice @@ -241,25 +286,26 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { } /** - * Get text color. The returned value is a string in the hex form "RRGGBB". - */ - public String getColor() { - String color = null; - if (run.isSetRPr()) { - CTRPr pr = run.getRPr(); - if (pr.isSetColor()) { - CTColor clr = pr.getColor(); - color = clr.xgetVal().getStringValue(); - } - } - return color; - } - - /** - * Set text color. - * @param rgbStr - the desired color, in the hex form "RRGGBB". - */ - public void setColor(String rgbStr) { + * Get text color. The returned value is a string in the hex form "RRGGBB". + */ + public String getColor() { + String color = null; + if (run.isSetRPr()) { + CTRPr pr = run.getRPr(); + if (pr.isSetColor()) { + CTColor clr = pr.getColor(); + color = clr.xgetVal().getStringValue(); + } + } + return color; + } + + /** + * Set text color. + * + * @param rgbStr - the desired color, in the hex form "RRGGBB". + */ + public void setColor(String rgbStr) { CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTColor color = pr.isSetColor() ? pr.getColor() : pr.addNewColor(); color.setVal(rgbStr); @@ -285,23 +331,24 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { /** * Sets the text of this text run * - * @param value the literal text which shall be displayed in the document - */ - public void setText(String value) { - setText(value,run.sizeOfTArray()); - } - - /** - * Sets the text of this text run in the - * - * @param value the literal text which shall be displayed in the document - * @param pos - position in the text array (NB: 0 based) - */ - public void setText(String value, int pos) { - if(pos > run.sizeOfTArray()) throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)"); - CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT(); - t.setStringValue(value); - preserveSpaces(t); + * @param value the literal text which shall be displayed in the document + */ + public void setText(String value) { + setText(value, run.sizeOfTArray()); + } + + /** + * Sets the text of this text run in the + * + * @param value the literal text which shall be displayed in the document + * @param pos - position in the text array (NB: 0 based) + */ + public void setText(String value, int pos) { + if (pos > run.sizeOfTArray()) + throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)"); + CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT(); + t.setStringValue(value); + preserveSpaces(t); } /** @@ -309,13 +356,13 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { * characters in the contents of this run when displayed in a document. * * @return true if the italic property is applied - */ - public boolean isItalic() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetI()) - return false; - return isCTOnOff(pr.getI()); - } + */ + public boolean isItalic() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetI()) + return false; + return isCTOnOff(pr.getI()); + } /** * Whether the bold property shall be applied to all non-complex script @@ -354,14 +401,14 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { * * @return the Underline pattern applyed to this run * @see UnderlinePatterns - */ - public UnderlinePatterns getUnderline() { - CTRPr pr = run.getRPr(); - return (pr != null && pr.isSetU() && pr.getU().getVal() != null) - ? UnderlinePatterns.valueOf(pr.getU().getVal().intValue()) - : UnderlinePatterns.NONE; - } - + */ + public UnderlinePatterns getUnderline() { + CTRPr pr = run.getRPr(); + return (pr != null && pr.isSetU() && pr.getU().getVal() != null) + ? UnderlinePatterns.valueOf(pr.getU().getVal().intValue()) + : UnderlinePatterns.NONE; + } + /** * Specifies that the contents of this run should be displayed along with an * underline appearing directly below the character heigh @@ -388,32 +435,16 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { * horizontal line through the center of the line. * * @return true if the strike property is applied - */ - public boolean isStrikeThrough() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetStrike()) - return false; - return isCTOnOff(pr.getStrike()); - } - @Deprecated - public boolean isStrike() { - return isStrikeThrough(); - } - /** - * Specifies that the contents of this run shall be displayed with a double - * horizontal line through the center of the line. - * - * @return true if the double strike property is applied - */ - public boolean isDoubleStrikeThrough() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetDstrike()) - return false; - return isCTOnOff(pr.getDstrike()); - } - - /** - * Specifies that the contents of this run shall be displayed with a single + */ + public boolean isStrikeThrough() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetStrike()) + return false; + return isCTOnOff(pr.getStrike()); + } + + /** + * Specifies that the contents of this run shall be displayed with a single * horizontal line through the center of the line. *

    * This formatting property is a toggle property, which specifies that its @@ -438,86 +469,113 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { */ public void setStrikeThrough(boolean value) { CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike(); - strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - @Deprecated - public void setStrike(boolean value) { - setStrikeThrough(value); - } - /** - * Specifies that the contents of this run shall be displayed with a - * double horizontal line through the center of the line. - * @see #setStrikeThrough(boolean) for the rules about this - */ - public void setDoubleStrikethrough(boolean value) { + CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike(); + strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); + } + + @Deprecated + public boolean isStrike() { + return isStrikeThrough(); + } + + @Deprecated + public void setStrike(boolean value) { + setStrikeThrough(value); + } + + /** + * Specifies that the contents of this run shall be displayed with a double + * horizontal line through the center of the line. + * + * @return true if the double strike property is applied + */ + public boolean isDoubleStrikeThrough() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetDstrike()) + return false; + return isCTOnOff(pr.getDstrike()); + } + + /** + * Specifies that the contents of this run shall be displayed with a + * double horizontal line through the center of the line. + * + * @see #setStrikeThrough(boolean) for the rules about this + */ + public void setDoubleStrikethrough(boolean value) { CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTOnOff dstrike = pr.isSetDstrike() ? pr.getDstrike() : pr.addNewDstrike(); dstrike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); } - - public boolean isSmallCaps() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetSmallCaps()) - return false; - return isCTOnOff(pr.getSmallCaps()); - } - public void setSmallCaps(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps(); - caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - public boolean isCapitalized() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetCaps()) - return false; - return isCTOnOff(pr.getCaps()); - } - public void setCapitalized(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps(); - caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isShadowed() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetShadow()) - return false; - return isCTOnOff(pr.getShadow()); - } - public void setShadow(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow(); - shadow.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isImprinted() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetImprint()) - return false; - return isCTOnOff(pr.getImprint()); - } - public void setImprinted(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint(); - imprinted.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isEmbossed() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetEmboss()) - return false; - return isCTOnOff(pr.getEmboss()); - } - public void setEmbossed(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss(); - emboss.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - /** - * Specifies the alignment which shall be applied to the contents of this - * run in relation to the default appearance of the run's text. + + public boolean isSmallCaps() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetSmallCaps()) + return false; + return isCTOnOff(pr.getSmallCaps()); + } + + public void setSmallCaps(boolean value) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps(); + caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); + } + + public boolean isCapitalized() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetCaps()) + return false; + return isCTOnOff(pr.getCaps()); + } + + public void setCapitalized(boolean value) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps(); + caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); + } + + public boolean isShadowed() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetShadow()) + return false; + return isCTOnOff(pr.getShadow()); + } + + public void setShadow(boolean value) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow(); + shadow.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); + } + + public boolean isImprinted() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetImprint()) + return false; + return isCTOnOff(pr.getImprint()); + } + + public void setImprinted(boolean value) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint(); + imprinted.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); + } + + public boolean isEmbossed() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetEmboss()) + return false; + return isCTOnOff(pr.getEmboss()); + } + + public void setEmbossed(boolean value) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss(); + emboss.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); + } + + /** + * Specifies the alignment which shall be applied to the contents of this + * run in relation to the default appearance of the run's text. * This allows the text to be repositioned as subscript or superscript without * altering the font size of the run properties. * @@ -550,105 +608,106 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { CTVerticalAlignRun ctValign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign(); ctValign.setVal(STVerticalAlignRun.Enum.forInt(valign.getValue())); } - - public int getKerning() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetKern()) - return 0; - return pr.getKern().getVal().intValue(); - } - public void setKerning(int kern) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern(); - kernmes.setVal(BigInteger.valueOf(kern)); - } - - public int getCharacterSpacing() { - CTRPr pr = run.getRPr(); - if(pr == null || !pr.isSetSpacing()) - return 0; - return pr.getSpacing().getVal().intValue(); - } - public void setCharacterSpacing(int twips) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing(); - spc.setVal(BigInteger.valueOf(twips)); - } - - /** - * Gets the fonts which shall be used to display the text contents of - * this run. Specifies a font which shall be used to format all characters + + public int getKerning() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetKern()) + return 0; + return pr.getKern().getVal().intValue(); + } + + public void setKerning(int kern) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern(); + kernmes.setVal(BigInteger.valueOf(kern)); + } + + public int getCharacterSpacing() { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetSpacing()) + return 0; + return pr.getSpacing().getVal().intValue(); + } + + public void setCharacterSpacing(int twips) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing(); + spc.setVal(BigInteger.valueOf(twips)); + } + + /** + * Gets the fonts which shall be used to display the text contents of + * this run. Specifies a font which shall be used to format all characters * in the ASCII range (0 - 127) within the parent run * * @return a string representing the font family */ - public String getFontFamily() { - return getFontFamily(null); - } - /** - * Alias for {@link #getFontFamily()} - */ - public String getFontName() { + public String getFontFamily() { + return getFontFamily(null); + } + + /** + * Specifies the fonts which shall be used to display the text contents of + * this run. Specifies a font which shall be used to format all characters + * in the ASCII range (0 - 127) within the parent run. + *

    + * Also sets the other font ranges, if they haven't been set before + * + * @param fontFamily + * @see FontCharRange + */ + public void setFontFamily(String fontFamily) { + setFontFamily(fontFamily, null); + } + + /** + * Alias for {@link #getFontFamily()} + */ + public String getFontName() { return getFontFamily(); } /** * Gets the font family for the specified font char range. - * If fcr is null, the font char range "ascii" is used - * - * @param fcr the font char range, defaults to "ansi" - * @return a string representing the font famil - */ - public String getFontFamily(FontCharRange fcr) { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetRFonts()) return null; - - CTFonts fonts = pr.getRFonts(); - switch (fcr == null ? FontCharRange.ascii : fcr) { - default: - case ascii: - return fonts.getAscii(); - case cs: - return fonts.getCs(); - case eastAsia: - return fonts.getEastAsia(); - case hAnsi: - return fonts.getHAnsi(); - } - } - - - /** - * Specifies the fonts which shall be used to display the text contents of - * this run. Specifies a font which shall be used to format all characters - * in the ASCII range (0 - 127) within the parent run. - * - * Also sets the other font ranges, if they haven't been set before - * - * @param fontFamily - * - * @see FontCharRange - */ - public void setFontFamily(String fontFamily) { - setFontFamily(fontFamily, null); - } - - /** - * Specifies the fonts which shall be used to display the text contents of - * this run. The default handling for fcr == null is to overwrite the - * ascii font char range with the given font family and also set all not - * specified font ranges - * - * @param fontFamily - * @param fcr FontCharRange or null for default handling - */ - public void setFontFamily(String fontFamily, FontCharRange fcr) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts(); - - if (fcr == null) { - fonts.setAscii(fontFamily); - if (!fonts.isSetHAnsi()) { + * If fcr is null, the font char range "ascii" is used + * + * @param fcr the font char range, defaults to "ansi" + * @return a string representing the font famil + */ + public String getFontFamily(FontCharRange fcr) { + CTRPr pr = run.getRPr(); + if (pr == null || !pr.isSetRFonts()) return null; + + CTFonts fonts = pr.getRFonts(); + switch (fcr == null ? FontCharRange.ascii : fcr) { + default: + case ascii: + return fonts.getAscii(); + case cs: + return fonts.getCs(); + case eastAsia: + return fonts.getEastAsia(); + case hAnsi: + return fonts.getHAnsi(); + } + } + + /** + * Specifies the fonts which shall be used to display the text contents of + * this run. The default handling for fcr == null is to overwrite the + * ascii font char range with the given font family and also set all not + * specified font ranges + * + * @param fontFamily + * @param fcr FontCharRange or null for default handling + */ + public void setFontFamily(String fontFamily, FontCharRange fcr) { + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts(); + + if (fcr == null) { + fonts.setAscii(fontFamily); + if (!fonts.isSetHAnsi()) { fonts.setHAnsi(fontFamily); } if (!fonts.isSetCs()) { @@ -656,24 +715,24 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { } if (!fonts.isSetEastAsia()) { fonts.setEastAsia(fontFamily); - } - } else { - switch (fcr) { - case ascii: - fonts.setAscii(fontFamily); - break; - case cs: - fonts.setCs(fontFamily); - break; - case eastAsia: - fonts.setEastAsia(fontFamily); - break; - case hAnsi: - fonts.setHAnsi(fontFamily); - break; - } - } - } + } + } else { + switch (fcr) { + case ascii: + fonts.setAscii(fontFamily); + break; + case cs: + fonts.setCs(fontFamily); + break; + case eastAsia: + fonts.setEastAsia(fontFamily); + break; + case hAnsi: + fonts.setHAnsi(fontFamily); + break; + } + } + } /** * Specifies the font size which shall be applied to all non complex script @@ -696,13 +755,13 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { * be used for non complex script characters. *

    * - * @param size - */ - public void setFontSize(int size) { - BigInteger bint=new BigInteger(""+size); - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz(); - ctSize.setVal(bint.multiply(new BigInteger("2"))); + * @param size + */ + public void setFontSize(int size) { + BigInteger bint = new BigInteger("" + size); + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz(); + ctSize.setVal(bint.multiply(new BigInteger("2"))); } /** @@ -739,52 +798,54 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { * contents of this run. *

    * - * @param val - */ - public void setTextPosition(int val) { - BigInteger bint=new BigInteger(""+val); - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition(); - position.setVal(bint); + * @param val + */ + public void setTextPosition(int val) { + BigInteger bint = new BigInteger("" + val); + CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); + CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition(); + position.setVal(bint); + } + + /** + * + */ + public void removeBreak() { + // TODO } - - /** - * - */ - public void removeBreak() { - // TODO - } - - /** - * Specifies that a break shall be placed at the current location in the run - * content. - * A break is a special character which is used to override the - * normal line breaking that would be performed based on the normal layout - * of the document's contents. - * @see #addCarriageReturn() - */ - public void addBreak() { - run.addNewBr(); - } - - /** - * Specifies that a break shall be placed at the current location in the run + + /** + * Specifies that a break shall be placed at the current location in the run + * content. + * A break is a special character which is used to override the + * normal line breaking that would be performed based on the normal layout + * of the document's contents. + * + * @see #addCarriageReturn() + */ + public void addBreak() { + run.addNewBr(); + } + + /** + * Specifies that a break shall be placed at the current location in the run * content. * A break is a special character which is used to override the * normal line breaking that would be performed based on the normal layout * of the document's contents. *

    * The behavior of this break character (the - * location where text shall be restarted after this break) shall be - * determined by its type values. - *

    - * @see BreakType - */ - public void addBreak(BreakType type){ - CTBr br=run.addNewBr(); - br.setType(STBrType.Enum.forInt(type.getValue())); - } - + * location where text shall be restarted after this break) shall be + * determined by its type values. + *

    + * + * @see BreakType + */ + public void addBreak(BreakType type) { + CTBr br = run.addNewBr(); + br.setType(STBrType.Enum.forInt(type.getValue())); + } + /** * Specifies that a break shall be placed at the current location in the run * content. A break is a special character which is used to override the @@ -792,31 +853,32 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { * of the document's contents. *

    * The behavior of this break character (the - * location where text shall be restarted after this break) shall be - * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values. - *

    - * @see BreakClear - */ - public void addBreak(BreakClear clear){ - CTBr br=run.addNewBr(); - br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue())); - br.setClear(STBrClear.Enum.forInt(clear.getValue())); + * location where text shall be restarted after this break) shall be + * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values. + *

    + * + * @see BreakClear + */ + public void addBreak(BreakClear clear) { + CTBr br = run.addNewBr(); + br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue())); + br.setClear(STBrClear.Enum.forInt(clear.getValue())); + } + + /** + * Specifies that a tab shall be placed at the current location in + * the run content. + */ + public void addTab() { + run.addNewTab(); } - - /** - * Specifies that a tab shall be placed at the current location in - * the run content. - */ - public void addTab() { - run.addNewTab(); - } - - public void removeTab() { - //TODO - } - - /** - * Specifies that a carriage return shall be placed at the + + public void removeTab() { + //TODO + } + + /** + * Specifies that a carriage return shall be placed at the * current location in the run content. * A carriage return is used to end the current line of text in * Wordprocess. @@ -830,34 +892,33 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { public void addCarriageReturn() { run.addNewCr(); } - - public void removeCarriageReturn() { - //TODO - } - - /** - * Adds a picture to the run. This method handles - * attaching the picture data to the overall file. - * - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB - * - * @param pictureData The raw picture data - * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG} - * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} - * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException - * @throws IOException - */ - public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height) - throws InvalidFormatException, IOException { - XWPFDocument doc = parent.getDocument(); - - // Add the picture + relationship + + public void removeCarriageReturn() { + //TODO + } + + /** + * Adds a picture to the run. This method handles + * attaching the picture data to the overall file. + * + * @param pictureData The raw picture data + * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG} + * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} + * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} + * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException + * @throws IOException + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG + * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB + */ + public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height) + throws InvalidFormatException, IOException { + XWPFDocument doc = parent.getDocument(); + + // Add the picture + relationship String relationId = doc.addPictureData(pictureData, pictureType); XWPFPictureData picData = (XWPFPictureData) doc.getRelationById(relationId); @@ -865,18 +926,18 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { try { CTDrawing drawing = run.addNewDrawing(); CTInline inline = drawing.addNewInline(); - - // Do the fiddly namespace bits on the inline - // (We need full control of what goes where and as what) - String xml = - "" + - "" + - "" + - "" + - ""; - inline.set(XmlToken.Factory.parse(xml)); - - // Setup the inline + + // Do the fiddly namespace bits on the inline + // (We need full control of what goes where and as what) + String xml = + "" + + "" + + "" + + "" + + ""; + inline.set(XmlToken.Factory.parse(xml)); + + // Setup the inline inline.setDistT(0); inline.setDistR(0); inline.setDistB(0); @@ -910,13 +971,13 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { CTNonVisualPictureProperties cNvPicPr = nvPicPr.addNewCNvPicPr(); cNvPicPr.addNewPicLocks().setNoChangeAspect(true); - - CTBlipFillProperties blipFill = pic.addNewBlipFill(); - CTBlip blip = blipFill.addNewBlip(); - blip.setEmbed( picData.getPackageRelationship().getId() ); - blipFill.addNewStretch().addNewFillRect(); - - CTShapeProperties spPr = pic.addNewSpPr(); + + CTBlipFillProperties blipFill = pic.addNewBlipFill(); + CTBlip blip = blipFill.addNewBlip(); + blip.setEmbed(picData.getPackageRelationship().getId()); + blipFill.addNewStretch().addNewFillRect(); + + CTShapeProperties spPr = pic.addNewSpPr(); CTTransform2D xfrm = spPr.addNewXfrm(); CTPoint2D off = xfrm.addNewOff(); @@ -932,50 +993,36 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { prstGeom.addNewAvLst(); // Finish up - XWPFPicture xwpfPicture = new XWPFPicture(pic, this); - pictures.add(xwpfPicture); - return xwpfPicture; - } catch(XmlException e) { - throw new IllegalStateException(e); - } - } - - /** - * Returns the embedded pictures of the run. These - * are pictures which reference an external, - * embedded picture image such as a .png or .jpg - */ - public List getEmbeddedPictures() { - return pictures; - } - - /** - * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces - * - * @param xs the string to check - */ - static void preserveSpaces(XmlString xs) { - String text = xs.getStringValue(); - if (text != null && (text.startsWith(" ") || text.endsWith(" "))) { - XmlCursor c = xs.newCursor(); - c.toNextToken(); - c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve"); - c.dispose(); - } - } - - /** - * Returns the string version of the text - */ - public String toString() { - return text(); - } - /** - * Returns the string version of the text, with tabs and - * carriage returns in place of their xml equivalents. - */ - public String text() { - StringBuffer text = new StringBuffer(); + XWPFPicture xwpfPicture = new XWPFPicture(pic, this); + pictures.add(xwpfPicture); + return xwpfPicture; + } catch (XmlException e) { + throw new IllegalStateException(e); + } + } + + /** + * Returns the embedded pictures of the run. These + * are pictures which reference an external, + * embedded picture image such as a .png or .jpg + */ + public List getEmbeddedPictures() { + return pictures; + } + + /** + * Returns the string version of the text + */ + public String toString() { + return text(); + } + + /** + * Returns the string version of the text, with tabs and + * carriage returns in place of their xml equivalents. + */ + public String text() { + StringBuffer text = new StringBuffer(); // Grab the text and tabs of the text run // Do so in a way that preserves the ordering @@ -989,26 +1036,26 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { // come up as instances of CTText, but we don't want them // in the normal text output if (!"w:instrText".equals(tagName)) { - text.append(((CTText) o).getStringValue()); - } - } - - // Complex type evaluation (currently only for extraction of check boxes) - if(o instanceof CTFldChar) { - CTFldChar ctfldChar = ((CTFldChar)o); - if(ctfldChar.getFldCharType() == STFldCharType.BEGIN) { - if(ctfldChar.getFfData() != null) { - for(CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) { - if(checkBox.getDefault().getVal() == STOnOff.X_1) { - text.append("|X|"); - } else { - text.append("|_|"); - } - } - } - } - } - + text.append(((CTText) o).getStringValue()); + } + } + + // Complex type evaluation (currently only for extraction of check boxes) + if (o instanceof CTFldChar) { + CTFldChar ctfldChar = ((CTFldChar) o); + if (ctfldChar.getFldCharType() == STFldCharType.BEGIN) { + if (ctfldChar.getFfData() != null) { + for (CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) { + if (checkBox.getDefault().getVal() == STOnOff.X_1) { + text.append("|X|"); + } else { + text.append("|_|"); + } + } + } + } + } + if (o instanceof CTPTab) { text.append("\t"); } @@ -1030,23 +1077,33 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { } if ("w:cr".equals(tagName) || "cr".equals(tagName)) { text.append("\n"); - } - } - if (o instanceof CTFtnEdnRef) { - CTFtnEdnRef ftn = (CTFtnEdnRef)o; - String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ? - "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]"; - text.append(footnoteRef); - } - } - - c.dispose(); - - // Any picture text? - if(pictureText != null && pictureText.length() > 0) { - text.append("\n").append(pictureText); - } - - return text.toString(); - } -} + } + } + if (o instanceof CTFtnEdnRef) { + CTFtnEdnRef ftn = (CTFtnEdnRef) o; + String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ? + "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]"; + text.append(footnoteRef); + } + } + + c.dispose(); + + // Any picture text? + if (pictureText != null && pictureText.length() > 0) { + text.append("\n").append(pictureText); + } + + return text.toString(); + } + + /** + * @see [MS-OI29500] Run Fonts + */ + public static enum FontCharRange { + ascii /* char 0-127 */, + cs /* complex symbol */, + eastAsia /* east asia */, + hAnsi /* high ansi */ + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java index 4a51725b19..fd8389ef56 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java @@ -17,31 +17,30 @@ package org.apache.poi.xwpf.usermodel; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun; - -/** - * Experimental class to offer rudimentary read-only processing of - * of StructuredDocumentTags/ContentControl - * - * WARNING - APIs expected to change rapidly - * - */ -public class XWPFSDT extends AbstractXWPFSDT - implements IBodyElement, IRunBody, ISDTContents, IRunElement { - private final ISDTContent content; - - public XWPFSDT(CTSdtRun sdtRun, IBody part){ - super(sdtRun.getSdtPr(), part); - this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this); - } - - public XWPFSDT(CTSdtBlock block, IBody part){ - super(block.getSdtPr(), part); - this.content = new XWPFSDTContent( block.getSdtContent(), part, this); - } - - public ISDTContent getContent(){ - return content; - } - -} +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun; + +/** + * Experimental class to offer rudimentary read-only processing of + * of StructuredDocumentTags/ContentControl + *

    + * WARNING - APIs expected to change rapidly + */ +public class XWPFSDT extends AbstractXWPFSDT + implements IBodyElement, IRunBody, ISDTContents, IRunElement { + private final ISDTContent content; + + public XWPFSDT(CTSdtRun sdtRun, IBody part) { + super(sdtRun.getSdtPr(), part); + this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this); + } + + public XWPFSDT(CTSdtBlock block, IBody part) { + super(block.getSdtPr(), part); + this.content = new XWPFSDTContent(block.getSdtContent(), part, this); + } + + public ISDTContent getContent() { + return content; + } + +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java index 21cca3e7b2..fb40955efb 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java @@ -16,29 +16,28 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell; - -/** - * Experimental class to offer rudimentary read-only processing of - * of StructuredDocumentTags/ContentControl that can appear - * in a table row as if a table cell. - *

    - * These can contain one or more cells or other SDTs within them. - * - * WARNING - APIs expected to change rapidly - * - */ -public class XWPFSDTCell extends AbstractXWPFSDT implements ICell { - private final XWPFSDTContentCell cellContent; - - public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part){ - super(sdtCell.getSdtPr(), part); - cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part); - } - - @Override - public ISDTContent getContent(){ - return cellContent; - } - -} +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell; + +/** + * Experimental class to offer rudimentary read-only processing of + * of StructuredDocumentTags/ContentControl that can appear + * in a table row as if a table cell. + *

    + * These can contain one or more cells or other SDTs within them. + *

    + * WARNING - APIs expected to change rapidly + */ +public class XWPFSDTCell extends AbstractXWPFSDT implements ICell { + private final XWPFSDTContentCell cellContent; + + public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part) { + super(sdtCell.getSdtPr(), part); + cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part); + } + + @Override + public ISDTContent getContent() { + return cellContent; + } + +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java index 42c56b3773..6942aa749d 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java @@ -16,93 +16,91 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import java.util.ArrayList; -import java.util.List; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; - -/** - * Experimental class to offer rudimentary read-only processing of - * of the contentblock of an SDT/ContentControl. - * - * - * - * WARNING - APIs expected to change rapidly - * - */ -public class XWPFSDTContent implements ISDTContent { - +import java.util.ArrayList; +import java.util.List; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; + +/** + * Experimental class to offer rudimentary read-only processing of + * of the contentblock of an SDT/ContentControl. + *

    + *

    + *

    + * WARNING - APIs expected to change rapidly + */ +public class XWPFSDTContent implements ISDTContent { + // private final IBody part; // private final XWPFDocument document; private List paragraphs = new ArrayList(); private List tables = new ArrayList(); private List runs = new ArrayList(); - private List contentControls = new ArrayList(); - private List bodyElements = new ArrayList(); - - public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent){ - for (CTR ctr : sdtRun.getRArray()){ - XWPFRun run = new XWPFRun(ctr, parent); - runs.add(run); - bodyElements.add(run); - } - } - public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent){ - XmlCursor cursor = block.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { + private List contentControls = new ArrayList(); + private List bodyElements = new ArrayList(); + + public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent) { + for (CTR ctr : sdtRun.getRArray()) { + XWPFRun run = new XWPFRun(ctr, parent); + runs.add(run); + bodyElements.add(run); + } + } + + public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent) { + XmlCursor cursor = block.newCursor(); + cursor.selectPath("./*"); + while (cursor.toNextSelection()) { XmlObject o = cursor.getObject(); if (o instanceof CTP) { XWPFParagraph p = new XWPFParagraph((CTP) o, part); bodyElements.add(p); paragraphs.add(p); } else if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, part); - bodyElements.add(t); - tables.add(t); - } else if (o instanceof CTSdtBlock){ - XWPFSDT c = new XWPFSDT(((CTSdtBlock)o), part); - bodyElements.add(c); - contentControls.add(c); - } else if (o instanceof CTR) { + XWPFTable t = new XWPFTable((CTTbl) o, part); + bodyElements.add(t); + tables.add(t); + } else if (o instanceof CTSdtBlock) { + XWPFSDT c = new XWPFSDT(((CTSdtBlock) o), part); + bodyElements.add(c); + contentControls.add(c); + } else if (o instanceof CTR) { XWPFRun run = new XWPFRun((CTR) o, parent); runs.add(run); bodyElements.add(run); } - } - } - - public String getText(){ - StringBuilder text = new StringBuilder(); - boolean addNewLine = false; - for (int i = 0; i < bodyElements.size(); i++){ - Object o = bodyElements.get(i); - if (o instanceof XWPFParagraph){ - appendParagraph((XWPFParagraph)o, text); - addNewLine = true; - } else if (o instanceof XWPFTable){ - appendTable((XWPFTable)o, text); - addNewLine = true; - } else if (o instanceof XWPFSDT){ - text.append(((XWPFSDT)o).getContent().getText()); - addNewLine = true; - } else if (o instanceof XWPFRun){ - text.append(((XWPFRun)o).toString()); - addNewLine = false; - } - if (addNewLine == true && i < bodyElements.size()-1){ - text.append("\n"); - } - } + } + } + + public String getText() { + StringBuilder text = new StringBuilder(); + boolean addNewLine = false; + for (int i = 0; i < bodyElements.size(); i++) { + Object o = bodyElements.get(i); + if (o instanceof XWPFParagraph) { + appendParagraph((XWPFParagraph) o, text); + addNewLine = true; + } else if (o instanceof XWPFTable) { + appendTable((XWPFTable) o, text); + addNewLine = true; + } else if (o instanceof XWPFSDT) { + text.append(((XWPFSDT) o).getContent().getText()); + addNewLine = true; + } else if (o instanceof XWPFRun) { + text.append(((XWPFRun) o).toString()); + addNewLine = false; + } + if (addNewLine == true && i < bodyElements.size() - 1) { + text.append("\n"); + } + } return text.toString(); } @@ -110,28 +108,28 @@ public class XWPFSDTContent implements ISDTContent { //this works recursively to pull embedded tables from within cells for (XWPFTableRow row : table.getRows()) { List cells = row.getTableICells(); - for (int i = 0; i < cells.size(); i++) { - ICell cell = cells.get(i); - if (cell instanceof XWPFTableCell) { - text.append(((XWPFTableCell)cell).getTextRecursively()); - } else if (cell instanceof XWPFSDTCell) { - text.append(((XWPFSDTCell)cell).getContent().getText()); - } - if (i < cells.size()-1) { - text.append("\t"); - } - } - text.append('\n'); - } - } - - private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) { - for(IRunElement run : paragraph.getRuns()) { - text.append(run.toString()); - } - } - - public String toString(){ - return getText(); - } + for (int i = 0; i < cells.size(); i++) { + ICell cell = cells.get(i); + if (cell instanceof XWPFTableCell) { + text.append(((XWPFTableCell) cell).getTextRecursively()); + } else if (cell instanceof XWPFSDTCell) { + text.append(((XWPFSDTCell) cell).getContent().getText()); + } + if (i < cells.size() - 1) { + text.append("\t"); + } + } + text.append('\n'); + } + } + + private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) { + for (IRunElement run : paragraph.getRuns()) { + text.append(run.toString()); + } + } + + public String toString() { + return getText(); + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java index 25e258a5cc..17f388b59e 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java @@ -18,54 +18,52 @@ package org.apache.poi.xwpf.usermodel; import javax.xml.namespace.QName; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell; - - - -/** - * Experimental class to offer rudimentary read-only processing of - * of the XWPFSDTCellContent. - - * WARNING - APIs expected to change rapidly - * - */ -public class XWPFSDTContentCell implements ISDTContent { - + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell; + + +/** + * Experimental class to offer rudimentary read-only processing of + * of the XWPFSDTCellContent. + *

    + * WARNING - APIs expected to change rapidly + */ +public class XWPFSDTContentCell implements ISDTContent { + //A full implementation would grab the icells //that a content cell can contain. This would require //significant changes, including changing the notion that the //parent of a cell can be not just a row, but an sdt. //For now we are just grabbing the text out of the text tokentypes. - //private List cells = new ArrayList(). - - private String text = ""; - public XWPFSDTContentCell(CTSdtContentCell sdtContentCell, - XWPFTableRow xwpfTableRow, IBody part){ - super(); - StringBuilder sb = new StringBuilder(); - XmlCursor cursor = sdtContentCell.newCursor(); - - //keep track of the following, - //and add "\n" only before the start of a body - //element if it is not the first body element. - - //index of cell in row - int tcCnt = 0; - //count of body objects + //private List cells = new ArrayList(). + + private String text = ""; + + public XWPFSDTContentCell(CTSdtContentCell sdtContentCell, + XWPFTableRow xwpfTableRow, IBody part) { + super(); + StringBuilder sb = new StringBuilder(); + XmlCursor cursor = sdtContentCell.newCursor(); + + //keep track of the following, + //and add "\n" only before the start of a body + //element if it is not the first body element. + + //index of cell in row + int tcCnt = 0; + //count of body objects int iBodyCnt = 0; int depth = 1; - - while (cursor.hasNextToken() && depth > 0) { - TokenType t = cursor.toNextToken(); - if (t.isText()){ - sb.append(cursor.getTextValue()); - } else if (isStartToken(cursor, "tr")) { - tcCnt = 0; + + while (cursor.hasNextToken() && depth > 0) { + TokenType t = cursor.toNextToken(); + if (t.isText()) { + sb.append(cursor.getTextValue()); + } else if (isStartToken(cursor, "tr")) { + tcCnt = 0; iBodyCnt = 0; } else if (isStartToken(cursor, "tc")) { if (tcCnt++ > 0) { @@ -77,38 +75,37 @@ public class XWPFSDTContentCell implements ISDTContent { isStartToken(cursor, "sdt")) { if (iBodyCnt > 0) { sb.append("\n"); - } - iBodyCnt++; - } - if (cursor.isStart()){ - depth++; - } else if (cursor.isEnd()){ - depth--; - } - } - text = sb.toString(); - } - - - - private boolean isStartToken(XmlCursor cursor, String string) { - if (! cursor.isStart()) { - return false; - } - QName qName = cursor.getName(); + } + iBodyCnt++; + } + if (cursor.isStart()) { + depth++; + } else if (cursor.isEnd()) { + depth--; + } + } + text = sb.toString(); + } + + + private boolean isStartToken(XmlCursor cursor, String string) { + if (!cursor.isStart()) { + return false; + } + QName qName = cursor.getName(); if (qName != null && qName.getLocalPart() != null && qName.getLocalPart().equals(string)) { return true; } return false; - } - - - public String getText(){ - return text; - } - - public String toString(){ - return getText(); - } + } + + + public String getText() { + return text; + } + + public String toString() { + return getText(); + } } diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java index 3dcc41aaa9..6ce7e2ac3d 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java @@ -59,8 +59,7 @@ public class XWPFSettings extends POIXMLDocumentPart { } @Override - protected void onDocumentRead() throws IOException - { + protected void onDocumentRead() throws IOException { super.onDocumentRead(); readFrom(getPackagePart().getInputStream()); } @@ -74,17 +73,18 @@ public class XWPFSettings extends POIXMLDocumentPart { *

          *    <w:zoom w:percent="50" />
          * 
    +     *
          * @return percentage as an integer of zoom level
          */
         public long getZoomPercent() {
    -       CTZoom zoom;
    -       if (!ctSettings.isSetZoom()) {
    -          zoom = ctSettings.addNewZoom();
    -       } else {
    -          zoom = ctSettings.getZoom();
    -       }
    -
    -       return zoom.getPercent().longValue();
    +        CTZoom zoom;
    +        if (!ctSettings.isSetZoom()) {
    +            zoom = ctSettings.addNewZoom();
    +        } else {
    +            zoom = ctSettings.getZoom();
    +        }
    +
    +        return zoom.getPercent().longValue();
         }
     
         /**
    @@ -92,31 +92,31 @@ public class XWPFSettings extends POIXMLDocumentPart {
          * In the zoom tag inside settings.xml file 
    * it sets the value of zoom *
    - * sample snippet from settings.xml + * sample snippet from settings.xml *
    -     *    <w:zoom w:percent="50" /> 
    +     *    <w:zoom w:percent="50" />
          * 
          */
         public void setZoomPercent(long zoomPercent) {
    -       if (! ctSettings.isSetZoom()) {
    -          ctSettings.addNewZoom();
    -       }
    -       CTZoom zoom = ctSettings.getZoom();
    -       zoom.setPercent(BigInteger.valueOf(zoomPercent));
    +        if (!ctSettings.isSetZoom()) {
    +            ctSettings.addNewZoom();
    +        }
    +        CTZoom zoom = ctSettings.getZoom();
    +        zoom.setPercent(BigInteger.valueOf(zoomPercent));
         }
     
         /**
          * Verifies the documentProtection tag inside settings.xml file 
    * if the protection is enforced (w:enforcement="1")
    * and if the kind of protection equals to passed (STDocProtect.Enum editValue)
    - * + *

    *
    * sample snippet from settings.xml *

          *     <w:settings  ... >
          *         <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
          * 
    - * + * * @return true if documentProtection is enforced with option readOnly */ public boolean isEnforcedWith(STDocProtect.Enum editValue) { @@ -152,23 +152,23 @@ public class XWPFSettings extends POIXMLDocumentPart { *
    * sample snippet from settings.xml *
    -     *   <w:documentProtection w:edit="[passed editValue]" w:enforcement="1" 
    +     *   <w:documentProtection w:edit="[passed editValue]" w:enforcement="1"
          *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
          *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
          *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
          *   />
          * 
    - * + * * @param editValue the protection type - * @param password the plaintext password, if null no password will be applied - * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 + * @param password the plaintext password, if null no password will be applied + * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. + * if null, it will default default to sha1 */ public void setEnforcementEditValue(org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect.Enum editValue, - String password, HashAlgorithm hashAlgo) { + String password, HashAlgorithm hashAlgo) { safeGetDocumentProtection().setEnforcement(STOnOff.X_1); safeGetDocumentProtection().setEdit(editValue); - + if (password == null) { if (safeGetDocumentProtection().isSetCryptProviderType()) { safeGetDocumentProtection().unsetCryptProviderType(); @@ -177,23 +177,23 @@ public class XWPFSettings extends POIXMLDocumentPart { if (safeGetDocumentProtection().isSetCryptAlgorithmClass()) { safeGetDocumentProtection().unsetCryptAlgorithmClass(); } - + if (safeGetDocumentProtection().isSetCryptAlgorithmType()) { safeGetDocumentProtection().unsetCryptAlgorithmType(); } - + if (safeGetDocumentProtection().isSetCryptAlgorithmSid()) { safeGetDocumentProtection().unsetCryptAlgorithmSid(); } - + if (safeGetDocumentProtection().isSetSalt()) { safeGetDocumentProtection().unsetSalt(); } - + if (safeGetDocumentProtection().isSetCryptSpinCount()) { safeGetDocumentProtection().unsetCryptSpinCount(); } - + if (safeGetDocumentProtection().isSetHash()) { safeGetDocumentProtection().unsetHash(); } @@ -201,47 +201,47 @@ public class XWPFSettings extends POIXMLDocumentPart { final STCryptProv.Enum providerType; final int sid; switch (hashAlgo) { - case md2: - providerType = STCryptProv.RSA_FULL; - sid = 1; - break; - case md4: - providerType = STCryptProv.RSA_FULL; - sid = 2; - break; - case md5: - providerType = STCryptProv.RSA_FULL; - sid = 3; - break; - case sha1: - providerType = STCryptProv.RSA_FULL; - sid = 4; - break; - case sha256: - providerType = STCryptProv.RSA_AES; - sid = 12; - break; - case sha384: - providerType = STCryptProv.RSA_AES; - sid = 13; - break; - case sha512: - providerType = STCryptProv.RSA_AES; - sid = 14; - break; - default: - throw new EncryptedDocumentException - ("Hash algorithm '"+hashAlgo+"' is not supported for document write protection."); + case md2: + providerType = STCryptProv.RSA_FULL; + sid = 1; + break; + case md4: + providerType = STCryptProv.RSA_FULL; + sid = 2; + break; + case md5: + providerType = STCryptProv.RSA_FULL; + sid = 3; + break; + case sha1: + providerType = STCryptProv.RSA_FULL; + sid = 4; + break; + case sha256: + providerType = STCryptProv.RSA_AES; + sid = 12; + break; + case sha384: + providerType = STCryptProv.RSA_AES; + sid = 13; + break; + case sha512: + providerType = STCryptProv.RSA_AES; + sid = 14; + break; + default: + throw new EncryptedDocumentException + ("Hash algorithm '" + hashAlgo + "' is not supported for document write protection."); } - - SecureRandom random = new SecureRandom(); + + SecureRandom random = new SecureRandom(); byte salt[] = random.generateSeed(16); - + // Iterations specifies the number of times the hashing function shall be iteratively run (using each // iteration's result as the input for the next iteration). int spinCount = 100000; - + if (hashAlgo == null) hashAlgo = HashAlgorithm.sha1; String legacyHash = CryptoFunctions.xorHashPasswordReversed(password); @@ -257,7 +257,7 @@ public class XWPFSettings extends POIXMLDocumentPart { safeGetDocumentProtection().setCryptAlgorithmClass(STAlgClass.HASH); safeGetDocumentProtection().setCryptProviderType(providerType); safeGetDocumentProtection().setCryptAlgorithmSid(BigInteger.valueOf(sid)); - } + } } /** @@ -271,30 +271,45 @@ public class XWPFSettings extends POIXMLDocumentPart { byte hash[] = safeGetDocumentProtection().getHash(); byte salt[] = safeGetDocumentProtection().getSalt(); BigInteger spinCount = safeGetDocumentProtection().getCryptSpinCount(); - + if (sid == null || hash == null || salt == null || spinCount == null) return false; - + HashAlgorithm hashAlgo; switch (sid.intValue()) { - case 1: hashAlgo = HashAlgorithm.md2; break; - case 2: hashAlgo = HashAlgorithm.md4; break; - case 3: hashAlgo = HashAlgorithm.md5; break; - case 4: hashAlgo = HashAlgorithm.sha1; break; - case 12: hashAlgo = HashAlgorithm.sha256; break; - case 13: hashAlgo = HashAlgorithm.sha384; break; - case 14: hashAlgo = HashAlgorithm.sha512; break; - default: return false; + case 1: + hashAlgo = HashAlgorithm.md2; + break; + case 2: + hashAlgo = HashAlgorithm.md4; + break; + case 3: + hashAlgo = HashAlgorithm.md5; + break; + case 4: + hashAlgo = HashAlgorithm.sha1; + break; + case 12: + hashAlgo = HashAlgorithm.sha256; + break; + case 13: + hashAlgo = HashAlgorithm.sha384; + break; + case 14: + hashAlgo = HashAlgorithm.sha512; + break; + default: + return false; } - + String legacyHash = CryptoFunctions.xorHashPasswordReversed(password); // Implementation Notes List: // --> In this third stage, the reversed byte order legacy hash from the second stage shall // be converted to Unicode hex string representation byte hash2[] = CryptoFunctions.hashPassword(legacyHash, hashAlgo, salt, spinCount.intValue(), false); - + return Arrays.equals(hash, hash2); } - + /** * Removes protection enforcement.
    * In the documentProtection tag inside settings.xml file
    @@ -308,18 +323,18 @@ public class XWPFSettings extends POIXMLDocumentPart { * Enforces fields update on document open (in Word). * In the settings.xml file
    * sets the updateSettings value to true (w:updateSettings w:val="true") - * - * NOTICES: - *
      - *
    • Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" - * (if "Update automatic links at open" is enabled)
    • - *
    • Flag is removed after saving with changes in Word
    • - *
    + *

    + * NOTICES: + *

      + *
    • Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" + * (if "Update automatic links at open" is enabled)
    • + *
    • Flag is removed after saving with changes in Word
    • + *
    */ public void setUpdateFields() { - CTOnOff onOff = CTOnOff.Factory.newInstance(); - onOff.setVal(STOnOff.TRUE); - ctSettings.setUpdateFields(onOff); + CTOnOff onOff = CTOnOff.Factory.newInstance(); + onOff.setVal(STOnOff.TRUE); + ctSettings.setUpdateFields(onOff); } boolean isUpdateFields() { @@ -328,7 +343,7 @@ public class XWPFSettings extends POIXMLDocumentPart { /** * Check if revision tracking is turned on. - * + * * @return true if revision tracking is turned on */ public boolean isTrackRevisions() { @@ -337,16 +352,16 @@ public class XWPFSettings extends POIXMLDocumentPart { /** * Enable or disable revision tracking. - * + * * @param enable true to turn on revision tracking, false to turn off revision tracking */ public void setTrackRevisions(boolean enable) { - if(enable) { - if(!ctSettings.isSetTrackRevisions()) { + if (enable) { + if (!ctSettings.isSetTrackRevisions()) { ctSettings.addNewTrackRevisions(); } } else { - if(ctSettings.isSetTrackRevisions()) { + if (ctSettings.isSetTrackRevisions()) { ctSettings.unsetTrackRevisions(); } } @@ -355,7 +370,7 @@ public class XWPFSettings extends POIXMLDocumentPart { @Override protected void commit() throws IOException { if (ctSettings == null) { - throw new IllegalStateException("Unable to write out settings that were never read in!"); + throw new IllegalStateException("Unable to write out settings that were never read in!"); } XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java index 2ceff9719b..a6ebdcc718 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java @@ -19,128 +19,141 @@ package org.apache.poi.xwpf.usermodel; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType; - -/** - * @author Philipp Epp - * - */ -public class XWPFStyle { - - private CTStyle ctStyle; - protected XWPFStyles styles; - - /** - * constructor - * @param style - */ - public XWPFStyle(CTStyle style){ - this(style,null); - } - /** - * constructor - * @param style - * @param styles - */ - public XWPFStyle(CTStyle style, XWPFStyles styles){ - this.ctStyle = style; - this.styles = styles; - } - - /** - * get StyleID of the style - * @return styleID StyleID of the style - */ - public String getStyleId(){ - return ctStyle.getStyleId(); - } - - /** - * get Type of the Style - * @return ctType - */ - public STStyleType.Enum getType(){ - return ctStyle.getType(); - } - - /** - * set style - * @param style - */ - public void setStyle(CTStyle style){ - this.ctStyle = style; - } - /** - * get ctStyle - * @return ctStyle - */ - public CTStyle getCTStyle(){ - return this.ctStyle; - } - /** - * set styleID - * @param styleId - */ - public void setStyleId(String styleId){ - ctStyle.setStyleId(styleId); - } - - /** - * set styleType - * @param type - */ - public void setType(STStyleType.Enum type){ - ctStyle.setType(type); - } - /** - * get styles - * @return styles the styles to which this style belongs - */ - public XWPFStyles getStyles(){ - return styles; - } - - public String getBasisStyleID(){ - if(ctStyle.getBasedOn()!=null) - return ctStyle.getBasedOn().getVal(); - else - return null; - } - - - /** - * get StyleID of the linked Style - */ - public String getLinkStyleID(){ - if (ctStyle.getLink()!=null) - return ctStyle.getLink().getVal(); - else - return null; - } - - /** - * get StyleID of the next style - */ - public String getNextStyleID(){ - if(ctStyle.getNext()!=null) - return ctStyle.getNext().getVal(); - else - return null; - } - - public String getName() { - if(ctStyle.isSetName()) - return ctStyle.getName().getVal(); - return null; - } - - /** - * compares the names of the Styles - * @param compStyle - */ - public boolean hasSameName(XWPFStyle compStyle){ - CTStyle ctCompStyle = compStyle.getCTStyle(); - String name = ctCompStyle.getName().getVal(); - return name.equals(ctStyle.getName().getVal()); - } - -}//end class + +/** + * @author Philipp Epp + */ +public class XWPFStyle { + + protected XWPFStyles styles; + private CTStyle ctStyle; + + /** + * constructor + * + * @param style + */ + public XWPFStyle(CTStyle style) { + this(style, null); + } + + /** + * constructor + * + * @param style + * @param styles + */ + public XWPFStyle(CTStyle style, XWPFStyles styles) { + this.ctStyle = style; + this.styles = styles; + } + + /** + * get StyleID of the style + * + * @return styleID StyleID of the style + */ + public String getStyleId() { + return ctStyle.getStyleId(); + } + + /** + * set styleID + * + * @param styleId + */ + public void setStyleId(String styleId) { + ctStyle.setStyleId(styleId); + } + + /** + * get Type of the Style + * + * @return ctType + */ + public STStyleType.Enum getType() { + return ctStyle.getType(); + } + + /** + * set styleType + * + * @param type + */ + public void setType(STStyleType.Enum type) { + ctStyle.setType(type); + } + + /** + * set style + * + * @param style + */ + public void setStyle(CTStyle style) { + this.ctStyle = style; + } + + /** + * get ctStyle + * + * @return ctStyle + */ + public CTStyle getCTStyle() { + return this.ctStyle; + } + + /** + * get styles + * + * @return styles the styles to which this style belongs + */ + public XWPFStyles getStyles() { + return styles; + } + + public String getBasisStyleID() { + if (ctStyle.getBasedOn() != null) + return ctStyle.getBasedOn().getVal(); + else + return null; + } + + + /** + * get StyleID of the linked Style + */ + public String getLinkStyleID() { + if (ctStyle.getLink() != null) + return ctStyle.getLink().getVal(); + else + return null; + } + + /** + * get StyleID of the next style + */ + public String getNextStyleID() { + if (ctStyle.getNext() != null) + return ctStyle.getNext().getVal(); + else + return null; + } + + public String getName() { + if (ctStyle.isSetName()) + return ctStyle.getName().getVal(); + return null; + } + + /** + * compares the names of the Styles + * + * @param compStyle + */ + public boolean hasSameName(XWPFStyle compStyle) { + CTStyle ctCompStyle = compStyle.getCTStyle(); + String name = ctCompStyle.getName().getVal(); + return name.equals(ctStyle.getName().getVal()); + } + +}//end class diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java index 8647cc9f7e..ed39601796 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java @@ -31,42 +31,43 @@ import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults; -/** - * Holds details of built-in, default and user styles, which - * apply to tables / paragraphs / lists etc. - * Text within one of those with custom stylings has the style - * information stored in the {@link XWPFRun} - */ -public class XWPFStyles extends POIXMLDocumentPart{ - private CTStyles ctStyles; - private List listStyle = new ArrayList(); - - private XWPFLatentStyles latentStyles; - private XWPFDefaultRunStyle defaultRunStyle; - private XWPFDefaultParagraphStyle defaultParaStyle; +import org.apache.poi.openxml4j.opc.PackageRelationship; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlOptions; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; + +/** + * Holds details of built-in, default and user styles, which + * apply to tables / paragraphs / lists etc. + * Text within one of those with custom stylings has the style + * information stored in the {@link XWPFRun} + */ +public class XWPFStyles extends POIXMLDocumentPart { + private CTStyles ctStyles; + private List listStyle = new ArrayList(); + + private XWPFLatentStyles latentStyles; + private XWPFDefaultRunStyle defaultRunStyle; + private XWPFDefaultParagraphStyle defaultParaStyle; /** * Construct XWPFStyles from a package part * - * @param part the package part holding the data of the styles, - * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" - */ - public XWPFStyles(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{ - super(part, rel); - } - + * @param part the package part holding the data of the styles, + * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" + */ + public XWPFStyles(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException { + super(part, rel); + } + /** * Construct XWPFStyles from scratch for a new document. */ @@ -74,13 +75,13 @@ public class XWPFStyles extends POIXMLDocumentPart{ } /** - * Read document - */ - @Override - protected void onDocumentRead() throws IOException{ - StylesDocument stylesDoc; - try { - InputStream is = getPackagePart().getInputStream(); + * Read document + */ + @Override + protected void onDocumentRead() throws IOException { + StylesDocument stylesDoc; + try { + InputStream is = getPackagePart().getInputStream(); stylesDoc = StylesDocument.Factory.parse(is); setStyles(stylesDoc.getStyles()); latentStyles = new XWPFLatentStyles(ctStyles.getLatentStyles(), this); @@ -94,52 +95,53 @@ public class XWPFStyles extends POIXMLDocumentPart{ if (ctStyles == null) { throw new IllegalStateException("Unable to write out styles that were never read in!"); } - - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles")); - Map map = new HashMap(); - map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); - map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); - xmlOptions.setSaveSuggestedPrefixes(map); + + XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); + xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles")); + Map map = new HashMap(); + map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); + map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); + xmlOptions.setSaveSuggestedPrefixes(map); PackagePart part = getPackagePart(); OutputStream out = part.getOutputStream(); ctStyles.save(out, xmlOptions); out.close(); - } - - protected void ensureDocDefaults() { - if (! ctStyles.isSetDocDefaults()) { - ctStyles.addNewDocDefaults(); - } - - CTDocDefaults docDefaults = ctStyles.getDocDefaults(); - if (! docDefaults.isSetPPrDefault()) - docDefaults.addNewPPrDefault(); - if (! docDefaults.isSetRPrDefault()) - docDefaults.addNewRPrDefault(); - - CTPPrDefault pprd = docDefaults.getPPrDefault(); - CTRPrDefault rprd = docDefaults.getRPrDefault(); - if (!pprd.isSetPPr()) pprd.addNewPPr(); - if (!rprd.isSetRPr()) rprd.addNewRPr(); - - defaultRunStyle = new XWPFDefaultRunStyle(rprd.getRPr()); - defaultParaStyle = new XWPFDefaultParagraphStyle(pprd.getPPr()); - } - - /** - * Sets the ctStyles - * @param styles - */ - @SuppressWarnings("deprecation") + } + + protected void ensureDocDefaults() { + if (!ctStyles.isSetDocDefaults()) { + ctStyles.addNewDocDefaults(); + } + + CTDocDefaults docDefaults = ctStyles.getDocDefaults(); + if (!docDefaults.isSetPPrDefault()) + docDefaults.addNewPPrDefault(); + if (!docDefaults.isSetRPrDefault()) + docDefaults.addNewRPrDefault(); + + CTPPrDefault pprd = docDefaults.getPPrDefault(); + CTRPrDefault rprd = docDefaults.getRPrDefault(); + if (!pprd.isSetPPr()) pprd.addNewPPr(); + if (!rprd.isSetRPr()) rprd.addNewRPr(); + + defaultRunStyle = new XWPFDefaultRunStyle(rprd.getRPr()); + defaultParaStyle = new XWPFDefaultParagraphStyle(pprd.getPPr()); + } + + /** + * Sets the ctStyles + * + * @param styles + */ + @SuppressWarnings("deprecation") public void setStyles(CTStyles styles) { - ctStyles = styles; - - // Build up all the style objects - for(CTStyle style : ctStyles.getStyleArray()) { - listStyle.add(new XWPFStyle(style, this)); - } - if (ctStyles.isSetDocDefaults()) { + ctStyles = styles; + + // Build up all the style objects + for (CTStyle style : ctStyles.getStyleArray()) { + listStyle.add(new XWPFStyle(style, this)); + } + if (ctStyles.isSetDocDefaults()) { CTDocDefaults docDefaults = ctStyles.getDocDefaults(); if (docDefaults.isSetRPrDefault() && docDefaults.getRPrDefault().isSetRPr()) { defaultRunStyle = new XWPFDefaultRunStyle( @@ -151,142 +153,152 @@ public class XWPFStyles extends POIXMLDocumentPart{ } } } - - /** - * checks whether style with styleID exist - * @param styleID styleID of the Style in the style-Document - * @return true if style exist, false if style not exist - */ - public boolean styleExist(String styleID){ - for (XWPFStyle style : listStyle) { - if (style.getStyleId().equals(styleID)) - return true; - } - return false; - } - /** - * add a style to the document - * @param style - * @throws IOException - */ - public void addStyle(XWPFStyle style){ - listStyle.add(style); - ctStyles.addNewStyle(); - int pos = ctStyles.sizeOfStyleArray() - 1; - ctStyles.setStyleArray(pos, style.getCTStyle()); - } - /** - * Get style by a styleID - * @param styleID styleID of the searched style - * @return style - */ - public XWPFStyle getStyle(String styleID){ - for (XWPFStyle style : listStyle) { - if(style.getStyleId().equals(styleID)) - return style; - } - return null; - } - public int getNumberOfStyles() { - return listStyle.size(); - } - - /** - * get the styles which are related to the parameter style and their relatives - * this method can be used to copy all styles from one document to another document - * @param style - * @return a list of all styles which were used by this method - */ - public List getUsedStyleList(XWPFStyle style){ - List usedStyleList = new ArrayList(); - usedStyleList.add(style); - return getUsedStyleList(style, usedStyleList); - } - - /** - * get the styles which are related to parameter style - * @param style - * @return all Styles of the parameterList - */ - private List getUsedStyleList(XWPFStyle style, List usedStyleList){ - String basisStyleID = style.getBasisStyleID(); - XWPFStyle basisStyle = getStyle(basisStyleID); - if((basisStyle!=null)&&(!usedStyleList.contains(basisStyle))){ - usedStyleList.add(basisStyle); - getUsedStyleList(basisStyle, usedStyleList); - } - String linkStyleID = style.getLinkStyleID(); - XWPFStyle linkStyle = getStyle(linkStyleID); - if((linkStyle!=null)&&(!usedStyleList.contains(linkStyle))){ - usedStyleList.add(linkStyle); - getUsedStyleList(linkStyle, usedStyleList); - } - - String nextStyleID = style.getNextStyleID(); - XWPFStyle nextStyle = getStyle(nextStyleID); - if((nextStyle!=null)&&(!usedStyleList.contains(nextStyle))){ - usedStyleList.add(linkStyle); - getUsedStyleList(linkStyle, usedStyleList); - } - return usedStyleList; - } - - protected CTLanguage getCTLanguage() { - ensureDocDefaults(); - - CTLanguage lang = null; - if (defaultRunStyle.getRPr().isSetLang()) { - lang = defaultRunStyle.getRPr().getLang(); - } else { - lang = defaultRunStyle.getRPr().addNewLang(); - } - - return lang; - } - - /** - * Sets the default spelling language on ctStyles DocDefaults parameter - * @param strSpellingLanguage - */ - public void setSpellingLanguage(String strSpellingLanguage) { + + /** + * checks whether style with styleID exist + * + * @param styleID styleID of the Style in the style-Document + * @return true if style exist, false if style not exist + */ + public boolean styleExist(String styleID) { + for (XWPFStyle style : listStyle) { + if (style.getStyleId().equals(styleID)) + return true; + } + return false; + } + + /** + * add a style to the document + * + * @param style + * @throws IOException + */ + public void addStyle(XWPFStyle style) { + listStyle.add(style); + ctStyles.addNewStyle(); + int pos = ctStyles.sizeOfStyleArray() - 1; + ctStyles.setStyleArray(pos, style.getCTStyle()); + } + + /** + * Get style by a styleID + * + * @param styleID styleID of the searched style + * @return style + */ + public XWPFStyle getStyle(String styleID) { + for (XWPFStyle style : listStyle) { + if (style.getStyleId().equals(styleID)) + return style; + } + return null; + } + + public int getNumberOfStyles() { + return listStyle.size(); + } + + /** + * get the styles which are related to the parameter style and their relatives + * this method can be used to copy all styles from one document to another document + * + * @param style + * @return a list of all styles which were used by this method + */ + public List getUsedStyleList(XWPFStyle style) { + List usedStyleList = new ArrayList(); + usedStyleList.add(style); + return getUsedStyleList(style, usedStyleList); + } + + /** + * get the styles which are related to parameter style + * + * @param style + * @return all Styles of the parameterList + */ + private List getUsedStyleList(XWPFStyle style, List usedStyleList) { + String basisStyleID = style.getBasisStyleID(); + XWPFStyle basisStyle = getStyle(basisStyleID); + if ((basisStyle != null) && (!usedStyleList.contains(basisStyle))) { + usedStyleList.add(basisStyle); + getUsedStyleList(basisStyle, usedStyleList); + } + String linkStyleID = style.getLinkStyleID(); + XWPFStyle linkStyle = getStyle(linkStyleID); + if ((linkStyle != null) && (!usedStyleList.contains(linkStyle))) { + usedStyleList.add(linkStyle); + getUsedStyleList(linkStyle, usedStyleList); + } + + String nextStyleID = style.getNextStyleID(); + XWPFStyle nextStyle = getStyle(nextStyleID); + if ((nextStyle != null) && (!usedStyleList.contains(nextStyle))) { + usedStyleList.add(linkStyle); + getUsedStyleList(linkStyle, usedStyleList); + } + return usedStyleList; + } + + protected CTLanguage getCTLanguage() { + ensureDocDefaults(); + + CTLanguage lang = null; + if (defaultRunStyle.getRPr().isSetLang()) { + lang = defaultRunStyle.getRPr().getLang(); + } else { + lang = defaultRunStyle.getRPr().addNewLang(); + } + + return lang; + } + + /** + * Sets the default spelling language on ctStyles DocDefaults parameter + * + * @param strSpellingLanguage + */ + public void setSpellingLanguage(String strSpellingLanguage) { CTLanguage lang = getCTLanguage(); - lang.setVal(strSpellingLanguage); - lang.setBidi(strSpellingLanguage); - } - - /** - * Sets the default East Asia spelling language on ctStyles DocDefaults parameter - * @param strEastAsia - */ - public void setEastAsia(String strEastAsia) { + lang.setVal(strSpellingLanguage); + lang.setBidi(strSpellingLanguage); + } + + /** + * Sets the default East Asia spelling language on ctStyles DocDefaults parameter + * + * @param strEastAsia + */ + public void setEastAsia(String strEastAsia) { CTLanguage lang = getCTLanguage(); lang.setEastAsia(strEastAsia); } - /** - * Sets the default font on ctStyles DocDefaults parameter - * TODO Replace this with specific setters for each type, possibly - * on XWPFDefaultRunStyle - */ - public void setDefaultFonts(CTFonts fonts) { - ensureDocDefaults(); - - CTRPr runProps = defaultRunStyle.getRPr(); - runProps.setRFonts(fonts); - } + /** + * Sets the default font on ctStyles DocDefaults parameter + * TODO Replace this with specific setters for each type, possibly + * on XWPFDefaultRunStyle + */ + public void setDefaultFonts(CTFonts fonts) { + ensureDocDefaults(); + + CTRPr runProps = defaultRunStyle.getRPr(); + runProps.setRFonts(fonts); + } /** - * get the style with the same name - * if this style is not existing, return null - */ - public XWPFStyle getStyleWithSameName(XWPFStyle style){ - for (XWPFStyle ownStyle : listStyle) { - if(ownStyle.hasSameName(style)){ - return ownStyle; - } - } - return null; - } + * get the style with the same name + * if this style is not existing, return null + */ + public XWPFStyle getStyleWithSameName(XWPFStyle style) { + for (XWPFStyle ownStyle : listStyle) { + if (ownStyle.hasSameName(style)) { + return ownStyle; + } + } + return null; + } /** * Get the default style which applies text runs in the document diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java index 643d28ffa9..1f4fd2b384 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java @@ -44,19 +44,10 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth; * of paragraphs (and other block-level content) arranged in rows and columns.

    */ public class XWPFTable implements IBodyElement, ISDTContents { - protected StringBuffer text = new StringBuffer(); - private CTTbl ctTbl; - protected List tableRows; - protected List styleIDs; - - // Create a map from this XWPF-level enum to the STBorder.Enum values - public static enum XWPFBorderType { NIL, NONE, SINGLE, THICK, DOUBLE, DOTTED, DASHED, DOT_DASH }; private static EnumMap xwpfBorderTypeMap; // Create a map from the STBorder.Enum values to the XWPF-level enums private static HashMap stBorderTypeMap; - protected IBody part; - static { // populate enum maps xwpfBorderTypeMap = new EnumMap(XWPFBorderType.class); @@ -77,9 +68,17 @@ public class XWPFTable implements IBodyElement, ISDTContents { stBorderTypeMap.put(STBorder.INT_DOUBLE, XWPFBorderType.DOUBLE); stBorderTypeMap.put(STBorder.INT_DOTTED, XWPFBorderType.DOTTED); stBorderTypeMap.put(STBorder.INT_DASHED, XWPFBorderType.DASHED); - stBorderTypeMap.put(STBorder.INT_DOT_DASH, XWPFBorderType.DOT_DASH); + stBorderTypeMap.put(STBorder.INT_DOT_DASH, XWPFBorderType.DOT_DASH); } - + + protected StringBuffer text = new StringBuffer(); + protected List tableRows; + + ; + protected List styleIDs; + protected IBody part; + private CTTbl ctTbl; + public XWPFTable(CTTbl table, IBody part, int row, int col) { this(table, part); @@ -94,7 +93,7 @@ public class XWPFTable implements IBodyElement, ISDTContents { } @SuppressWarnings("deprecation") - public XWPFTable(CTTbl table, IBody part){ + public XWPFTable(CTTbl table, IBody part) { this.part = part; this.ctTbl = table; @@ -163,9 +162,9 @@ public class XWPFTable implements IBodyElement, ISDTContents { * Convenience method to extract text in cells. This * does not extract text recursively in cells, and it does not * currently include text in SDT (form) components. - *

    + *

    * To get all text within a table, see XWPFWordExtractor's appendTableText - * as an example. + * as an example. * * @return text */ @@ -216,22 +215,21 @@ public class XWPFTable implements IBodyElement, ISDTContents { return null; } - /** - * @param width + * @return width value */ - public void setWidth(int width) { + public int getWidth() { CTTblPr tblPr = getTrPr(); - CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW(); - tblWidth.setW(new BigInteger("" + width)); + return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1; } /** - * @return width value + * @param width */ - public int getWidth() { + public void setWidth(int width) { CTTblPr tblPr = getTrPr(); - return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1; + CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW(); + tblWidth.setW(new BigInteger("" + width)); } /** @@ -253,12 +251,13 @@ public class XWPFTable implements IBodyElement, ISDTContents { } } } - + /** * get the StyleID of the table - * @return style-ID of the table + * + * @return style-ID of the table */ - public String getStyleID(){ + public String getStyleID() { String styleId = null; CTTblPr tblPr = ctTbl.getTblPr(); if (tblPr != null) { @@ -273,6 +272,7 @@ public class XWPFTable implements IBodyElement, ISDTContents { /** * Set the table style. If the style is not defined in the document, MS Word * will set the table style to "Normal". + * * @param styleName - the style name to apply to this table */ public void setStyleID(String styleName) { @@ -523,24 +523,25 @@ public class XWPFTable implements IBodyElement, ISDTContents { /** * add a new Row to the table - * - * @param row the row which should be added + * + * @param row the row which should be added */ - public void addRow(XWPFTableRow row){ + public void addRow(XWPFTableRow row) { ctTbl.addNewTr(); - ctTbl.setTrArray(getNumberOfRows()-1, row.getCtRow()); + ctTbl.setTrArray(getNumberOfRows() - 1, row.getCtRow()); tableRows.add(row); } /** * add a new Row to the table * at position pos - * @param row the row which should be added + * + * @param row the row which should be added */ - public boolean addRow(XWPFTableRow row, int pos){ - if(pos >= 0 && pos <= tableRows.size()){ + public boolean addRow(XWPFTableRow row, int pos) { + if (pos >= 0 && pos <= tableRows.size()) { ctTbl.insertNewTr(pos); - ctTbl.setTrArray(pos,row.getCtRow()); + ctTbl.setTrArray(pos, row.getCtRow()); tableRows.add(pos, row); return true; } @@ -548,12 +549,13 @@ public class XWPFTable implements IBodyElement, ISDTContents { } /** - * inserts a new tablerow + * inserts a new tablerow + * * @param pos - * @return the inserted row + * @return the inserted row */ - public XWPFTableRow insertNewTableRow(int pos){ - if(pos >= 0 && pos <= tableRows.size()){ + public XWPFTableRow insertNewTableRow(int pos) { + if (pos >= 0 && pos <= tableRows.size()) { CTRow row = ctTbl.insertNewTr(pos); XWPFTableRow tableRow = new XWPFTableRow(row, this); tableRows.add(pos, tableRow); @@ -562,10 +564,10 @@ public class XWPFTable implements IBodyElement, ISDTContents { return null; } - /** * Remove a row at position pos from the table - * @param pos position the Row in the Table + * + * @param pos position the Row in the Table */ public boolean removeRow(int pos) throws IndexOutOfBoundsException { if (pos >= 0 && pos < tableRows.size()) { @@ -582,9 +584,9 @@ public class XWPFTable implements IBodyElement, ISDTContents { return tableRows; } - /** * returns the type of the BodyElement Table + * * @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType() */ public BodyElementType getElementType() { @@ -597,10 +599,11 @@ public class XWPFTable implements IBodyElement, ISDTContents { /** * returns the part of the bodyElement + * * @see org.apache.poi.xwpf.usermodel.IBody#getPart() */ public POIXMLDocumentPart getPart() { - if(part != null){ + if (part != null) { return part.getPart(); } return null; @@ -608,6 +611,7 @@ public class XWPFTable implements IBodyElement, ISDTContents { /** * returns the partType of the bodyPart which owns the bodyElement + * * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() */ public BodyType getPartType() { @@ -619,9 +623,14 @@ public class XWPFTable implements IBodyElement, ISDTContents { * if this row is not existing in the table null will be returned */ public XWPFTableRow getRow(CTRow row) { - for(int i=0; i paragraphs = null; - protected List tables = null; - protected List bodyElements = null; - protected IBody part; - private XWPFTableRow tableRow = null; - // Create a map from this XWPF-level enum to the STVerticalJc.Enum values - public static enum XWPFVertAlign { TOP, CENTER, BOTH, BOTTOM }; - private static EnumMap alignMap; - // Create a map from the STVerticalJc.Enum values to the XWPF-level enums - private static HashMap stVertAlignTypeMap; + +/** + * Represents a Cell within a {@link XWPFTable}. The + * Cell is the thing that holds the actual content (paragraphs etc) + */ +public class XWPFTableCell implements IBody, ICell { + private static EnumMap alignMap; + // Create a map from the STVerticalJc.Enum values to the XWPF-level enums + private static HashMap stVertAlignTypeMap; static { // populate enum maps @@ -68,337 +60,343 @@ public class XWPFTableCell implements IBody, ICell { stVertAlignTypeMap.put(STVerticalJc.INT_CENTER, XWPFVertAlign.CENTER); stVertAlignTypeMap.put(STVerticalJc.INT_BOTH, XWPFVertAlign.BOTH); stVertAlignTypeMap.put(STVerticalJc.INT_BOTTOM, XWPFVertAlign.BOTTOM); - - } - - /** - * If a table cell does not include at least one block-level element, then this document shall be considered corrupt - */ + + } + + private final CTTc ctTc; + protected List paragraphs = null; + protected List tables = null; + protected List bodyElements = null; + + ; + protected IBody part; + private XWPFTableRow tableRow = null; + + /** + * If a table cell does not include at least one block-level element, then this document shall be considered corrupt + */ public XWPFTableCell(CTTc cell, XWPFTableRow tableRow, IBody part) { this.ctTc = cell; - this.part = part; - this.tableRow = tableRow; - // NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt. - if(cell.sizeOfPArray()<1) - cell.addNewP(); - bodyElements = new ArrayList(); - paragraphs = new ArrayList(); + this.part = part; + this.tableRow = tableRow; + // NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt. + if (cell.sizeOfPArray() < 1) + cell.addNewP(); + bodyElements = new ArrayList(); + paragraphs = new ArrayList(); tables = new ArrayList(); XmlCursor cursor = ctTc.newCursor(); cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP)o, this); - paragraphs.add(p); - bodyElements.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl)o, this); - tables.add(t); - bodyElements.add(t); - } - if (o instanceof CTSdtBlock){ - XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); - bodyElements.add(c); - } - if (o instanceof CTSdtRun){ - XWPFSDT c = new XWPFSDT((CTSdtRun)o, this); - System.out.println(c.getContent().getText()); - bodyElements.add(c); - } - } - cursor.dispose(); - } - - - @Internal - public CTTc getCTTc() { - return ctTc; - } - - /** - * returns an Iterator with paragraphs and tables - * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() - */ - public List getBodyElements(){ - return Collections.unmodifiableList(bodyElements); + while (cursor.toNextSelection()) { + XmlObject o = cursor.getObject(); + if (o instanceof CTP) { + XWPFParagraph p = new XWPFParagraph((CTP) o, this); + paragraphs.add(p); + bodyElements.add(p); + } + if (o instanceof CTTbl) { + XWPFTable t = new XWPFTable((CTTbl) o, this); + tables.add(t); + bodyElements.add(t); + } + if (o instanceof CTSdtBlock) { + XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); + bodyElements.add(c); + } + if (o instanceof CTSdtRun) { + XWPFSDT c = new XWPFSDT((CTSdtRun) o, this); + System.out.println(c.getContent().getText()); + bodyElements.add(c); + } + } + cursor.dispose(); + } + + @Internal + public CTTc getCTTc() { + return ctTc; } - - public void setParagraph(XWPFParagraph p) { - if (ctTc.sizeOfPArray() == 0) { - ctTc.addNewP(); + + /** + * returns an Iterator with paragraphs and tables + * + * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() + */ + public List getBodyElements() { + return Collections.unmodifiableList(bodyElements); + } + + public void setParagraph(XWPFParagraph p) { + if (ctTc.sizeOfPArray() == 0) { + ctTc.addNewP(); } ctTc.setPArray(0, p.getCTP()); } - /** - * returns a list of paragraphs - */ - public List getParagraphs(){ - return paragraphs; - } - - /** - * Add a Paragraph to this Table Cell - * @return The paragraph which was added - */ - public XWPFParagraph addParagraph() { - XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this); - addParagraph(p); - return p; - } - - /** - * add a Paragraph to this TableCell - * @param p the paragaph which has to be added - */ - public void addParagraph(XWPFParagraph p){ - paragraphs.add(p); - } - - /** - * removes a paragraph of this tablecell - * @param pos - */ - public void removeParagraph(int pos){ - paragraphs.remove(pos); - ctTc.removeP(pos); - } - - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table - * XWPFParagraph with the correspondig CTP p - */ - public XWPFParagraph getParagraph(CTP p){ - for (XWPFParagraph paragraph : paragraphs) { - if(p.equals(paragraph.getCTP())){ - return paragraph; - } - } - return null; - } - - public void setText(String text) { - CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0); - XWPFParagraph par = new XWPFParagraph(ctP, this); - par.createRun().setText(text); - } - - public XWPFTableRow getTableRow(){ - return tableRow; - } - - /** - * Set cell color. This sets some associated values; for finer control - * you may want to access these elements individually. - * @param rgbStr - the desired cell color, in the hex form "RRGGBB". - */ - public void setColor(String rgbStr) { - CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); - CTShd ctshd = tcpr.isSetShd() ? tcpr.getShd() : tcpr.addNewShd(); - ctshd.setColor("auto"); - ctshd.setVal(STShd.CLEAR); - ctshd.setFill(rgbStr); - } - - /** - * Get cell color. Note that this method only returns the "fill" value. - * @return RGB string of cell color - */ - public String getColor() { - String color = null; - CTTcPr tcpr = ctTc.getTcPr(); - if (tcpr != null) { - CTShd ctshd = tcpr.getShd(); - if (ctshd != null) { - color = ctshd.xgetFill().getStringValue(); - } - } - return color; - } - - /** - * Set the vertical alignment of the cell. - * @param vAlign - the desired alignment enum value - */ - public void setVerticalAlignment(XWPFVertAlign vAlign) { - CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); - CTVerticalJc va = tcpr.addNewVAlign(); - va.setVal(alignMap.get(vAlign)); - } - - /** - * Get the vertical alignment of the cell. - * @return the cell alignment enum value - */ - public XWPFVertAlign getVerticalAlignment() { - XWPFVertAlign vAlign = null; - CTTcPr tcpr = ctTc.getTcPr(); - if (ctTc != null) { - CTVerticalJc va = tcpr.getVAlign(); - vAlign = stVertAlignTypeMap.get(va.getVal().intValue()); - } - return vAlign; - } - - /** - * add a new paragraph at position of the cursor - * @param cursor - * @return the inserted paragraph - */ - public XWPFParagraph insertNewParagraph(XmlCursor cursor){ - if(!isCursorInTableCell(cursor)) { - return null; - } - - String uri = CTP.type.getName().getNamespaceURI(); - String localPart = "p"; - cursor.beginElement(localPart,uri); - cursor.toParent(); - CTP p = (CTP)cursor.getObject(); - XWPFParagraph newP = new XWPFParagraph(p, this); - XmlObject o = null; - while(!(o instanceof CTP)&&(cursor.toPrevSibling())){ - o = cursor.getObject(); - } - if((!(o instanceof CTP)) || (CTP)o == p){ - paragraphs.add(0, newP); - } - else{ - int pos = paragraphs.indexOf(getParagraph((CTP)o))+1; - paragraphs.add(pos,newP); - } - int i=0; - cursor.toCursor(p.newCursor()); - while(cursor.toPrevSibling()){ - o =cursor.getObject(); - if(o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newP); - cursor.toCursor(p.newCursor()); - cursor.toEndToken(); - return newP; - } - - public XWPFTable insertNewTbl(XmlCursor cursor) { - if(isCursorInTableCell(cursor)){ - String uri = CTTbl.type.getName().getNamespaceURI(); - String localPart = "tbl"; - cursor.beginElement(localPart,uri); - cursor.toParent(); - CTTbl t = (CTTbl)cursor.getObject(); - XWPFTable newT = new XWPFTable(t, this); - cursor.removeXmlContents(); - XmlObject o = null; - while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){ - o = cursor.getObject(); - } - if(!(o instanceof CTTbl)){ - tables.add(0, newT); - } - else{ - int pos = tables.indexOf(getTable((CTTbl)o))+1; - tables.add(pos,newT); - } - int i=0; - cursor = t.newCursor(); - while(cursor.toPrevSibling()){ - o =cursor.getObject(); - if(o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newT); - cursor = t.newCursor(); - cursor.toEndToken(); - return newT; - } - return null; - } - - /** - * verifies that cursor is on the right position - */ - private boolean isCursorInTableCell(XmlCursor cursor) { - XmlCursor verify = cursor.newCursor(); - verify.toParent(); - if(verify.getObject() == this.ctTc){ - return true; - } - return false; - } - - - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) - */ - public XWPFParagraph getParagraphArray(int pos) { - if(pos > 0 && pos < paragraphs.size()){ - return paragraphs.get(pos); - } - return null; - } - - /** - * get the to which the TableCell belongs - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public POIXMLDocumentPart getPart() { - return tableRow.getTable().getPart(); - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { - return BodyType.TABLECELL; - } - - - /** - * get a table by its CTTbl-Object - * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) - */ - public XWPFTable getTable(CTTbl ctTable) { - for(int i=0; i 0 && pos < tables.size()){ - return tables.get(pos); - } - return null; - } - - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getTables() - */ - public List getTables() { - return Collections.unmodifiableList(tables); - } - - - /** - * inserts an existing XWPFTable to the arrays bodyElements and tables - * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int, org.apache.poi.xwpf.usermodel.XWPFTable) - */ - @SuppressWarnings("deprecation") + /** + * returns a list of paragraphs + */ + public List getParagraphs() { + return paragraphs; + } + + /** + * Add a Paragraph to this Table Cell + * + * @return The paragraph which was added + */ + public XWPFParagraph addParagraph() { + XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this); + addParagraph(p); + return p; + } + + /** + * add a Paragraph to this TableCell + * + * @param p the paragaph which has to be added + */ + public void addParagraph(XWPFParagraph p) { + paragraphs.add(p); + } + + /** + * removes a paragraph of this tablecell + * + * @param pos + */ + public void removeParagraph(int pos) { + paragraphs.remove(pos); + ctTc.removeP(pos); + } + + /** + * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table + * the method will return this paragraph + * if there is no corresponding {@link XWPFParagraph} the method will return null + * + * @param p is instance of CTP and is searching for an XWPFParagraph + * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table + * XWPFParagraph with the correspondig CTP p + */ + public XWPFParagraph getParagraph(CTP p) { + for (XWPFParagraph paragraph : paragraphs) { + if (p.equals(paragraph.getCTP())) { + return paragraph; + } + } + return null; + } + + public XWPFTableRow getTableRow() { + return tableRow; + } + + /** + * Get cell color. Note that this method only returns the "fill" value. + * + * @return RGB string of cell color + */ + public String getColor() { + String color = null; + CTTcPr tcpr = ctTc.getTcPr(); + if (tcpr != null) { + CTShd ctshd = tcpr.getShd(); + if (ctshd != null) { + color = ctshd.xgetFill().getStringValue(); + } + } + return color; + } + + /** + * Set cell color. This sets some associated values; for finer control + * you may want to access these elements individually. + * + * @param rgbStr - the desired cell color, in the hex form "RRGGBB". + */ + public void setColor(String rgbStr) { + CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); + CTShd ctshd = tcpr.isSetShd() ? tcpr.getShd() : tcpr.addNewShd(); + ctshd.setColor("auto"); + ctshd.setVal(STShd.CLEAR); + ctshd.setFill(rgbStr); + } + + /** + * Get the vertical alignment of the cell. + * + * @return the cell alignment enum value + */ + public XWPFVertAlign getVerticalAlignment() { + XWPFVertAlign vAlign = null; + CTTcPr tcpr = ctTc.getTcPr(); + if (ctTc != null) { + CTVerticalJc va = tcpr.getVAlign(); + vAlign = stVertAlignTypeMap.get(va.getVal().intValue()); + } + return vAlign; + } + + /** + * Set the vertical alignment of the cell. + * + * @param vAlign - the desired alignment enum value + */ + public void setVerticalAlignment(XWPFVertAlign vAlign) { + CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); + CTVerticalJc va = tcpr.addNewVAlign(); + va.setVal(alignMap.get(vAlign)); + } + + /** + * add a new paragraph at position of the cursor + * + * @param cursor + * @return the inserted paragraph + */ + public XWPFParagraph insertNewParagraph(XmlCursor cursor) { + if (!isCursorInTableCell(cursor)) { + return null; + } + + String uri = CTP.type.getName().getNamespaceURI(); + String localPart = "p"; + cursor.beginElement(localPart, uri); + cursor.toParent(); + CTP p = (CTP) cursor.getObject(); + XWPFParagraph newP = new XWPFParagraph(p, this); + XmlObject o = null; + while (!(o instanceof CTP) && (cursor.toPrevSibling())) { + o = cursor.getObject(); + } + if ((!(o instanceof CTP)) || (CTP) o == p) { + paragraphs.add(0, newP); + } else { + int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; + paragraphs.add(pos, newP); + } + int i = 0; + cursor.toCursor(p.newCursor()); + while (cursor.toPrevSibling()) { + o = cursor.getObject(); + if (o instanceof CTP || o instanceof CTTbl) + i++; + } + bodyElements.add(i, newP); + cursor.toCursor(p.newCursor()); + cursor.toEndToken(); + return newP; + } + + public XWPFTable insertNewTbl(XmlCursor cursor) { + if (isCursorInTableCell(cursor)) { + String uri = CTTbl.type.getName().getNamespaceURI(); + String localPart = "tbl"; + cursor.beginElement(localPart, uri); + cursor.toParent(); + CTTbl t = (CTTbl) cursor.getObject(); + XWPFTable newT = new XWPFTable(t, this); + cursor.removeXmlContents(); + XmlObject o = null; + while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { + o = cursor.getObject(); + } + if (!(o instanceof CTTbl)) { + tables.add(0, newT); + } else { + int pos = tables.indexOf(getTable((CTTbl) o)) + 1; + tables.add(pos, newT); + } + int i = 0; + cursor = t.newCursor(); + while (cursor.toPrevSibling()) { + o = cursor.getObject(); + if (o instanceof CTP || o instanceof CTTbl) + i++; + } + bodyElements.add(i, newT); + cursor = t.newCursor(); + cursor.toEndToken(); + return newT; + } + return null; + } + + /** + * verifies that cursor is on the right position + */ + private boolean isCursorInTableCell(XmlCursor cursor) { + XmlCursor verify = cursor.newCursor(); + verify.toParent(); + if (verify.getObject() == this.ctTc) { + return true; + } + return false; + } + + /** + * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) + */ + public XWPFParagraph getParagraphArray(int pos) { + if (pos > 0 && pos < paragraphs.size()) { + return paragraphs.get(pos); + } + return null; + } + + /** + * get the to which the TableCell belongs + * + * @see org.apache.poi.xwpf.usermodel.IBody#getPart() + */ + public POIXMLDocumentPart getPart() { + return tableRow.getTable().getPart(); + } + + /** + * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() + */ + public BodyType getPartType() { + return BodyType.TABLECELL; + } + + /** + * get a table by its CTTbl-Object + * + * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) + */ + public XWPFTable getTable(CTTbl ctTable) { + for (int i = 0; i < tables.size(); i++) { + if (getTables().get(i).getCTTbl() == ctTable) return getTables().get(i); + } + return null; + } + + /** + * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) + */ + public XWPFTable getTableArray(int pos) { + if (pos > 0 && pos < tables.size()) { + return tables.get(pos); + } + return null; + } + + /** + * @see org.apache.poi.xwpf.usermodel.IBody#getTables() + */ + public List getTables() { + return Collections.unmodifiableList(tables); + } + + /** + * inserts an existing XWPFTable to the arrays bodyElements and tables + * + * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int, org.apache.poi.xwpf.usermodel.XWPFTable) + */ + @SuppressWarnings("deprecation") public void insertTable(int pos, XWPFTable table) { bodyElements.add(pos, table); int i = 0; @@ -408,90 +406,101 @@ public class XWPFTableCell implements IBody, ICell { } i++; } - tables.add(i, table); - } - - public String getText(){ - StringBuffer text = new StringBuffer(); - for (XWPFParagraph p : paragraphs) { - text.append(p.getText()); - } - return text.toString(); - } - - /** - * extracts all text recursively through embedded tables and embedded SDTs - */ - public String getTextRecursively(){ - - StringBuffer text = new StringBuffer(); - for (int i = 0; i < bodyElements.size(); i++){ - boolean isLast = (i== bodyElements.size()-1)? true : false; - appendBodyElementText(text, bodyElements.get(i), isLast); - } - - return text.toString(); - } - - private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast){ - if (e instanceof XWPFParagraph){ - text.append(((XWPFParagraph)e).getText()); - if (isLast == false){ - text.append('\t'); - } - } else if (e instanceof XWPFTable){ - XWPFTable eTable = (XWPFTable)e; - for (XWPFTableRow row : eTable.getRows()){ - for (XWPFTableCell cell : row.getTableCells()){ - List localBodyElements = cell.getBodyElements(); - for (int i = 0; i < localBodyElements.size(); i++){ - boolean localIsLast = (i== localBodyElements.size()-1)? true : false; - appendBodyElementText(text, localBodyElements.get(i), localIsLast); - } - } - } - - if (isLast == false){ - text.append('\n'); - } - } else if (e instanceof XWPFSDT){ - text.append(((XWPFSDT)e).getContent().getText()); - if (isLast == false){ - text.append('\t'); - } - } + tables.add(i, table); + } + + public String getText() { + StringBuffer text = new StringBuffer(); + for (XWPFParagraph p : paragraphs) { + text.append(p.getText()); + } + return text.toString(); + } + + public void setText(String text) { + CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0); + XWPFParagraph par = new XWPFParagraph(ctP, this); + par.createRun().setText(text); + } + + /** + * extracts all text recursively through embedded tables and embedded SDTs + */ + public String getTextRecursively() { + + StringBuffer text = new StringBuffer(); + for (int i = 0; i < bodyElements.size(); i++) { + boolean isLast = (i == bodyElements.size() - 1) ? true : false; + appendBodyElementText(text, bodyElements.get(i), isLast); + } + + return text.toString(); + } + + private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast) { + if (e instanceof XWPFParagraph) { + text.append(((XWPFParagraph) e).getText()); + if (isLast == false) { + text.append('\t'); + } + } else if (e instanceof XWPFTable) { + XWPFTable eTable = (XWPFTable) e; + for (XWPFTableRow row : eTable.getRows()) { + for (XWPFTableCell cell : row.getTableCells()) { + List localBodyElements = cell.getBodyElements(); + for (int i = 0; i < localBodyElements.size(); i++) { + boolean localIsLast = (i == localBodyElements.size() - 1) ? true : false; + appendBodyElementText(text, localBodyElements.get(i), localIsLast); + } + } + } + + if (isLast == false) { + text.append('\n'); + } + } else if (e instanceof XWPFSDT) { + text.append(((XWPFSDT) e).getContent().getText()); + if (isLast == false) { + text.append('\t'); + } + } } /** - * get the TableCell which belongs to the TableCell - */ - public XWPFTableCell getTableCell(CTTc cell) { - XmlCursor cursor = cell.newCursor(); - cursor.toParent(); - XmlObject o = cursor.getObject(); - if(!(o instanceof CTRow)){ - return null; - } - CTRow row = (CTRow)o; - cursor.toParent(); - o = cursor.getObject(); - cursor.dispose(); - if(! (o instanceof CTTbl)){ - return null; - } - CTTbl tbl = (CTTbl) o; - XWPFTable table = getTable(tbl); - if(table == null){ - return null; - } - XWPFTableRow tableRow = table.getRow(row); - if (tableRow == null) { - return null; - } - return tableRow.getTableCell(cell); - } - - public XWPFDocument getXWPFDocument() { - return part.getXWPFDocument(); - } -} + * get the TableCell which belongs to the TableCell + */ + public XWPFTableCell getTableCell(CTTc cell) { + XmlCursor cursor = cell.newCursor(); + cursor.toParent(); + XmlObject o = cursor.getObject(); + if (!(o instanceof CTRow)) { + return null; + } + CTRow row = (CTRow) o; + cursor.toParent(); + o = cursor.getObject(); + cursor.dispose(); + if (!(o instanceof CTTbl)) { + return null; + } + CTTbl tbl = (CTTbl) o; + XWPFTable table = getTable(tbl); + if (table == null) { + return null; + } + XWPFTableRow tableRow = table.getRow(row); + if (tableRow == null) { + return null; + } + return tableRow.getTableCell(cell); + } + + public XWPFDocument getXWPFDocument() { + return part.getXWPFDocument(); + } + + // Create a map from this XWPF-level enum to the STVerticalJc.Enum values + public static enum XWPFVertAlign { + TOP, CENTER, BOTH, BOTTOM + } +} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java index 627ee3c8d3..5a947efc7a 100644 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java +++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java @@ -31,14 +31,14 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; - -/** - * A row within an {@link XWPFTable}. Rows mostly just have - * sizings and stylings, the interesting content lives inside - * the child {@link XWPFTableCell}s - */ -public class XWPFTableRow { - private CTRow ctRow; + +/** + * A row within an {@link XWPFTable}. Rows mostly just have + * sizings and stylings, the interesting content lives inside + * the child {@link XWPFTableCell}s + */ +public class XWPFTableRow { + private CTRow ctRow; private XWPFTable table; private List tableCells; @@ -52,187 +52,195 @@ public class XWPFTableRow { public CTRow getCtRow() { return ctRow; } - - /** - * create a new XWPFTableCell and add it to the tableCell-list of this tableRow - * @return the newly created XWPFTableCell - */ - public XWPFTableCell createCell() { - XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody()); - tableCells.add(tableCell); - return tableCell; - } - - public XWPFTableCell getCell(int pos) { - if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { - return getTableCells().get(pos); - } - return null; - } - - public void removeCell(int pos) { - if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { - tableCells.remove(pos); - } - } - /** - * adds a new TableCell at the end of this tableRow - */ - public XWPFTableCell addNewTableCell(){ - CTTc cell = ctRow.addNewTc(); - XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.getBody()); - tableCells.add(tableCell); - return tableCell; - } - - /** + + /** + * create a new XWPFTableCell and add it to the tableCell-list of this tableRow + * + * @return the newly created XWPFTableCell + */ + public XWPFTableCell createCell() { + XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody()); + tableCells.add(tableCell); + return tableCell; + } + + public XWPFTableCell getCell(int pos) { + if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { + return getTableCells().get(pos); + } + return null; + } + + public void removeCell(int pos) { + if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { + tableCells.remove(pos); + } + } + + /** + * adds a new TableCell at the end of this tableRow + */ + public XWPFTableCell addNewTableCell() { + CTTc cell = ctRow.addNewTc(); + XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.getBody()); + tableCells.add(tableCell); + return tableCell; + } + + /** * This element specifies the height of the current table row within the * current table. This height shall be used to determine the resulting * height of the table row, which may be absolute or relative (depending on * its attribute values). If omitted, then the table row shall automatically - * resize its height to the height required by its contents (the equivalent - * of an hRule value of auto). - * - * @param height - */ - public void setHeight(int height) { - CTTrPr properties = getTrPr(); - CTHeight h = properties.sizeOfTrHeightArray() == 0 ? properties.addNewTrHeight() : properties.getTrHeightArray(0); - h.setVal(new BigInteger("" + height)); - } - - /** + * resize its height to the height required by its contents (the equivalent + * of an hRule value of auto). + * + * @return height + */ + public int getHeight() { + CTTrPr properties = getTrPr(); + return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue(); + } + + /** * This element specifies the height of the current table row within the * current table. This height shall be used to determine the resulting * height of the table row, which may be absolute or relative (depending on * its attribute values). If omitted, then the table row shall automatically - * resize its height to the height required by its contents (the equivalent - * of an hRule value of auto). - * - * @return height - */ - public int getHeight() { - CTTrPr properties = getTrPr(); - return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue(); - } - - private CTTrPr getTrPr() { - return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr(); - } - - public XWPFTable getTable(){ - return table; - } - - /** - * create and return a list of all XWPFTableCell - * who belongs to this row - * @return a list of {@link XWPFTableCell} - */ - public List getTableICells(){ - - List cells = new ArrayList(); - //Can't use ctRow.getTcList because that only gets table cells - //Can't use ctRow.getSdtList because that only gets sdts that are at cell level + * resize its height to the height required by its contents (the equivalent + * of an hRule value of auto). + * + * @param height + */ + public void setHeight(int height) { + CTTrPr properties = getTrPr(); + CTHeight h = properties.sizeOfTrHeightArray() == 0 ? properties.addNewTrHeight() : properties.getTrHeightArray(0); + h.setVal(new BigInteger("" + height)); + } + + private CTTrPr getTrPr() { + return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr(); + } + + public XWPFTable getTable() { + return table; + } + + /** + * create and return a list of all XWPFTableCell + * who belongs to this row + * + * @return a list of {@link XWPFTableCell} + */ + public List getTableICells() { + + List cells = new ArrayList(); + //Can't use ctRow.getTcList because that only gets table cells + //Can't use ctRow.getSdtList because that only gets sdts that are at cell level XmlCursor cursor = ctRow.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTTc){ - cells.add(new XWPFTableCell((CTTc)o, this, table.getBody())); - } else if (o instanceof CTSdtCell) { - cells.add(new XWPFSDTCell((CTSdtCell)o, this, table.getBody())); - } - } - return cells; - } - - /** - * create and return a list of all XWPFTableCell - * who belongs to this row - * @return a list of {@link XWPFTableCell} - */ - @SuppressWarnings("deprecation") - public List getTableCells(){ - if(tableCells == null){ - List cells = new ArrayList(); - for (CTTc tableCell : ctRow.getTcArray()) { - cells.add(new XWPFTableCell(tableCell, this, table.getBody())); - } - //TODO: it is possible to have an SDT that contains a cell in within a row - //need to modify this code so that it pulls out SDT wrappers around cells, too. - - this.tableCells = cells; - } - return tableCells; - } - - /** + cursor.selectPath("./*"); + while (cursor.toNextSelection()) { + XmlObject o = cursor.getObject(); + if (o instanceof CTTc) { + cells.add(new XWPFTableCell((CTTc) o, this, table.getBody())); + } else if (o instanceof CTSdtCell) { + cells.add(new XWPFSDTCell((CTSdtCell) o, this, table.getBody())); + } + } + return cells; + } + + /** + * create and return a list of all XWPFTableCell + * who belongs to this row + * + * @return a list of {@link XWPFTableCell} + */ + @SuppressWarnings("deprecation") + public List getTableCells() { + if (tableCells == null) { + List cells = new ArrayList(); + for (CTTc tableCell : ctRow.getTcArray()) { + cells.add(new XWPFTableCell(tableCell, this, table.getBody())); + } + //TODO: it is possible to have an SDT that contains a cell in within a row + //need to modify this code so that it pulls out SDT wrappers around cells, too. + + this.tableCells = cells; + } + return tableCells; + } + + /** * returns the XWPFTableCell which belongs to the CTTC cell - * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned - */ - public XWPFTableCell getTableCell(CTTc cell) { - for(int i=0; i 0) { - CTOnOff onoff = trpr.getCantSplitArray(0); - isCant = onoff.getVal().equals(STOnOff.ON); - } - return isCant; - } - - /** - * This attribute controls whether to repeat a table's header row at the top - * of a table split across pages. - * @param repeat - if TRUE, repeat header row at the top of each page of table; - * if FALSE, don't repeat header row. - */ - public void setRepeatHeader(boolean repeat) { - CTTrPr trpr = getTrPr(); - CTOnOff onoff = trpr.addNewTblHeader(); - onoff.setVal(repeat ? STOnOff.ON : STOnOff.OFF); - } - - /** - * Return true if a table's header row should be repeated at the top of a - * table split across pages. - * @return true if table's header row should be repeated at the top of each - * page of table, false otherwise. - */ - public boolean isRepeatHeader() { - boolean repeat = false; - CTTrPr trpr = getTrPr(); - if (trpr.sizeOfTblHeaderArray() > 0) { - CTOnOff rpt = trpr.getTblHeaderArray(0); - repeat = rpt.getVal().equals(STOnOff.ON); - } - return repeat; - } -} + * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned + */ + public XWPFTableCell getTableCell(CTTc cell) { + for (int i = 0; i < tableCells.size(); i++) { + if (tableCells.get(i).getCTTc() == cell) + return tableCells.get(i); + } + return null; + } + + /** + * Return true if the "can't split row" value is true. The logic for this + * attribute is a little unusual: a TRUE value means DON'T allow rows to + * split, FALSE means allow rows to split. + * + * @return true if rows can't be split, false otherwise. + */ + public boolean isCantSplitRow() { + boolean isCant = false; + CTTrPr trpr = getTrPr(); + if (trpr.sizeOfCantSplitArray() > 0) { + CTOnOff onoff = trpr.getCantSplitArray(0); + isCant = onoff.getVal().equals(STOnOff.ON); + } + return isCant; + } + + /** + * This attribute controls whether to allow table rows to split across pages. + * The logic for this attribute is a little unusual: a true value means + * DON'T allow rows to split, false means allow rows to split. + * + * @param split - if true, don't allow rows to be split. If false, allow + * rows to be split. + */ + public void setCantSplitRow(boolean split) { + CTTrPr trpr = getTrPr(); + CTOnOff onoff = trpr.addNewCantSplit(); + onoff.setVal(split ? STOnOff.ON : STOnOff.OFF); + } + + /** + * Return true if a table's header row should be repeated at the top of a + * table split across pages. + * + * @return true if table's header row should be repeated at the top of each + * page of table, false otherwise. + */ + public boolean isRepeatHeader() { + boolean repeat = false; + CTTrPr trpr = getTrPr(); + if (trpr.sizeOfTblHeaderArray() > 0) { + CTOnOff rpt = trpr.getTblHeaderArray(0); + repeat = rpt.getVal().equals(STOnOff.ON); + } + return repeat; + } + + /** + * This attribute controls whether to repeat a table's header row at the top + * of a table split across pages. + * + * @param repeat - if TRUE, repeat header row at the top of each page of table; + * if FALSE, don't repeat header row. + */ + public void setRepeatHeader(boolean repeat) { + CTTrPr trpr = getTrPr(); + CTOnOff onoff = trpr.addNewTblHeader(); + onoff.setVal(repeat ? STOnOff.ON : STOnOff.OFF); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java b/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java index f7ed6df7c7..7243f114d6 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java @@ -33,24 +33,24 @@ import org.junit.runners.Suite; /** * Collects all tests for org.apache.poi.xwpf and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestXWPFBugs.class, - org.apache.poi.xwpf.usermodel.TestXWPFBugs.class, - TestXWPFDocument.class, - TestXWPFWordExtractor.class, - TestXWPFHeaderFooterPolicy.class, - TestXWPFHeader.class, - TestXWPFHeadings.class, - TestXWPFParagraph.class, - TestXWPFRun.class, - TestXWPFTable.class, - TestXWPFStyles.class, - TestXWPFPictureData.class, - TestXWPFNumbering.class, - TestAllExtendedProperties.class, - TestPackageCorePropertiesGetKeywords.class -}) -public final class AllXWPFTests { + */ +@RunWith(Suite.class) +@Suite.SuiteClasses({ + TestXWPFBugs.class, + org.apache.poi.xwpf.usermodel.TestXWPFBugs.class, + TestXWPFDocument.class, + TestXWPFWordExtractor.class, + TestXWPFHeaderFooterPolicy.class, + TestXWPFHeader.class, + TestXWPFHeadings.class, + TestXWPFParagraph.class, + TestXWPFRun.class, + TestXWPFTable.class, + TestXWPFStyles.class, + TestXWPFPictureData.class, + TestXWPFNumbering.class, + TestAllExtendedProperties.class, + TestPackageCorePropertiesGetKeywords.class +}) +public final class AllXWPFTests { } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java index c04f73c934..ff955dadb6 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java @@ -17,13 +17,12 @@ package org.apache.poi.xwpf; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.xwpf.usermodel.XWPFDocument; +import java.io.IOException; + +import junit.framework.TestCase; +import org.apache.poi.POIXMLProperties.CoreProperties; +import org.apache.poi.openxml4j.opc.PackageProperties; +import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr; @@ -31,77 +30,76 @@ import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVect /** * Tests if the {@link CoreProperties#getKeywords()} method. This test has been - * submitted because even though the - * {@link PackageProperties#getKeywordsProperty()} had been present before, the - * {@link CoreProperties#getKeywords()} had been missing. - * - * The author of this has added {@link CoreProperties#getKeywords()} and - * {@link CoreProperties#setKeywords(String)} and this test is supposed to test - * them. - * - * @author Antoni Mylka - * - */ -public final class TestAllExtendedProperties extends TestCase { - public void testGetAllExtendedProperties() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); - CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties(); - assertEquals("Microsoft Office Word",ctProps.getApplication()); - assertEquals("14.0000",ctProps.getAppVersion()); - assertEquals(57,ctProps.getCharacters()); - assertEquals(66,ctProps.getCharactersWithSpaces()); - assertEquals("",ctProps.getCompany()); - assertNull(ctProps.getDigSig()); - assertEquals(0,ctProps.getDocSecurity()); - assertNotNull(ctProps.getDomNode()); - - CTVectorVariant vec = ctProps.getHeadingPairs(); - assertEquals(2,vec.getVector().sizeOfVariantArray()); - assertEquals("Title",vec.getVector().getVariantArray(0).getLpstr()); - assertEquals(1,vec.getVector().getVariantArray(1).getI4()); - - assertFalse(ctProps.isSetHiddenSlides()); - assertEquals(0,ctProps.getHiddenSlides()); - assertFalse(ctProps.isSetHLinks()); - assertNull(ctProps.getHLinks()); - assertNull(ctProps.getHyperlinkBase()); - assertTrue(ctProps.isSetHyperlinksChanged()); - assertFalse(ctProps.getHyperlinksChanged()); - assertEquals(1,ctProps.getLines()); - assertTrue(ctProps.isSetLinksUpToDate()); - assertFalse(ctProps.getLinksUpToDate()); - assertNull(ctProps.getManager()); - assertFalse(ctProps.isSetMMClips()); - assertEquals(0,ctProps.getMMClips()); - assertFalse(ctProps.isSetNotes()); - assertEquals(0,ctProps.getNotes()); - assertEquals(1,ctProps.getPages()); - assertEquals(1,ctProps.getParagraphs()); - assertNull(ctProps.getPresentationFormat()); - assertTrue(ctProps.isSetScaleCrop()); - assertFalse(ctProps.getScaleCrop()); - assertTrue(ctProps.isSetSharedDoc()); - assertFalse(ctProps.getSharedDoc()); - assertFalse(ctProps.isSetSlides()); - assertEquals(0,ctProps.getSlides()); - assertEquals("Normal.dotm",ctProps.getTemplate()); - - CTVectorLpstr vec2 = ctProps.getTitlesOfParts(); - assertEquals(1,vec2.getVector().sizeOfLpstrArray()); - assertEquals("Example Word 2010 Document",vec2.getVector().getLpstrArray(0)); - - assertEquals(3,ctProps.getTotalTime()); - assertEquals(10,ctProps.getWords()); - - // Check the digital signature part - // Won't be there in this file, but we - // need to do this check so that the - // appropriate parts end up in the - // smaller ooxml schemas file - CTDigSigBlob blob = ctProps.getDigSig(); - assertNull(blob); - - blob = CTDigSigBlob.Factory.newInstance(); - blob.setBlob(new byte [] {2,6,7,2,3,4,5,1,2,3}); - } -} + * submitted because even though the + * {@link PackageProperties#getKeywordsProperty()} had been present before, the + * {@link CoreProperties#getKeywords()} had been missing. + *

    + * The author of this has added {@link CoreProperties#getKeywords()} and + * {@link CoreProperties#setKeywords(String)} and this test is supposed to test + * them. + * + * @author Antoni Mylka + */ +public final class TestAllExtendedProperties extends TestCase { + public void testGetAllExtendedProperties() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); + CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties(); + assertEquals("Microsoft Office Word", ctProps.getApplication()); + assertEquals("14.0000", ctProps.getAppVersion()); + assertEquals(57, ctProps.getCharacters()); + assertEquals(66, ctProps.getCharactersWithSpaces()); + assertEquals("", ctProps.getCompany()); + assertNull(ctProps.getDigSig()); + assertEquals(0, ctProps.getDocSecurity()); + assertNotNull(ctProps.getDomNode()); + + CTVectorVariant vec = ctProps.getHeadingPairs(); + assertEquals(2, vec.getVector().sizeOfVariantArray()); + assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr()); + assertEquals(1, vec.getVector().getVariantArray(1).getI4()); + + assertFalse(ctProps.isSetHiddenSlides()); + assertEquals(0, ctProps.getHiddenSlides()); + assertFalse(ctProps.isSetHLinks()); + assertNull(ctProps.getHLinks()); + assertNull(ctProps.getHyperlinkBase()); + assertTrue(ctProps.isSetHyperlinksChanged()); + assertFalse(ctProps.getHyperlinksChanged()); + assertEquals(1, ctProps.getLines()); + assertTrue(ctProps.isSetLinksUpToDate()); + assertFalse(ctProps.getLinksUpToDate()); + assertNull(ctProps.getManager()); + assertFalse(ctProps.isSetMMClips()); + assertEquals(0, ctProps.getMMClips()); + assertFalse(ctProps.isSetNotes()); + assertEquals(0, ctProps.getNotes()); + assertEquals(1, ctProps.getPages()); + assertEquals(1, ctProps.getParagraphs()); + assertNull(ctProps.getPresentationFormat()); + assertTrue(ctProps.isSetScaleCrop()); + assertFalse(ctProps.getScaleCrop()); + assertTrue(ctProps.isSetSharedDoc()); + assertFalse(ctProps.getSharedDoc()); + assertFalse(ctProps.isSetSlides()); + assertEquals(0, ctProps.getSlides()); + assertEquals("Normal.dotm", ctProps.getTemplate()); + + CTVectorLpstr vec2 = ctProps.getTitlesOfParts(); + assertEquals(1, vec2.getVector().sizeOfLpstrArray()); + assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0)); + + assertEquals(3, ctProps.getTotalTime()); + assertEquals(10, ctProps.getWords()); + + // Check the digital signature part + // Won't be there in this file, but we + // need to do this check so that the + // appropriate parts end up in the + // smaller ooxml schemas file + CTDigSigBlob blob = ctProps.getDigSig(); + assertNull(blob); + + blob = CTDigSigBlob.Factory.newInstance(); + blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3}); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java index 4b37623df1..85a21f12b7 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java @@ -17,36 +17,34 @@ package org.apache.poi.xwpf; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.xwpf.usermodel.XWPFDocument; +import java.io.IOException; + +import junit.framework.TestCase; +import org.apache.poi.POIXMLProperties.CoreProperties; +import org.apache.poi.openxml4j.opc.PackageProperties; +import org.apache.poi.xwpf.usermodel.XWPFDocument; /** * Tests if the {@link CoreProperties#getKeywords()} method. This test has been - * submitted because even though the - * {@link PackageProperties#getKeywordsProperty()} had been present before, the - * {@link CoreProperties#getKeywords()} had been missing. - * - * The author of this has added {@link CoreProperties#getKeywords()} and - * {@link CoreProperties#setKeywords(String)} and this test is supposed to test - * them. - * - * @author Antoni Mylka - * - */ -public final class TestPackageCorePropertiesGetKeywords extends TestCase { - public void testGetSetKeywords() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); - String keywords = doc.getProperties().getCoreProperties().getKeywords(); - assertEquals("extractor, test, rdf", keywords); - - doc.getProperties().getCoreProperties().setKeywords("test, keywords"); - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - keywords = doc.getProperties().getCoreProperties().getKeywords(); - assertEquals("test, keywords",keywords); - } -} + * submitted because even though the + * {@link PackageProperties#getKeywordsProperty()} had been present before, the + * {@link CoreProperties#getKeywords()} had been missing. + *

    + * The author of this has added {@link CoreProperties#getKeywords()} and + * {@link CoreProperties#setKeywords(String)} and this test is supposed to test + * them. + * + * @author Antoni Mylka + */ +public final class TestPackageCorePropertiesGetKeywords extends TestCase { + public void testGetSetKeywords() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); + String keywords = doc.getProperties().getCoreProperties().getKeywords(); + assertEquals("extractor, test, rdf", keywords); + + doc.getProperties().getCoreProperties().setKeywords("test, keywords"); + doc = XWPFTestDataSamples.writeOutAndReadBack(doc); + keywords = doc.getProperties().getCoreProperties().getKeywords(); + assertEquals("test, keywords", keywords); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java index 055e47076d..6f7e4b689e 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java @@ -40,7 +40,7 @@ import org.junit.Test; public class TestXWPFBugs { /** * A word document that's encrypted with non-standard - * Encryption options, and no cspname section. See bug 53475 + * Encryption options, and no cspname section. See bug 53475 */ @Test public void bug53475NoCSPName() throws Exception { @@ -54,7 +54,7 @@ public class TestXWPFBugs { assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx()); // Check it can be decoded - Decryptor d = Decryptor.getInstance(info); + Decryptor d = Decryptor.getInstance(info); assertTrue("Unable to process: document is encrypted", d.verifyPassword("solrcell")); // Check we can read the word document in that @@ -66,7 +66,7 @@ public class TestXWPFBugs { assertNotNull(text); assertEquals("This is password protected Word document.", text.trim()); ex.close(); - + filesystem.close(); } @@ -90,7 +90,7 @@ public class TestXWPFBugs { assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx()); // Check it can be decoded - Decryptor d = Decryptor.getInstance(info); + Decryptor d = Decryptor.getInstance(info); assertTrue("Unable to process: document is encrypted", d.verifyPassword("pass")); // Check we can read the word document in that @@ -103,7 +103,7 @@ public class TestXWPFBugs { // I know ... a stupid typo, maybe next time ... assertEquals("The is a password protected document.", text.trim()); ex.close(); - + filesystem.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java index 05d6b2f844..929d430413 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java @@ -20,7 +20,6 @@ package org.apache.poi.xwpf.extractor; import java.io.IOException; import junit.framework.TestCase; - import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; @@ -28,19 +27,20 @@ public class TestExternalEntities extends TestCase { /** * Get text out of the simple file - * @throws IOException + * + * @throws IOException */ public void testFile() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ExternalEntityInText.docx"); XWPFWordExtractor extractor = new XWPFWordExtractor(doc); String text = extractor.getText(); - + assertTrue(text.length() > 0); // Check contents, they should not contain the text from POI web site after colon! assertEquals("Here should not be the POI web site: \"\"", text.trim()); - + extractor.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java index 00408829df..48330bbeeb 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java @@ -22,7 +22,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; - import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; @@ -33,7 +32,8 @@ public class TestXWPFWordExtractor extends TestCase { /** * Get text out of the simple file - * @throws IOException + * + * @throws IOException */ public void testGetSimpleText() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); @@ -59,13 +59,14 @@ public class TestXWPFWordExtractor extends TestCase { } } assertEquals(3, ps); - + extractor.close(); } /** * Tests getting the text out of a complex file - * @throws IOException + * + * @throws IOException */ public void testGetComplexText() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx"); @@ -97,7 +98,7 @@ public class TestXWPFWordExtractor extends TestCase { } } assertEquals(134, ps); - + extractor.close(); } @@ -108,23 +109,23 @@ public class TestXWPFWordExtractor extends TestCase { // Now check contents extractor.setFetchHyperlinks(false); assertEquals( - "This is a test document.\nThis bit is in bold and italic\n" + - "Back to normal\n" + - "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + - "We have a hyperlink here, and another.\n", + "This is a test document.\nThis bit is in bold and italic\n" + + "Back to normal\n" + + "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + + "We have a hyperlink here, and another.\n", extractor.getText() ); // One hyperlink is a real one, one is just to the top of page extractor.setFetchHyperlinks(true); assertEquals( - "This is a test document.\nThis bit is in bold and italic\n" + - "Back to normal\n" + - "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + - "We have a hyperlink here, and another.\n", + "This is a test document.\nThis bit is in bold and italic\n" + + "Back to normal\n" + + "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + + "We have a hyperlink here, and another.\n", extractor.getText() ); - + extractor.close(); } @@ -173,7 +174,7 @@ public class TestXWPFWordExtractor extends TestCase { "Footer Left\tFooter Middle\tFooter Right\n", extractor.getText() ); - + extractor.close(); } @@ -183,7 +184,7 @@ public class TestXWPFWordExtractor extends TestCase { String text = extractor.getText(); assertTrue(text.contains("snoska")); assertTrue(text.contains("Eto ochen prostoy[footnoteRef:1] text so snoskoy")); - + extractor.close(); } @@ -193,7 +194,7 @@ public class TestXWPFWordExtractor extends TestCase { XWPFWordExtractor extractor = new XWPFWordExtractor(doc); assertTrue(extractor.getText().contains("snoska")); - + extractor.close(); } @@ -204,7 +205,7 @@ public class TestXWPFWordExtractor extends TestCase { String text = extractor.getText(); assertTrue("Unable to find expected word in text\n" + text, text.contains("testdoc")); assertTrue("Unable to find expected word in text\n" + text, text.contains("test phrase")); - + extractor.close(); } @@ -214,7 +215,7 @@ public class TestXWPFWordExtractor extends TestCase { String text = extractor.getText(); assertTrue(text.contains("XXX")); assertTrue(text.contains("tilaka [endnoteRef:2]or 'tika'")); - + extractor.close(); } @@ -224,7 +225,7 @@ public class TestXWPFWordExtractor extends TestCase { assertTrue(extractor.getText().contains("pendant worn")); assertTrue(extractor.getText().contains("extremely well")); - + extractor.close(); } @@ -235,14 +236,15 @@ public class TestXWPFWordExtractor extends TestCase { assertTrue(extractor.getText().contains("Section 1")); assertTrue(extractor.getText().contains("Section 2")); assertTrue(extractor.getText().contains("Section 3")); - + extractor.close(); } /** * Test that we can open and process .docm - * (macro enabled) docx files (bug #45690) - * @throws IOException + * (macro enabled) docx files (bug #45690) + * + * @throws IOException */ public void testDOCMFiles() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm"); @@ -251,35 +253,37 @@ public class TestXWPFWordExtractor extends TestCase { assertTrue(extractor.getText().contains("2004")); assertTrue(extractor.getText().contains("2008")); assertTrue(extractor.getText().contains("(120 ")); - + extractor.close(); } - + /** * Test that we handle things like tabs and - * carriage returns properly in the text that - * we're extracting (bug #49189) - * @throws IOException + * carriage returns properly in the text that + * we're extracting (bug #49189) + * + * @throws IOException */ public void testDocTabs() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - // Check bits - assertTrue(extractor.getText().contains("a")); - assertTrue(extractor.getText().contains("\t")); - assertTrue(extractor.getText().contains("b")); - - // Now check the first paragraph in total - assertTrue(extractor.getText().contains("a\tb\n")); - - extractor.close(); + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx"); + XWPFWordExtractor extractor = new XWPFWordExtractor(doc); + + // Check bits + assertTrue(extractor.getText().contains("a")); + assertTrue(extractor.getText().contains("\t")); + assertTrue(extractor.getText().contains("b")); + + // Now check the first paragraph in total + assertTrue(extractor.getText().contains("a\tb\n")); + + extractor.close(); } - + /** * The output should not contain field codes, e.g. those specified in the * w:instrText tag (spec sec. 17.16.23) - * @throws IOException + * + * @throws IOException */ public void testNoFieldCodes() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx"); @@ -288,14 +292,15 @@ public class TestXWPFWordExtractor extends TestCase { assertTrue(text.length() > 0); assertFalse(text.contains("AUTHOR")); assertFalse(text.contains("CREATEDATE")); - + extractor.close(); } - + /** * The output should contain the values of simple fields, those specified * with the fldSimple element (spec sec. 17.16.19) - * @throws IOException + * + * @throws IOException */ public void testFldSimpleContent() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx"); @@ -303,7 +308,7 @@ public class TestXWPFWordExtractor extends TestCase { String text = extractor.getText(); assertTrue(text.length() > 0); assertTrue(text.contains("FldSimple.docx")); - + extractor.close(); } @@ -316,12 +321,13 @@ public class TestXWPFWordExtractor extends TestCase { XWPFWordExtractor extractor = new XWPFWordExtractor(doc); String text = extractor.getText(); assertTrue(text.length() > 0); - + extractor.close(); } - + /** * Test for basic extraction of SDT content + * * @throws IOException */ public void testSimpleControlContent() throws IOException { @@ -345,19 +351,19 @@ public class TestXWPFWordExtractor extends TestCase { XWPFWordExtractor ex = new XWPFWordExtractor(doc); String s = ex.getText().toLowerCase(); int hits = 0; - - for (String targ : targs){ + + for (String targ : targs) { boolean hit = false; - if (s.indexOf(targ) > -1){ + if (s.indexOf(targ) > -1) { hit = true; hits++; } - assertEquals("controlled content loading-"+targ, true, hit); + assertEquals("controlled content loading-" + targ, true, hit); } assertEquals("controlled content loading hit count", targs.length, hits); ex.close(); - - + + doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); targs = new String[]{ "bb", @@ -366,48 +372,50 @@ public class TestXWPFWordExtractor extends TestCase { }; ex = new XWPFWordExtractor(doc); s = ex.getText().toLowerCase(); - + //At one point in development there were three copies of the text. //This ensures that there is only one copy. - for (String targ : targs){ + for (String targ : targs) { Matcher m = Pattern.compile(targ).matcher(s); int hit = 0; while (m.find()) { hit++; } - assertEquals("controlled content loading-"+targ, 1, hit); + assertEquals("controlled content loading-" + targ, 1, hit); } //"test\n" appears twice: once as the "title" and once in the text. //This also happens when you save this document as text from MSWord. Matcher m = Pattern.compile("test\n").matcher(s); int hit = 0; - while (m.find()){ + while (m.find()) { hit++; } assertEquals("test", 2, hit); ex.close(); } - /** No Header or Footer in document */ + /** + * No Header or Footer in document + */ public void testBug55733() throws Exception { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); + XWPFWordExtractor extractor = new XWPFWordExtractor(doc); // Check it gives text without error extractor.getText(); extractor.close(); } - - public void testCheckboxes() throws IOException { + + public void testCheckboxes() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx"); System.out.println(doc); XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - + assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" + - "Or checked: |X|\n\n\n\n\n" + - "Test a checkbox within a textbox: |_| -> |X|\n\n\n" + - "In Table:\n|_|\t|X|\n\n\n" + - "In Sequence:\n|X||_||X|\n", extractor.getText()); + "Or checked: |X|\n\n\n\n\n" + + "Test a checkbox within a textbox: |_| -> |X|\n\n\n" + + "In Table:\n|_|\t|X|\n\n\n" + + "In Sequence:\n|X||_||X|\n", extractor.getText()); extractor.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java index 3df111bfab..aa1167dd01 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java @@ -17,86 +17,85 @@ package org.apache.poi.xwpf.model; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; +import java.io.IOException; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; /** - * Tests for the various XWPF decorators - */ -public class TestXWPFDecorators extends TestCase { - private XWPFDocument simple; - private XWPFDocument hyperlink; - private XWPFDocument comments; - - protected void setUp() throws IOException { - simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx"); - } - - @SuppressWarnings("deprecation") - public void testHyperlink() { - XWPFParagraph ps; - XWPFParagraph ph; - assertEquals(7, simple.getParagraphs().size()); - assertEquals(5, hyperlink.getParagraphs().size()); - - // Simple text - ps = simple.getParagraphs().get(0); - assertEquals("I am a test document", ps.getParagraphText()); - assertEquals(1, ps.getRuns().size()); - - ph = hyperlink.getParagraphs().get(4); - assertEquals("We have a hyperlink here, and another.", ph.getParagraphText()); - assertEquals(3, ph.getRuns().size()); - - - // The proper way to do hyperlinks(!) - assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun); - assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun); - assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun); - assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun); - - XWPFHyperlinkRun link = (XWPFHyperlinkRun)ph.getRuns().get(1); - assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL()); - - - // Test the old style decorator - // You probably don't want to still be using it... - assertEquals( - "I am a test document", - (new XWPFHyperlinkDecorator(ps, null, false)).getText() - ); - assertEquals( - "I am a test document", - (new XWPFHyperlinkDecorator(ps, null, true)).getText() - ); - - assertEquals( - "We have a hyperlink here, and another.hyperlink", - (new XWPFHyperlinkDecorator(ph, null, false)).getText() - ); - assertEquals( - "We have a hyperlink here, and another.hyperlink ", - (new XWPFHyperlinkDecorator(ph, null, true)).getText() - ); - } - - public void testComments() { - int numComments = 0; - for(XWPFParagraph p : comments.getParagraphs()) { - XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null); - if(d.getCommentText().length() > 0) { - numComments++; - assertEquals("\tComment by", d.getCommentText().substring(0, 11)); - } - } - assertEquals(3, numComments); - } -} + * Tests for the various XWPF decorators + */ +public class TestXWPFDecorators extends TestCase { + private XWPFDocument simple; + private XWPFDocument hyperlink; + private XWPFDocument comments; + + protected void setUp() throws IOException { + simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); + hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); + comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx"); + } + + @SuppressWarnings("deprecation") + public void testHyperlink() { + XWPFParagraph ps; + XWPFParagraph ph; + assertEquals(7, simple.getParagraphs().size()); + assertEquals(5, hyperlink.getParagraphs().size()); + + // Simple text + ps = simple.getParagraphs().get(0); + assertEquals("I am a test document", ps.getParagraphText()); + assertEquals(1, ps.getRuns().size()); + + ph = hyperlink.getParagraphs().get(4); + assertEquals("We have a hyperlink here, and another.", ph.getParagraphText()); + assertEquals(3, ph.getRuns().size()); + + + // The proper way to do hyperlinks(!) + assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun); + assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun); + assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun); + assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun); + + XWPFHyperlinkRun link = (XWPFHyperlinkRun) ph.getRuns().get(1); + assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL()); + + + // Test the old style decorator + // You probably don't want to still be using it... + assertEquals( + "I am a test document", + (new XWPFHyperlinkDecorator(ps, null, false)).getText() + ); + assertEquals( + "I am a test document", + (new XWPFHyperlinkDecorator(ps, null, true)).getText() + ); + + assertEquals( + "We have a hyperlink here, and another.hyperlink", + (new XWPFHyperlinkDecorator(ph, null, false)).getText() + ); + assertEquals( + "We have a hyperlink here, and another.hyperlink ", + (new XWPFHyperlinkDecorator(ph, null, true)).getText() + ); + } + + public void testComments() { + int numComments = 0; + for (XWPFParagraph p : comments.getParagraphs()) { + XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null); + if (d.getCommentText().length() > 0) { + numComments++; + assertEquals("\tComment by", d.getCommentText().substring(0, 11)); + } + } + assertEquals(3, numComments); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java index 7d70866e89..d461265d48 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java @@ -20,7 +20,6 @@ package org.apache.poi.xwpf.model; import java.io.IOException; import junit.framework.TestCase; - import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; @@ -28,130 +27,130 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument; * Tests for XWPF Header Footer Stuff */ public class TestXWPFHeaderFooterPolicy extends TestCase { - private XWPFDocument noHeader; - private XWPFDocument header; - private XWPFDocument headerFooter; - private XWPFDocument footer; - private XWPFDocument oddEven; - private XWPFDocument diffFirst; - - protected void setUp() throws IOException { - - noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx"); - header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); - headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx"); - footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx"); - oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx"); - diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); - } - - public void testPolicy() { - XWPFHeaderFooterPolicy policy; - - policy = noHeader.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getDefaultFooter()); - - assertNull(policy.getHeader(1)); - assertNull(policy.getHeader(2)); - assertNull(policy.getHeader(3)); - assertNull(policy.getFooter(1)); - assertNull(policy.getFooter(2)); - assertNull(policy.getFooter(3)); - - - policy = header.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNull(policy.getDefaultFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertNull(policy.getFooter(1)); - assertNull(policy.getFooter(2)); - assertNull(policy.getFooter(3)); - - - policy = footer.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - - assertNull(policy.getHeader(1)); - assertNull(policy.getHeader(2)); - assertNull(policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = headerFooter.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = oddEven.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getEvenPageHeader()); - assertNotNull(policy.getEvenPageFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getEvenPageHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getEvenPageFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = diffFirst.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getFirstPageFooter()); - assertNull(policy.getEvenPageHeader()); - assertNull(policy.getEvenPageFooter()); - - assertEquals(policy.getFirstPageHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getFirstPageFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - } - - public void testContents() { - XWPFHeaderFooterPolicy policy; - - // Test a few simple bits off a simple header - policy = diffFirst.getHeaderFooterPolicy(); - - assertEquals( - "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n", - policy.getFirstPageHeader().getText() - ); - assertEquals( - "First header column!\tMid header\tRight header!\n", - policy.getDefaultHeader().getText() - ); - - - // And a few bits off a more complex header - policy = oddEven.getHeaderFooterPolicy(); - - assertEquals( - "[ODD Page Header text]\n\n", - policy.getDefaultHeader().getText() - ); - assertEquals( - "[This is an Even Page, with a Header]\n\n", - policy.getEvenPageHeader().getText() - ); - } + private XWPFDocument noHeader; + private XWPFDocument header; + private XWPFDocument headerFooter; + private XWPFDocument footer; + private XWPFDocument oddEven; + private XWPFDocument diffFirst; + + protected void setUp() throws IOException { + + noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx"); + header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); + headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx"); + footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx"); + oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx"); + diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); + } + + public void testPolicy() { + XWPFHeaderFooterPolicy policy; + + policy = noHeader.getHeaderFooterPolicy(); + assertNull(policy.getDefaultHeader()); + assertNull(policy.getDefaultFooter()); + + assertNull(policy.getHeader(1)); + assertNull(policy.getHeader(2)); + assertNull(policy.getHeader(3)); + assertNull(policy.getFooter(1)); + assertNull(policy.getFooter(2)); + assertNull(policy.getFooter(3)); + + + policy = header.getHeaderFooterPolicy(); + assertNotNull(policy.getDefaultHeader()); + assertNull(policy.getDefaultFooter()); + + assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); + assertNull(policy.getFooter(1)); + assertNull(policy.getFooter(2)); + assertNull(policy.getFooter(3)); + + + policy = footer.getHeaderFooterPolicy(); + assertNull(policy.getDefaultHeader()); + assertNotNull(policy.getDefaultFooter()); + + assertNull(policy.getHeader(1)); + assertNull(policy.getHeader(2)); + assertNull(policy.getHeader(3)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); + + + policy = headerFooter.getHeaderFooterPolicy(); + assertNotNull(policy.getDefaultHeader()); + assertNotNull(policy.getDefaultFooter()); + + assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); + + + policy = oddEven.getHeaderFooterPolicy(); + assertNotNull(policy.getDefaultHeader()); + assertNotNull(policy.getDefaultFooter()); + assertNotNull(policy.getEvenPageHeader()); + assertNotNull(policy.getEvenPageFooter()); + + assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); + assertEquals(policy.getEvenPageHeader(), policy.getHeader(2)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); + assertEquals(policy.getEvenPageFooter(), policy.getFooter(2)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); + + + policy = diffFirst.getHeaderFooterPolicy(); + assertNotNull(policy.getDefaultHeader()); + assertNotNull(policy.getDefaultFooter()); + assertNotNull(policy.getFirstPageHeader()); + assertNotNull(policy.getFirstPageFooter()); + assertNull(policy.getEvenPageHeader()); + assertNull(policy.getEvenPageFooter()); + + assertEquals(policy.getFirstPageHeader(), policy.getHeader(1)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); + assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); + assertEquals(policy.getFirstPageFooter(), policy.getFooter(1)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); + assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); + } + + public void testContents() { + XWPFHeaderFooterPolicy policy; + + // Test a few simple bits off a simple header + policy = diffFirst.getHeaderFooterPolicy(); + + assertEquals( + "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n", + policy.getFirstPageHeader().getText() + ); + assertEquals( + "First header column!\tMid header\tRight header!\n", + policy.getDefaultHeader().getText() + ); + + + // And a few bits off a more complex header + policy = oddEven.getHeaderFooterPolicy(); + + assertEquals( + "[ODD Page Header text]\n\n", + policy.getDefaultHeader().getText() + ); + assertEquals( + "[This is an Even Page, with a Header]\n\n", + policy.getEvenPageHeader().getText() + ); + } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java index d3e4758e1f..0a309a8306 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java @@ -44,7 +44,7 @@ public class TestChangeTracking { assertFalse(document.isTrackRevisions()); document.setTrackRevisions(true); - + assertTrue(document.isTrackRevisions()); } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java index 8fd7f97e04..78df19c009 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java @@ -19,11 +19,9 @@ package org.apache.poi.xwpf.usermodel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange; import org.junit.Test; @@ -32,14 +30,14 @@ public class TestXWPFBugs { @Test public void bug55802() throws Exception { String blabla = - "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n"+ - "\nalt\u0131, yedi, sekiz, dokuz, on.\n"+ - "\nK\u0131rm\u0131z\u0131 don,\n"+ - "\ngel bizim bah\u00e7eye kon,\n"+ - "\nsar\u0131 limon"; + "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" + + "\nalt\u0131, yedi, sekiz, dokuz, on.\n" + + "\nK\u0131rm\u0131z\u0131 don,\n" + + "\ngel bizim bah\u00e7eye kon,\n" + + "\nsar\u0131 limon"; XWPFDocument doc = new XWPFDocument(); XWPFRun run = doc.createParagraph().createRun(); - + for (String str : blabla.split("\n")) { run.setText(str); run.addBreak(); @@ -55,40 +53,40 @@ public class TestXWPFBugs { assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial"); } - + @Test public void bug57312_NullPointException() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx"); assertNotNull(doc); - - for( IBodyElement bodyElement : doc.getBodyElements()){ + + for (IBodyElement bodyElement : doc.getBodyElements()) { BodyElementType elementType = bodyElement.getElementType(); - - if(elementType == BodyElementType.PARAGRAPH) { + + if (elementType == BodyElementType.PARAGRAPH) { XWPFParagraph paragraph = (XWPFParagraph) bodyElement; - - for (IRunElement iRunElem : paragraph.getIRuns()){ - - if (iRunElem instanceof XWPFRun){ + + for (IRunElement iRunElem : paragraph.getIRuns()) { + + if (iRunElem instanceof XWPFRun) { XWPFRun runElement = (XWPFRun) iRunElem; - + UnderlinePatterns underline = runElement.getUnderline(); assertNotNull(underline); - + //System.out.println("Found: " + underline + ": " + runElement.getText(0)); } } - } + } } } - + @Test public void test56392() throws IOException, OpenXML4JException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx"); - assertNotNull(doc); + assertNotNull(doc); } - + /** * Removing a run needs to remove it from both Runs and IRuns */ @@ -97,7 +95,7 @@ public class TestXWPFBugs { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); assertNotNull(doc); assertEquals(3, doc.getParagraphs().size()); - + for (XWPFParagraph paragraph : doc.getParagraphs()) { paragraph.removeRun(0); assertNotNull(paragraph.getText()); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java index 9d8243959a..f46fd716b4 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java @@ -23,7 +23,6 @@ import java.util.Arrays; import java.util.List; import junit.framework.TestCase; - import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLProperties; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; @@ -44,8 +43,8 @@ public final class TestXWPFDocument extends TestCase { OPCPackage pack = doc.getPackage(); boolean found = false; - for(PackagePart part : pack.getParts()) { - if(part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) { + for (PackagePart part : pack.getParts()) { + if (part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) { found = true; } if (false) { @@ -106,7 +105,7 @@ public final class TestXWPFDocument extends TestCase { assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); } - public void testAddParagraph() throws IOException{ + public void testAddParagraph() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); assertEquals(3, doc.getParagraphs().size()); @@ -129,15 +128,15 @@ public final class TestXWPFDocument extends TestCase { public void testAddPicture() throws IOException, InvalidFormatException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg"); - String relationId = doc.addPictureData(jpeg,XWPFDocument.PICTURE_TYPE_JPEG); + String relationId = doc.addPictureData(jpeg, XWPFDocument.PICTURE_TYPE_JPEG); byte[] newJpeg = ((XWPFPictureData) doc.getRelationById(relationId)).getData(); - assertEquals(newJpeg.length,jpeg.length); - for (int i = 0 ; i < jpeg.length ; i++) - { - assertEquals(newJpeg[i],jpeg[i]); + assertEquals(newJpeg.length, jpeg.length); + for (int i = 0; i < jpeg.length; i++) { + assertEquals(newJpeg[i], jpeg[i]); } } + public void testAllPictureFormats() throws IOException, InvalidFormatException { XWPFDocument doc = new XWPFDocument(); @@ -235,7 +234,7 @@ public final class TestXWPFDocument extends TestCase { os.close(); XWPFHeader xwpfHeader = doc.getHeaderArray(0); PackageRelationship relationship = xwpfHeader.getPackagePart().addRelationship(partName, TargetMode.INTERNAL, jpgRelation.getRelation()); - XWPFPictureData newPicData = new XWPFPictureData(newImagePart,relationship); + XWPFPictureData newPicData = new XWPFPictureData(newImagePart, relationship); /* new part is now ready to rumble */ assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); @@ -267,7 +266,7 @@ public final class TestXWPFDocument extends TestCase { List allPackagePictures = doc.getAllPackagePictures(); assertNotNull(allPictures); - assertEquals(3,allPictures.size()); + assertEquals(3, allPictures.size()); for (XWPFPictureData xwpfPictureData : allPictures) { assertTrue(allPackagePictures.contains(xwpfPictureData)); } @@ -287,7 +286,7 @@ public final class TestXWPFDocument extends TestCase { List allPackagePictures = doc.getAllPackagePictures(); assertNotNull(allPackagePictures); - assertEquals(5,allPackagePictures.size()); + assertEquals(5, allPackagePictures.size()); try { allPackagePictures.add(allPackagePictures.get(0)); @@ -301,22 +300,22 @@ public final class TestXWPFDocument extends TestCase { public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - assertEquals(1,doc.getAllPackagePictures().size()); + assertEquals(1, doc.getAllPackagePictures().size()); byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg"); String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG); - assertEquals(2,doc.getAllPackagePictures().size()); + assertEquals(2, doc.getAllPackagePictures().size()); /* copy data, to avoid instance-equality */ byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length); String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG); - assertEquals(id1,id2); + assertEquals(id1, id2); doc.getPackage().revert(); } public void testPictureHandlingHeaderDocumentImages() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx"); - assertEquals(1,doc.getAllPictures().size()); - assertEquals(1,doc.getAllPackagePictures().size()); - assertEquals(1,doc.getHeaderArray(0).getAllPictures().size()); + assertEquals(1, doc.getAllPictures().size()); + assertEquals(1, doc.getAllPackagePictures().size()); + assertEquals(1, doc.getHeaderArray(0).getAllPictures().size()); doc.getPackage().revert(); } @@ -324,18 +323,19 @@ public final class TestXWPFDocument extends TestCase { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); XWPFHeader xwpfHeader = doc.getHeaderArray(0); - assertEquals(3,doc.getAllPictures().size()); - assertEquals(3,xwpfHeader.getAllPictures().size()); - assertEquals(5,doc.getAllPackagePictures().size()); + assertEquals(3, doc.getAllPictures().size()); + assertEquals(3, xwpfHeader.getAllPictures().size()); + assertEquals(5, doc.getAllPackagePictures().size()); byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg"); String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG); POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1"); XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id); - assertSame(part1,part2); + assertSame(part1, part2); doc.getPackage().revert(); } + public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx"); POIXMLProperties properties = doc.getProperties(); @@ -352,7 +352,7 @@ public final class TestXWPFDocument extends TestCase { assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters()); } - public void testSettings(){ + public void testSettings() { XWPFSettings settings = new XWPFSettings(); settings.setZoomPercent(50); assertEquals(50, settings.getZoomPercent()); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java index fb97bf594e..0915de0fef 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java @@ -19,52 +19,50 @@ package org.apache.poi.xwpf.usermodel; import java.io.IOException; import java.math.BigInteger; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; - -public class TestXWPFFootnotes extends TestCase { - - public void testAddFootnotesToDocument() throws IOException{ - XWPFDocument docOut = new XWPFDocument(); - - BigInteger noteId = BigInteger.valueOf(1); - - XWPFFootnotes footnotes = docOut.createFootnotes(); - CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance(); - ctNote.setId(noteId); - ctNote.setType(STFtnEdn.NORMAL); - footnotes.addFootnote(ctNote); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue()); - assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL); - } - - /** - * Bug 55066 - avoid double loading the footnotes - */ - public void testLoadFootnotesOnce() throws IOException{ - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - List footnotes = doc.getFootnotes(); - int hits = 0; - for (XWPFFootnote fn : footnotes){ - for (IBodyElement e : fn.getBodyElements()){ - if (e instanceof XWPFParagraph){ - String txt = ((XWPFParagraph)e).getText(); - if (txt.indexOf("Footnote_sdt") > -1){ - hits++; - } - } - } - } - assertEquals("Load footnotes once", 1, hits); - } -} - +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; + +public class TestXWPFFootnotes extends TestCase { + + public void testAddFootnotesToDocument() throws IOException { + XWPFDocument docOut = new XWPFDocument(); + + BigInteger noteId = BigInteger.valueOf(1); + + XWPFFootnotes footnotes = docOut.createFootnotes(); + CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance(); + ctNote.setId(noteId); + ctNote.setType(STFtnEdn.NORMAL); + footnotes.addFootnote(ctNote); + + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); + + XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue()); + assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL); + } + + /** + * Bug 55066 - avoid double loading the footnotes + */ + public void testLoadFootnotesOnce() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); + List footnotes = doc.getFootnotes(); + int hits = 0; + for (XWPFFootnote fn : footnotes) { + for (IBodyElement e : fn.getBodyElements()) { + if (e instanceof XWPFParagraph) { + String txt = ((XWPFParagraph) e).getText(); + if (txt.indexOf("Footnote_sdt") > -1) { + hits++; + } + } + } + } + assertEquals("Load footnotes once", 1, hits); + } +} + diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java index a607d0e3fd..172c0eb16d 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java @@ -17,13 +17,12 @@ package org.apache.poi.xwpf.usermodel; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import java.io.IOException; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; @@ -159,25 +158,25 @@ public final class TestXWPFHeader extends TestCase { assertEquals("First paragraph for the footer", paras[0].getText()); assertEquals("Second paragraph for the footer", paras[1].getText()); } - - public void testSetWatermark() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - - // No header is set (yet) - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); + + public void testSetWatermark() throws IOException { + XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); + + // No header is set (yet) + XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); + assertNull(policy.getDefaultHeader()); assertNull(policy.getFirstPageHeader()); assertNull(policy.getDefaultFooter()); policy.createWatermark("DRAFT"); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - - // Re-open, and check - XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - policy = reopened.getHeaderFooterPolicy(); + assertNotNull(policy.getDefaultHeader()); + assertNotNull(policy.getFirstPageHeader()); + assertNotNull(policy.getEvenPageHeader()); + + // Re-open, and check + XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); + policy = reopened.getHeaderFooterPolicy(); assertNotNull(policy.getDefaultHeader()); assertNotNull(policy.getFirstPageHeader()); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java index ca74d81e2f..b084634829 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java @@ -16,39 +16,38 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; - -/** - * @author Paolo Mottadelli - */ -public final class TestXWPFHeadings extends TestCase{ - private static final String HEADING1 = "Heading1"; - - public void testSetParagraphStyle() throws IOException, XmlException { - //new clean instance of paragraph - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx"); - XWPFParagraph p = doc.createParagraph(); - XWPFRun run = p.createRun(); - run.setText("Heading 1"); - - CTSdtBlock block = doc.getDocument().getBody().addNewSdt(); - - assertNull(p.getStyle()); - p.setStyle(HEADING1); - assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal()); - - doc.createTOC(); - /* - // TODO - finish this test - if (false) { - CTStyles styles = doc.getStyle(); - CTStyle style = styles.addNewStyle(); +import java.io.IOException; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.apache.xmlbeans.XmlException; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; + +/** + * @author Paolo Mottadelli + */ +public final class TestXWPFHeadings extends TestCase { + private static final String HEADING1 = "Heading1"; + + public void testSetParagraphStyle() throws IOException, XmlException { + //new clean instance of paragraph + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx"); + XWPFParagraph p = doc.createParagraph(); + XWPFRun run = p.createRun(); + run.setText("Heading 1"); + + CTSdtBlock block = doc.getDocument().getBody().addNewSdt(); + + assertNull(p.getStyle()); + p.setStyle(HEADING1); + assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal()); + + doc.createTOC(); + /* + // TODO - finish this test + if (false) { + CTStyles styles = doc.getStyle(); + CTStyle style = styles.addNewStyle(); style.setType(STStyleType.PARAGRAPH); style.setStyleId("Heading1"); } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java index 5f5e9c07bc..dfdecc9f38 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java @@ -18,86 +18,85 @@ package org.apache.poi.xwpf.usermodel; import java.io.IOException; -import java.math.BigInteger; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl; - -public class TestXWPFNumbering extends TestCase { - - public void testCompareAbstractNum() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - XWPFNumbering numbering = doc.getNumbering(); - BigInteger numId = BigInteger.valueOf(1); - assertTrue(numbering.numExist(numId)); - XWPFNum num = numbering.getNum(numId); - BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal(); - XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId); - BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum); - assertEquals(abstrNumId, compareAbstractNum); - } - - public void testAddNumberingToDoc() throws IOException{ - BigInteger abstractNumId = BigInteger.valueOf(1); - BigInteger numId = BigInteger.valueOf(1); - - XWPFDocument docOut = new XWPFDocument(); - XWPFNumbering numbering = docOut.createNumbering(); - numId = numbering.addNum(abstractNumId); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - numbering = docIn.getNumbering(); - assertTrue(numbering.numExist(numId)); - XWPFNum num = numbering.getNum(numId); - - BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); - assertEquals(abstractNumId, compareAbstractNum); - } - - public void testGetNumIlvl() throws IOException{ - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - BigInteger numIlvl = BigInteger.valueOf(0); - assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl()); - numIlvl = BigInteger.valueOf(1); - assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl()); - } - - public void testGetNumFmt() throws IOException{ - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt()); - assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt()); - assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt()); - assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt()); - } - - public void testLvlText() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - - assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText()); - - assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText()); - - XWPFParagraph p = doc.getParagraphs().get(18); - assertEquals("%1.", p.getNumLevelText()); - //test that null doesn't throw NPE - assertNull(p.getNumFmt()); - } - - public void testOverrideList() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx"); - XWPFParagraph p = doc.getParagraphs().get(4); - XWPFNumbering numbering = doc.getNumbering(); - CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum(); - assertEquals(9, ctNum.sizeOfLvlOverrideArray()); - CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0); - assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString()); - } - -} +import java.math.BigInteger; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl; + +public class TestXWPFNumbering extends TestCase { + + public void testCompareAbstractNum() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); + XWPFNumbering numbering = doc.getNumbering(); + BigInteger numId = BigInteger.valueOf(1); + assertTrue(numbering.numExist(numId)); + XWPFNum num = numbering.getNum(numId); + BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal(); + XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId); + BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum); + assertEquals(abstrNumId, compareAbstractNum); + } + + public void testAddNumberingToDoc() throws IOException { + BigInteger abstractNumId = BigInteger.valueOf(1); + BigInteger numId = BigInteger.valueOf(1); + + XWPFDocument docOut = new XWPFDocument(); + XWPFNumbering numbering = docOut.createNumbering(); + numId = numbering.addNum(abstractNumId); + + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); + + numbering = docIn.getNumbering(); + assertTrue(numbering.numExist(numId)); + XWPFNum num = numbering.getNum(numId); + + BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); + assertEquals(abstractNumId, compareAbstractNum); + } + + public void testGetNumIlvl() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); + BigInteger numIlvl = BigInteger.valueOf(0); + assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl()); + numIlvl = BigInteger.valueOf(1); + assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl()); + } + + public void testGetNumFmt() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); + assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt()); + assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt()); + assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt()); + assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt()); + assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt()); + assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt()); + assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt()); + } + + public void testLvlText() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); + + assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText()); + + assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText()); + + XWPFParagraph p = doc.getParagraphs().get(18); + assertEquals("%1.", p.getNumLevelText()); + //test that null doesn't throw NPE + assertNull(p.getNumFmt()); + } + + public void testOverrideList() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx"); + XWPFParagraph p = doc.getParagraphs().get(4); + XWPFNumbering numbering = doc.getNumbering(); + CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum(); + assertEquals(9, ctNum.sizeOfLvlOverrideArray()); + CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0); + assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString()); + } + +} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java index ec17da408d..31be821e06 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java @@ -22,12 +22,26 @@ import java.math.BigInteger; import java.util.List; import junit.framework.TestCase; - import org.apache.poi.xwpf.XWPFTestDataSamples; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument; import org.openxmlformats.schemas.drawingml.x2006.picture.impl.PicDocumentImpl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTextAlignment; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment; /** * Tests for XWPF Paragraphs @@ -36,7 +50,8 @@ public final class TestXWPFParagraph extends TestCase { /** * Check that we get the right paragraph from the header - * @throws IOException + * + * @throws IOException */ public void disabled_testHeaderParagraph() throws IOException { XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); @@ -44,7 +59,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader(); assertNotNull(hdr); - List ps = hdr.getParagraphs(); + List ps = hdr.getParagraphs(); assertEquals(1, ps.size()); XWPFParagraph p = ps.get(0); @@ -55,7 +70,8 @@ public final class TestXWPFParagraph extends TestCase { /** * Check that we get the right paragraphs from the document - * @throws IOException + * + * @throws IOException */ public void disabled_testDocumentParagraph() throws IOException { XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); @@ -88,7 +104,7 @@ public final class TestXWPFParagraph extends TestCase { assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue()); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); //bordi CTPBdr bdr = ppr.addNewPBdr(); @@ -109,7 +125,7 @@ public final class TestXWPFParagraph extends TestCase { assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue()); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); CTJc align = ppr.addNewJc(); align.setVal(STJc.CENTER); @@ -125,7 +141,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFParagraph p = doc.createParagraph(); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); assertEquals(-1, p.getSpacingAfter()); @@ -142,7 +158,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFParagraph p = doc.createParagraph(); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue()); @@ -161,7 +177,7 @@ public final class TestXWPFParagraph extends TestCase { assertEquals(-1, p.getIndentationLeft()); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); assertEquals(-1, p.getIndentationLeft()); @@ -179,7 +195,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFParagraph p = doc.createParagraph(); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); CTTextAlignment txtAlign = ppr.addNewTextAlignment(); txtAlign.setVal(STTextAlignment.CENTER); @@ -194,7 +210,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFParagraph p = doc.createParagraph(); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); CTOnOff wordWrap = ppr.addNewWordWrap(); wordWrap.setVal(STOnOff.FALSE); @@ -210,7 +226,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFParagraph p = doc.createParagraph(); CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); + CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); CTOnOff pageBreak = ppr.addNewPageBreakBefore(); pageBreak.setVal(STOnOff.FALSE); @@ -229,8 +245,8 @@ public final class TestXWPFParagraph extends TestCase { assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray()); CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0); assertEquals("poi", ctBookmark.getName()); - for(CTBookmark bookmark : paragraph.getCTP().getBookmarkStartArray()) { - assertEquals("poi", bookmark.getName()); + for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartArray()) { + assertEquals("poi", bookmark.getName()); } } @@ -241,108 +257,108 @@ public final class TestXWPFParagraph extends TestCase { p.setNumID(new BigInteger("10")); assertEquals("10", p.getNumID().toString()); } - + public void testAddingRuns() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - - XWPFParagraph p = doc.getParagraphs().get(0); - assertEquals(2, p.getRuns().size()); - - XWPFRun r = p.createRun(); - assertEquals(3, p.getRuns().size()); - assertEquals(2, p.getRuns().indexOf(r)); - - XWPFRun r2 = p.insertNewRun(1); - assertEquals(4, p.getRuns().size()); - assertEquals(1, p.getRuns().indexOf(r2)); - assertEquals(3, p.getRuns().indexOf(r)); + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); + + XWPFParagraph p = doc.getParagraphs().get(0); + assertEquals(2, p.getRuns().size()); + + XWPFRun r = p.createRun(); + assertEquals(3, p.getRuns().size()); + assertEquals(2, p.getRuns().indexOf(r)); + + XWPFRun r2 = p.insertNewRun(1); + assertEquals(4, p.getRuns().size()); + assertEquals(1, p.getRuns().indexOf(r2)); + assertEquals(3, p.getRuns().indexOf(r)); } - + public void testPictures() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); - assertEquals(7, doc.getParagraphs().size()); - - XWPFParagraph p; - XWPFRun r; - - // Text paragraphs - assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText()); - assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText()); - - // Spacer ones - assertEquals("", doc.getParagraphs().get(2).getText()); - assertEquals("", doc.getParagraphs().get(3).getText()); - assertEquals("", doc.getParagraphs().get(4).getText()); - - // Image one - p = doc.getParagraphs().get(5); - assertEquals(6, p.getRuns().size()); - - r = p.getRuns().get(0); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(1); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(2); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(3); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(4); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(5); - assertEquals(" ", r.toString()); - assertEquals(0, r.getEmbeddedPictures().size()); - - // Final spacer - assertEquals("", doc.getParagraphs().get(6).getText()); - - - // Look in detail at one - r = p.getRuns().get(4); - XWPFPicture pict = r.getEmbeddedPictures().get(0); - CTPicture picture = pict.getCTPicture(); - assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed()); - - // Ensure that the ooxml compiler finds everything we need - r.getCTR().getDrawingArray(0); - r.getCTR().getDrawingArray(0).getInlineArray(0); - r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic(); - r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData(); - PicDocument pd = new PicDocumentImpl(null); - assertTrue(pd.isNil()); + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); + assertEquals(7, doc.getParagraphs().size()); + + XWPFParagraph p; + XWPFRun r; + + // Text paragraphs + assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText()); + assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText()); + + // Spacer ones + assertEquals("", doc.getParagraphs().get(2).getText()); + assertEquals("", doc.getParagraphs().get(3).getText()); + assertEquals("", doc.getParagraphs().get(4).getText()); + + // Image one + p = doc.getParagraphs().get(5); + assertEquals(6, p.getRuns().size()); + + r = p.getRuns().get(0); + assertEquals("", r.toString()); + assertEquals(1, r.getEmbeddedPictures().size()); + assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); + assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); + + r = p.getRuns().get(1); + assertEquals("", r.toString()); + assertEquals(1, r.getEmbeddedPictures().size()); + assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); + assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); + + r = p.getRuns().get(2); + assertEquals("", r.toString()); + assertEquals(1, r.getEmbeddedPictures().size()); + assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); + assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); + + r = p.getRuns().get(3); + assertEquals("", r.toString()); + assertEquals(1, r.getEmbeddedPictures().size()); + assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); + assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); + + r = p.getRuns().get(4); + assertEquals("", r.toString()); + assertEquals(1, r.getEmbeddedPictures().size()); + assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); + assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); + + r = p.getRuns().get(5); + assertEquals(" ", r.toString()); + assertEquals(0, r.getEmbeddedPictures().size()); + + // Final spacer + assertEquals("", doc.getParagraphs().get(6).getText()); + + + // Look in detail at one + r = p.getRuns().get(4); + XWPFPicture pict = r.getEmbeddedPictures().get(0); + CTPicture picture = pict.getCTPicture(); + assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed()); + + // Ensure that the ooxml compiler finds everything we need + r.getCTR().getDrawingArray(0); + r.getCTR().getDrawingArray(0).getInlineArray(0); + r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic(); + r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData(); + PicDocument pd = new PicDocumentImpl(null); + assertTrue(pd.isNil()); } - - public void testTika792() throws Exception{ - //This test forces the loading of CTMoveBookmark and - //CTMoveBookmarkImpl into ooxml-lite. - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx"); - XWPFParagraph paragraph = doc.getParagraphs().get(0); - assertEquals("s", paragraph.getText()); + + public void testTika792() throws Exception { + //This test forces the loading of CTMoveBookmark and + //CTMoveBookmarkImpl into ooxml-lite. + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx"); + XWPFParagraph paragraph = doc.getParagraphs().get(0); + assertEquals("s", paragraph.getText()); } public void testSettersGetters() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.createParagraph(); - + assertTrue(p.isEmpty()); assertFalse(p.removeRun(0)); @@ -355,7 +371,7 @@ public final class TestXWPFParagraph extends TestCase { assertFalse(p.isEmpty()); assertNull(p.getStyleID()); assertNull(p.getStyle()); - + assertNull(p.getNumID()); p.setNumID(BigInteger.valueOf(12)); assertEquals(BigInteger.valueOf(12), p.getNumID()); @@ -363,18 +379,18 @@ public final class TestXWPFParagraph extends TestCase { assertEquals(BigInteger.valueOf(13), p.getNumID()); assertNull(p.getNumFmt()); - + assertNull(p.getNumIlvl()); - + assertEquals("", p.getParagraphText()); assertEquals("", p.getPictureText()); assertEquals("", p.getFootnoteText()); - + p.setBorderBetween(Borders.NONE); assertEquals(Borders.NONE, p.getBorderBetween()); p.setBorderBetween(Borders.BASIC_BLACK_DASHES); assertEquals(Borders.BASIC_BLACK_DASHES, p.getBorderBetween()); - + p.setBorderBottom(Borders.NONE); assertEquals(Borders.NONE, p.getBorderBottom()); p.setBorderBottom(Borders.BABY_RATTLE); @@ -394,37 +410,37 @@ public final class TestXWPFParagraph extends TestCase { assertEquals(Borders.NONE, p.getBorderBottom()); p.setBorderBottom(Borders.BASIC_WHITE_DOTS); assertEquals(Borders.BASIC_WHITE_DOTS, p.getBorderBottom()); - + assertFalse(p.isPageBreak()); p.setPageBreak(true); assertTrue(p.isPageBreak()); p.setPageBreak(false); assertFalse(p.isPageBreak()); - + assertEquals(-1, p.getSpacingAfter()); p.setSpacingAfter(12); assertEquals(12, p.getSpacingAfter()); - + assertEquals(-1, p.getSpacingAfterLines()); p.setSpacingAfterLines(14); assertEquals(14, p.getSpacingAfterLines()); - + assertEquals(-1, p.getSpacingBefore()); p.setSpacingBefore(16); assertEquals(16, p.getSpacingBefore()); - + assertEquals(-1, p.getSpacingBeforeLines()); p.setSpacingBeforeLines(18); assertEquals(18, p.getSpacingBeforeLines()); - + assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); p.setSpacingLineRule(LineSpacingRule.EXACT); assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule()); - + assertEquals(-1, p.getIndentationLeft()); p.setIndentationLeft(21); assertEquals(21, p.getIndentationLeft()); - + assertEquals(-1, p.getIndentationRight()); p.setIndentationRight(25); assertEquals(25, p.getIndentationRight()); @@ -442,20 +458,20 @@ public final class TestXWPFParagraph extends TestCase { assertTrue(p.isWordWrap()); p.setWordWrap(false); assertFalse(p.isWordWrap()); - + assertNull(p.getStyle()); p.setStyle("teststyle"); assertEquals("teststyle", p.getStyle()); - + p.addRun(CTR.Factory.newInstance()); - + //assertTrue(p.removeRun(0)); - + assertNotNull(p.getBody()); assertEquals(BodyElementType.PARAGRAPH, p.getElementType()); assertEquals(BodyType.DOCUMENT, p.getPartType()); } - + public void testSearchTextNotFound() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.createParagraph(); @@ -469,17 +485,17 @@ public final class TestXWPFParagraph extends TestCase { List ps = xml.getParagraphs(); assertEquals(10, ps.size()); - + XWPFParagraph p = ps.get(0); TextSegement segment = p.searchText("sample word document", new PositionInParagraph()); assertNotNull(segment); - + assertEquals("sample word document", p.getText(segment)); - + assertTrue(p.removeRun(0)); } - + @SuppressWarnings("deprecation") public void testRuns() { XWPFDocument doc = new XWPFDocument(); @@ -489,7 +505,7 @@ public final class TestXWPFParagraph extends TestCase { XWPFRun r = new XWPFRun(run, doc.createParagraph()); p.addRun(r); p.addRun(r); - + assertNotNull(p.getRun(run)); assertNull(p.getRun(null)); } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java index 34a47fdfbb..c9123a3a14 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java @@ -20,138 +20,129 @@ package org.apache.poi.xwpf.usermodel; import static org.junit.Assert.assertArrayEquals; import java.io.IOException; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.xssf.usermodel.XSSFRelation; +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.PackageRelationship; +import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; - -public class TestXWPFPictureData extends TestCase { - - public void testRead() throws InvalidFormatException, IOException - { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); - List pictures = sampleDoc.getAllPictures(); - - assertEquals(5,pictures.size()); - String[] ext = {"wmf","png","emf","emf","jpeg"}; - for (int i = 0 ; i < pictures.size() ; i++) - { - assertEquals(ext[i],pictures.get(i).suggestFileExtension()); - } - - int num = pictures.size(); - - byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg"); - - String relationId = sampleDoc.addPictureData(pictureData,XWPFDocument.PICTURE_TYPE_JPEG); - // picture list was updated - assertEquals(num + 1,pictures.size()); - XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId); - assertEquals("jpeg",pict.suggestFileExtension()); - assertArrayEquals(pictureData,pict.getData()); - } - - public void testPictureInHeader() throws IOException - { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); - verifyOneHeaderPicture(sampleDoc); - - XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - verifyOneHeaderPicture(readBack); - } +import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; + +public class TestXWPFPictureData extends TestCase { + + public void testRead() throws InvalidFormatException, IOException { + XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); + List pictures = sampleDoc.getAllPictures(); + + assertEquals(5, pictures.size()); + String[] ext = {"wmf", "png", "emf", "emf", "jpeg"}; + for (int i = 0; i < pictures.size(); i++) { + assertEquals(ext[i], pictures.get(i).suggestFileExtension()); + } + + int num = pictures.size(); + + byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg"); + + String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG); + // picture list was updated + assertEquals(num + 1, pictures.size()); + XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId); + assertEquals("jpeg", pict.suggestFileExtension()); + assertArrayEquals(pictureData, pict.getData()); + } + + public void testPictureInHeader() throws IOException { + XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); + verifyOneHeaderPicture(sampleDoc); + + XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); + verifyOneHeaderPicture(readBack); + } private void verifyOneHeaderPicture(XWPFDocument sampleDoc) { XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - XWPFHeader header = policy.getDefaultHeader(); - - List pictures = header.getAllPictures(); - assertEquals(1,pictures.size()); - } - - public void testNew() throws InvalidFormatException, IOException - { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx"); - byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg"); - assertNotNull(jpegData); + XWPFHeader header = policy.getDefaultHeader(); + + List pictures = header.getAllPictures(); + assertEquals(1, pictures.size()); + } + + public void testNew() throws InvalidFormatException, IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx"); + byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg"); + assertNotNull(jpegData); byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif"); assertNotNull(gifData); byte[] pngData = XWPFTestDataSamples.getImage("nature1.png"); - assertNotNull(pngData); - - List pictures = doc.getAllPictures(); - assertEquals(0,pictures.size()); - - // Document shouldn't have any image relationships - assertEquals(13,doc.getPackagePart().getRelationships().size()); - for (PackageRelationship rel : doc.getPackagePart().getRelationships()) - { - if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) - { - fail("Shouldn't have JPEG yet"); - } - } - - // Add the image - String relationId = doc.addPictureData(jpegData,XWPFDocument.PICTURE_TYPE_JPEG); - assertEquals(1,pictures.size()); - XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId); - assertEquals("jpeg",jpgPicData.suggestFileExtension()); - assertArrayEquals(jpegData,jpgPicData.getData()); - - // Ensure it now has one - assertEquals(14,doc.getPackagePart().getRelationships().size()); - PackageRelationship jpegRel = null; - for (PackageRelationship rel : doc.getPackagePart().getRelationships()) - { - if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) - { - if (jpegRel != null) - fail("Found 2 jpegs!"); - jpegRel = rel; - } - } - assertNotNull("JPEG Relationship not found",jpegRel); - - // Check the details - assertNotNull(jpegRel); - assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(),jpegRel.getRelationshipType()); - assertEquals("/word/document.xml",jpegRel.getSource().getPartName().toString()); - assertEquals("/word/media/image1.jpeg",jpegRel.getTargetURI().getPath()); - - XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); - assertArrayEquals(jpegData, pictureDataByID.getData()); - - // Save an re-load, check it appears - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(1,doc.getAllPictures().size()); - assertEquals(1,doc.getAllPackagePictures().size()); - - // verify the picture that we read back in - pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); - assertArrayEquals(jpegData, pictureDataByID.getData()); - - } - - public void testBug51770() throws InvalidFormatException, IOException { + assertNotNull(pngData); + + List pictures = doc.getAllPictures(); + assertEquals(0, pictures.size()); + + // Document shouldn't have any image relationships + assertEquals(13, doc.getPackagePart().getRelationships().size()); + for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { + if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) { + fail("Shouldn't have JPEG yet"); + } + } + + // Add the image + String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG); + assertEquals(1, pictures.size()); + XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId); + assertEquals("jpeg", jpgPicData.suggestFileExtension()); + assertArrayEquals(jpegData, jpgPicData.getData()); + + // Ensure it now has one + assertEquals(14, doc.getPackagePart().getRelationships().size()); + PackageRelationship jpegRel = null; + for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { + if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) { + if (jpegRel != null) + fail("Found 2 jpegs!"); + jpegRel = rel; + } + } + assertNotNull("JPEG Relationship not found", jpegRel); + + // Check the details + assertNotNull(jpegRel); + assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType()); + assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString()); + assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath()); + + XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); + assertArrayEquals(jpegData, pictureDataByID.getData()); + + // Save an re-load, check it appears + doc = XWPFTestDataSamples.writeOutAndReadBack(doc); + assertEquals(1, doc.getAllPictures().size()); + assertEquals(1, doc.getAllPackagePictures().size()); + + // verify the picture that we read back in + pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); + assertArrayEquals(jpegData, pictureDataByID.getData()); + + } + + public void testBug51770() throws InvalidFormatException, IOException { XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx"); XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy(); XWPFHeader header = policy.getDefaultHeader(); for (XWPFParagraph paragraph : header.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { for (XWPFPicture picture : run.getEmbeddedPictures()) { - if (paragraph.getDocument() != null) { - //System.out.println(picture.getCTPicture()); - XWPFPictureData data = picture.getPictureData(); - if(data != null) System.out.println(data.getFileName()); - } - } - } + if (paragraph.getDocument() != null) { + //System.out.println(picture.getCTPicture()); + XWPFPictureData data = picture.getPictureData(); + if (data != null) System.out.println(data.getFileName()); + } + } + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java index 618618f92c..d9af8c91fd 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java @@ -20,13 +20,12 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear; @@ -46,28 +45,28 @@ public class TestXWPFRun extends TestCase { p = doc.createParagraph(); this.ctRun = CTR.Factory.newInstance(); - } - - public void testSetGetText() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewT().setStringValue("TEST3 STRING"); - - assertEquals(3,ctRun.sizeOfTArray()); - XWPFRun run = new XWPFRun(ctRun, p); - - assertEquals("TEST2 STRING",run.getText(1)); - - run.setText("NEW STRING",0); - assertEquals("NEW STRING",run.getText(0)); - - //run.setText("xxx",14); - //fail("Position wrong"); - } - - public void testSetGetBold() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewB().setVal(STOnOff.TRUE); + } + + public void testSetGetText() { + ctRun.addNewT().setStringValue("TEST STRING"); + ctRun.addNewT().setStringValue("TEST2 STRING"); + ctRun.addNewT().setStringValue("TEST3 STRING"); + + assertEquals(3, ctRun.sizeOfTArray()); + XWPFRun run = new XWPFRun(ctRun, p); + + assertEquals("TEST2 STRING", run.getText(1)); + + run.setText("NEW STRING", 0); + assertEquals("NEW STRING", run.getText(0)); + + //run.setText("xxx",14); + //fail("Position wrong"); + } + + public void testSetGetBold() { + CTRPr rpr = ctRun.addNewRPr(); + rpr.addNewB().setVal(STOnOff.TRUE); XWPFRun run = new XWPFRun(ctRun, p); assertEquals(true, run.isBold()); @@ -178,16 +177,16 @@ public class TestXWPFRun extends TestCase { run.setText("T1"); run.addCarriageReturn(); run.addCarriageReturn(); - run.setText("T2"); - run.addCarriageReturn(); - assertEquals(3, run.getCTR().sizeOfCrArray()); - - assertEquals("T1\n\nT2\n", run.toString()); - } - - public void testAddTabsAndLineBreaks() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewCr(); + run.setText("T2"); + run.addCarriageReturn(); + assertEquals(3, run.getCTR().sizeOfCrArray()); + + assertEquals("T1\n\nT2\n", run.toString()); + } + + public void testAddTabsAndLineBreaks() { + ctRun.addNewT().setStringValue("TEST STRING"); + ctRun.addNewCr(); ctRun.addNewT().setStringValue("TEST2 STRING"); ctRun.addNewTab(); ctRun.addNewT().setStringValue("TEST3 STRING"); @@ -199,21 +198,21 @@ public class TestXWPFRun extends TestCase { run.addCarriageReturn(); run.setText("T2"); run.addTab(); - run.setText("T3"); - assertEquals(1, run.getCTR().sizeOfCrArray()); - assertEquals(1, run.getCTR().sizeOfTabArray()); - - assertEquals("T1\nT2\tT3", run.toString()); - } - + run.setText("T3"); + assertEquals(1, run.getCTR().sizeOfCrArray()); + assertEquals(1, run.getCTR().sizeOfTabArray()); + + assertEquals("T1\nT2\tT3", run.toString()); + } + public void testAddPageBreak() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewBr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - CTBr breac=ctRun.addNewBr(); - breac.setClear(STBrClear.LEFT); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(2, ctRun.sizeOfBrArray()); + ctRun.addNewT().setStringValue("TEST STRING"); + ctRun.addNewBr(); + ctRun.addNewT().setStringValue("TEST2 STRING"); + CTBr breac = ctRun.addNewBr(); + breac.setClear(STBrClear.LEFT); + ctRun.addNewT().setStringValue("TEST3 STRING"); + assertEquals(2, ctRun.sizeOfBrArray()); XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), p); run.setText("TEXT1"); @@ -222,144 +221,145 @@ public class TestXWPFRun extends TestCase { run.addBreak(BreakType.TEXT_WRAPPING); assertEquals(2, run.getCTR().sizeOfBrArray()); } - - /** - * Test that on an existing document, we do the - * right thing with it - * @throws IOException - */ - public void testExisting() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFParagraph p; - XWPFRun run; - - - // First paragraph is simple - p = doc.getParagraphArray(0); - assertEquals("This is a test document.", p.getText()); - assertEquals(2, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This is a test document", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(1); - assertEquals(".", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - - // Next paragraph is all in one style, but a different one - p = doc.getParagraphArray(1); - assertEquals("This bit is in bold and italic", p.getText()); - assertEquals(1, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This bit is in bold and italic", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(true, run.getCTR().getRPr().isSetB()); - assertEquals(false, run.getCTR().getRPr().getB().isSetVal()); - - - // Back to normal - p = doc.getParagraphArray(2); - assertEquals("Back to normal", p.getText()); - assertEquals(1, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("Back to normal", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - - // Different styles in one paragraph - p = doc.getParagraphArray(3); - assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText()); - assertEquals(11, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This contains ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(1); - assertEquals("BOLD", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - - run = p.getRuns().get(2); - assertEquals(", ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(3); - assertEquals("ITALIC", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrike()); - - run = p.getRuns().get(4); - assertEquals(" and ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(5); - assertEquals("BOTH", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrike()); - - run = p.getRuns().get(6); - assertEquals(", as well as ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(7); - assertEquals("RED", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - - run = p.getRuns().get(8); - assertEquals(" and ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(9); - assertEquals("YELLOW", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - - run = p.getRuns().get(10); - assertEquals(" text.", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrike()); - assertEquals(null, run.getCTR().getRPr()); - } - - public void testPictureInHeader() throws IOException { + + /** + * Test that on an existing document, we do the + * right thing with it + * + * @throws IOException + */ + public void testExisting() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); + XWPFParagraph p; + XWPFRun run; + + + // First paragraph is simple + p = doc.getParagraphArray(0); + assertEquals("This is a test document.", p.getText()); + assertEquals(2, p.getRuns().size()); + + run = p.getRuns().get(0); + assertEquals("This is a test document", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + run = p.getRuns().get(1); + assertEquals(".", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + + // Next paragraph is all in one style, but a different one + p = doc.getParagraphArray(1); + assertEquals("This bit is in bold and italic", p.getText()); + assertEquals(1, p.getRuns().size()); + + run = p.getRuns().get(0); + assertEquals("This bit is in bold and italic", run.toString()); + assertEquals(true, run.isBold()); + assertEquals(true, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(true, run.getCTR().getRPr().isSetB()); + assertEquals(false, run.getCTR().getRPr().getB().isSetVal()); + + + // Back to normal + p = doc.getParagraphArray(2); + assertEquals("Back to normal", p.getText()); + assertEquals(1, p.getRuns().size()); + + run = p.getRuns().get(0); + assertEquals("Back to normal", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + + // Different styles in one paragraph + p = doc.getParagraphArray(3); + assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText()); + assertEquals(11, p.getRuns().size()); + + run = p.getRuns().get(0); + assertEquals("This contains ", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + run = p.getRuns().get(1); + assertEquals("BOLD", run.toString()); + assertEquals(true, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + + run = p.getRuns().get(2); + assertEquals(", ", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + run = p.getRuns().get(3); + assertEquals("ITALIC", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(true, run.isItalic()); + assertEquals(false, run.isStrike()); + + run = p.getRuns().get(4); + assertEquals(" and ", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + run = p.getRuns().get(5); + assertEquals("BOTH", run.toString()); + assertEquals(true, run.isBold()); + assertEquals(true, run.isItalic()); + assertEquals(false, run.isStrike()); + + run = p.getRuns().get(6); + assertEquals(", as well as ", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + run = p.getRuns().get(7); + assertEquals("RED", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + + run = p.getRuns().get(8); + assertEquals(" and ", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + + run = p.getRuns().get(9); + assertEquals("YELLOW", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + + run = p.getRuns().get(10); + assertEquals(" text.", run.toString()); + assertEquals(false, run.isBold()); + assertEquals(false, run.isItalic()); + assertEquals(false, run.isStrike()); + assertEquals(null, run.getCTR().getRPr()); + } + + public void testPictureInHeader() throws IOException { XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); @@ -373,47 +373,47 @@ public class TestXWPFRun extends TestCase { for (XWPFPicture pic : pictures) { assertNotNull(pic.getPictureData()); - assertEquals("DOZOR", pic.getDescription()); - } - - count+= pictures.size(); - } - } - - assertEquals(1, count); - } - - public void testAddPicture() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFParagraph p = doc.getParagraphArray(2); - XWPFRun r = p.getRuns().get(0); - - assertEquals(0, doc.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); - - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); - } - - /** - * Bugzilla #52288 - setting the font family on the - * run mustn't NPE - */ - public void testSetFontFamily_52288() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx"); - final Iterator paragraphs = doc.getParagraphsIterator(); - while (paragraphs.hasNext()) { - final XWPFParagraph paragraph = paragraphs.next(); - for (final XWPFRun run : paragraph.getRuns()) { - if (run != null) { - final String text = run.getText(0); - if (text != null) { - run.setFontFamily("Times New Roman"); - } - } - } - } - } -} + assertEquals("DOZOR", pic.getDescription()); + } + + count += pictures.size(); + } + } + + assertEquals(1, count); + } + + public void testAddPicture() throws Exception { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); + XWPFParagraph p = doc.getParagraphArray(2); + XWPFRun r = p.getRuns().get(0); + + assertEquals(0, doc.getAllPictures().size()); + assertEquals(0, r.getEmbeddedPictures().size()); + + r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); + + assertEquals(1, doc.getAllPictures().size()); + assertEquals(1, r.getEmbeddedPictures().size()); + } + + /** + * Bugzilla #52288 - setting the font family on the + * run mustn't NPE + */ + public void testSetFontFamily_52288() throws Exception { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx"); + final Iterator paragraphs = doc.getParagraphsIterator(); + while (paragraphs.hasNext()) { + final XWPFParagraph paragraph = paragraphs.next(); + for (final XWPFRun run : paragraph.getRuns()) { + if (run != null) { + final String text = run.getText(0); + if (text != null) { + run.setFontFamily("Times New Roman"); + } + } + } + } + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java index f4114c9620..92c94052e0 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java @@ -15,48 +15,46 @@ limitations under the License. ==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; - -public final class TestXWPFSDT extends TestCase { - - /** - * Test simple tag and title extraction from SDT - * @throws Exception - */ - public void testTagTitle() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - String tag = null; - String title= null; - List sdts = extractAllSDTs(doc); - for (AbstractXWPFSDT sdt :sdts){ - if (sdt.getContent().toString().equals("Rich_text")){ - tag = "MyTag"; - title = "MyTitle"; - break; - } - - } - assertEquals("controls size", 13, sdts.size()); - +package org.apache.poi.xwpf.usermodel; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; + +public final class TestXWPFSDT extends TestCase { + + /** + * Test simple tag and title extraction from SDT + * + * @throws Exception + */ + public void testTagTitle() throws Exception { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); + String tag = null; + String title = null; + List sdts = extractAllSDTs(doc); + for (AbstractXWPFSDT sdt : sdts) { + if (sdt.getContent().toString().equals("Rich_text")) { + tag = "MyTag"; + title = "MyTitle"; + break; + } + + } + assertEquals("controls size", 13, sdts.size()); + assertEquals("tag", "MyTag", tag); assertEquals("title", "MyTitle", title); - } - - - public void testGetSDTs() throws Exception{ - String[] contents = new String[]{ - "header_rich_text", - "Rich_text", + } + + + public void testGetSDTs() throws Exception { + String[] contents = new String[]{ + "header_rich_text", + "Rich_text", "Rich_text_pre_table\nRich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nRich_text_post_table", "Plain_text_no_newlines", "Plain_text_with_newlines1\nplain_text_with_newlines2", @@ -72,125 +70,126 @@ public final class TestXWPFSDT extends TestCase { }; XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); List sdts = extractAllSDTs(doc); - - assertEquals("number of sdts", contents.length, sdts.size()); - - for (int i = 0; i < contents.length; i++){ - AbstractXWPFSDT sdt = sdts.get(i); - assertEquals(i+ ": " + contents[i], contents[i], sdt.getContent().toString()); - } - } - /** - * POI-54771 and TIKA-1317 - */ + + assertEquals("number of sdts", contents.length, sdts.size()); + + for (int i = 0; i < contents.length; i++) { + AbstractXWPFSDT sdt = sdts.get(i); + assertEquals(i + ": " + contents[i], contents[i], sdt.getContent().toString()); + } + } + + /** + * POI-54771 and TIKA-1317 + */ public void testSDTAsCell() throws Exception { //Bug54771a.docx and Bug54771b.docx test slightly //different recursion patterns. Keep both! - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); - List sdts = extractAllSDTs(doc); - String text = sdts.get(0).getContent().getText(); - assertEquals(2, sdts.size()); - assertTrue(text.indexOf("Test") > -1); - - text = sdts.get(1).getContent().getText(); + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); + List sdts = extractAllSDTs(doc); + String text = sdts.get(0).getContent().getText(); + assertEquals(2, sdts.size()); + assertTrue(text.indexOf("Test") > -1); + + text = sdts.get(1).getContent().getText(); assertTrue(text.indexOf("Test Subtitle") > -1); assertTrue(text.indexOf("Test User") > -1); assertTrue(text.indexOf("Test") < text.indexOf("Test Subtitle")); - - doc = XWPFTestDataSamples.openSampleDocument("Bug54771b.docx"); - sdts = extractAllSDTs(doc); - assertEquals(3, sdts.size()); - assertTrue(sdts.get(0).getContent().getText().indexOf("Test") > -1); - - assertTrue(sdts.get(1).getContent().getText().indexOf("Test Subtitle") > -1); - assertTrue(sdts.get(2).getContent().getText().indexOf("Test User") > -1); - - } - - /** - * POI-55142 and Tika 1130 - */ - public void testNewLinesBetweenRuns() throws Exception{ - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx"); - List sdts = extractAllSDTs(doc); - List targs = new ArrayList(); - //these test newlines and tabs in paragraphs/body elements - targs.add("Rich-text1 abcdefghi"); - targs.add("Rich-text2 abcd\t\tefgh"); - targs.add("Rich-text3 abcd\nefg"); - targs.add("Rich-text4 abcdefg"); - targs.add("Rich-text5 abcdefg\nhijk"); - targs.add("Plain-text1 abcdefg"); - targs.add("Plain-text2 abcdefg\nhijk\nlmnop"); - //this tests consecutive runs within a cell (not a paragraph) - //this test case was triggered by Tika-1130 - targs.add("sdt_incell2 abcdefg"); - - for (int i = 0; i < sdts.size(); i++){ - AbstractXWPFSDT sdt = sdts.get(i); - assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText()); - } - } - - private List extractAllSDTs(XWPFDocument doc){ - - List sdts = new ArrayList(); - - List headers = doc.getHeaderList(); - for (XWPFHeader header : headers){ - sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements())); - } - sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements())); - - List footers = doc.getFooterList(); - for (XWPFFooter footer : footers){ - sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements())); - } - - for (XWPFFootnote footnote : doc.getFootnotes()){ - sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements())); - } - for (Map.Entry e : doc.endnotes.entrySet()){ - sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements())); - } - return sdts; - } - - private List extractSDTsFromBodyElements(List elements){ - List sdts = new ArrayList(); - for (IBodyElement e : elements){ - if (e instanceof XWPFSDT){ - XWPFSDT sdt = (XWPFSDT)e; - sdts.add(sdt); - } else if (e instanceof XWPFParagraph){ - - XWPFParagraph p = (XWPFParagraph)e; - for (IRunElement e2 : p.getIRuns()){ - if (e2 instanceof XWPFSDT){ - XWPFSDT sdt = (XWPFSDT)e2; - sdts.add(sdt); - } - } - } else if (e instanceof XWPFTable){ - XWPFTable table = (XWPFTable)e; - sdts.addAll(extractSDTsFromTable(table)); - } - } + + doc = XWPFTestDataSamples.openSampleDocument("Bug54771b.docx"); + sdts = extractAllSDTs(doc); + assertEquals(3, sdts.size()); + assertTrue(sdts.get(0).getContent().getText().indexOf("Test") > -1); + + assertTrue(sdts.get(1).getContent().getText().indexOf("Test Subtitle") > -1); + assertTrue(sdts.get(2).getContent().getText().indexOf("Test User") > -1); + + } + + /** + * POI-55142 and Tika 1130 + */ + public void testNewLinesBetweenRuns() throws Exception { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx"); + List sdts = extractAllSDTs(doc); + List targs = new ArrayList(); + //these test newlines and tabs in paragraphs/body elements + targs.add("Rich-text1 abcdefghi"); + targs.add("Rich-text2 abcd\t\tefgh"); + targs.add("Rich-text3 abcd\nefg"); + targs.add("Rich-text4 abcdefg"); + targs.add("Rich-text5 abcdefg\nhijk"); + targs.add("Plain-text1 abcdefg"); + targs.add("Plain-text2 abcdefg\nhijk\nlmnop"); + //this tests consecutive runs within a cell (not a paragraph) + //this test case was triggered by Tika-1130 + targs.add("sdt_incell2 abcdefg"); + + for (int i = 0; i < sdts.size(); i++) { + AbstractXWPFSDT sdt = sdts.get(i); + assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText()); + } + } + + private List extractAllSDTs(XWPFDocument doc) { + + List sdts = new ArrayList(); + + List headers = doc.getHeaderList(); + for (XWPFHeader header : headers) { + sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements())); + } + sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements())); + + List footers = doc.getFooterList(); + for (XWPFFooter footer : footers) { + sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements())); + } + + for (XWPFFootnote footnote : doc.getFootnotes()) { + sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements())); + } + for (Map.Entry e : doc.endnotes.entrySet()) { + sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements())); + } + return sdts; + } + + private List extractSDTsFromBodyElements(List elements) { + List sdts = new ArrayList(); + for (IBodyElement e : elements) { + if (e instanceof XWPFSDT) { + XWPFSDT sdt = (XWPFSDT) e; + sdts.add(sdt); + } else if (e instanceof XWPFParagraph) { + + XWPFParagraph p = (XWPFParagraph) e; + for (IRunElement e2 : p.getIRuns()) { + if (e2 instanceof XWPFSDT) { + XWPFSDT sdt = (XWPFSDT) e2; + sdts.add(sdt); + } + } + } else if (e instanceof XWPFTable) { + XWPFTable table = (XWPFTable) e; + sdts.addAll(extractSDTsFromTable(table)); + } + } return sdts; } private List extractSDTsFromTable(XWPFTable table) { List sdts = new ArrayList(); - for (XWPFTableRow r : table.getRows()) { - for (ICell c : r.getTableICells()) { - if (c instanceof XWPFSDTCell) { - sdts.add((XWPFSDTCell)c); - } else if (c instanceof XWPFTableCell) { - sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell)c).getBodyElements())); - } - } - } + for (XWPFTableRow r : table.getRows()) { + for (ICell c : r.getTableICells()) { + if (c instanceof XWPFSDTCell) { + sdts.add((XWPFSDTCell) c); + } else if (c instanceof XWPFTableCell) { + sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell) c).getBodyElements())); + } + } + } return sdts; } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java index f12e168057..011092729a 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java @@ -19,13 +19,12 @@ package org.apache.poi.xwpf.usermodel; import java.io.IOException; import junit.framework.TestCase; - import org.apache.poi.xwpf.XWPFTestDataSamples; /** * Tests for reading SmartTags from Word docx. * - * @author Fabian Lange + * @author Fabian Lange */ public final class TestXWPFSmartTag extends TestCase { diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java index c297bc4c3b..bef00de159 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java @@ -19,13 +19,12 @@ package org.apache.poi.xwpf.usermodel; import java.io.IOException; import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; @@ -33,69 +32,69 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType; public class TestXWPFStyles extends TestCase { -// protected void setUp() throws Exception { -// super.setUp(); -// } - - public void testGetUsedStyles() throws IOException{ - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx"); - List testUsedStyleList = new ArrayList(); - XWPFStyles styles = sampleDoc.getStyles(); - XWPFStyle style = styles.getStyle("berschrift1"); - testUsedStyleList.add(style); - testUsedStyleList.add(styles.getStyle("Standard")); - testUsedStyleList.add(styles.getStyle("berschrift1Zchn")); - testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart")); - style.hasSameName(style); - - List usedStyleList = styles.getUsedStyleList(style); - assertEquals(usedStyleList, testUsedStyleList); - - - } - - public void testAddStylesToDocument() throws IOException{ - XWPFDocument docOut = new XWPFDocument(); - XWPFStyles styles = docOut.createStyles(); - - String strStyleId = "headline1"; - CTStyle ctStyle = CTStyle.Factory.newInstance(); - - ctStyle.setStyleId(strStyleId); - XWPFStyle s = new XWPFStyle(ctStyle); - styles.addStyle(s); - - assertTrue(styles.styleExist(strStyleId)); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - styles = docIn.getStyles(); - assertTrue(styles.styleExist(strStyleId)); - } - - /** - * Bug #52449 - We should be able to write a file containing - * both regular and glossary styles without error - */ - public void test52449() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx"); - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); - styles = docIn.getStyles(); - assertNotNull(styles); - } - - - /** - * YK: tests below don't make much sense, - * they exist only to copy xml beans to pi-ooxml-schemas.jar - */ - public void testLanguages(){ - XWPFDocument docOut = new XWPFDocument(); - XWPFStyles styles = docOut.createStyles(); - styles.setEastAsia("Chinese"); +// protected void setUp() throws Exception { +// super.setUp(); +// } + + public void testGetUsedStyles() throws IOException { + XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx"); + List testUsedStyleList = new ArrayList(); + XWPFStyles styles = sampleDoc.getStyles(); + XWPFStyle style = styles.getStyle("berschrift1"); + testUsedStyleList.add(style); + testUsedStyleList.add(styles.getStyle("Standard")); + testUsedStyleList.add(styles.getStyle("berschrift1Zchn")); + testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart")); + style.hasSameName(style); + + List usedStyleList = styles.getUsedStyleList(style); + assertEquals(usedStyleList, testUsedStyleList); + + + } + + public void testAddStylesToDocument() throws IOException { + XWPFDocument docOut = new XWPFDocument(); + XWPFStyles styles = docOut.createStyles(); + + String strStyleId = "headline1"; + CTStyle ctStyle = CTStyle.Factory.newInstance(); + + ctStyle.setStyleId(strStyleId); + XWPFStyle s = new XWPFStyle(ctStyle); + styles.addStyle(s); + + assertTrue(styles.styleExist(strStyleId)); + + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); + + styles = docIn.getStyles(); + assertTrue(styles.styleExist(strStyleId)); + } + + /** + * Bug #52449 - We should be able to write a file containing + * both regular and glossary styles without error + */ + public void test52449() throws Exception { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx"); + XWPFStyles styles = doc.getStyles(); + assertNotNull(styles); + + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); + styles = docIn.getStyles(); + assertNotNull(styles); + } + + + /** + * YK: tests below don't make much sense, + * they exist only to copy xml beans to pi-ooxml-schemas.jar + */ + public void testLanguages() { + XWPFDocument docOut = new XWPFDocument(); + XWPFStyles styles = docOut.createStyles(); + styles.setEastAsia("Chinese"); styles.setSpellingLanguage("English"); @@ -116,82 +115,82 @@ public class TestXWPFStyles extends TestCase { CTLsdException ex = latentStyles.addNewLsdException(); ex.setName("ex1"); XWPFLatentStyles ls = new XWPFLatentStyles(latentStyles); - assertEquals(true, ls.isLatentStyle("ex1")); - assertEquals(false, ls.isLatentStyle("notex1")); - } - - public void testSetStyles_Bug57254() throws IOException { - XWPFDocument docOut = new XWPFDocument(); - XWPFStyles styles = docOut.createStyles(); + assertEquals(true, ls.isLatentStyle("ex1")); + assertEquals(false, ls.isLatentStyle("notex1")); + } + + public void testSetStyles_Bug57254() throws IOException { + XWPFDocument docOut = new XWPFDocument(); + XWPFStyles styles = docOut.createStyles(); CTStyles ctStyles = CTStyles.Factory.newInstance(); String strStyleId = "headline1"; CTStyle ctStyle = ctStyles.addNewStyle(); - - ctStyle.setStyleId(strStyleId); - styles.setStyles(ctStyles); - - assertTrue(styles.styleExist(strStyleId)); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - styles = docIn.getStyles(); - assertTrue(styles.styleExist(strStyleId)); - } - - public void testEasyAccessToStyles() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - // Has 3 paragraphs on page one, a break, and 3 on page 2 - assertEquals(7, doc.getParagraphs().size()); - - // Check the first three have no run styles, just default paragraph style - for (int i=0; i<3; i++) { - XWPFParagraph p = doc.getParagraphs().get(i); - assertEquals(null, p.getStyle()); - assertEquals(null, p.getStyleID()); - assertEquals(1, p.getRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals(null, r.getColor()); - assertEquals(null, r.getFontFamily()); - assertEquals(null, r.getFontName()); - assertEquals(-1, r.getFontSize()); - } - - // On page two, has explicit styles, but on runs not on - // the paragraph itself - for (int i=4; i<7; i++) { - XWPFParagraph p = doc.getParagraphs().get(i); - assertEquals(null, p.getStyle()); - assertEquals(null, p.getStyleID()); - assertEquals(1, p.getRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals("Arial Black", r.getFontFamily()); - assertEquals("Arial Black", r.getFontName()); - assertEquals(16, r.getFontSize()); - assertEquals("548DD4", r.getColor()); - } - - // Check the document styles - // Should have a style defined for each type - assertEquals(4, styles.getNumberOfStyles()); + + ctStyle.setStyleId(strStyleId); + styles.setStyles(ctStyles); + + assertTrue(styles.styleExist(strStyleId)); + + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); + + styles = docIn.getStyles(); + assertTrue(styles.styleExist(strStyleId)); + } + + public void testEasyAccessToStyles() throws IOException { + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); + XWPFStyles styles = doc.getStyles(); + assertNotNull(styles); + + // Has 3 paragraphs on page one, a break, and 3 on page 2 + assertEquals(7, doc.getParagraphs().size()); + + // Check the first three have no run styles, just default paragraph style + for (int i = 0; i < 3; i++) { + XWPFParagraph p = doc.getParagraphs().get(i); + assertEquals(null, p.getStyle()); + assertEquals(null, p.getStyleID()); + assertEquals(1, p.getRuns().size()); + + XWPFRun r = p.getRuns().get(0); + assertEquals(null, r.getColor()); + assertEquals(null, r.getFontFamily()); + assertEquals(null, r.getFontName()); + assertEquals(-1, r.getFontSize()); + } + + // On page two, has explicit styles, but on runs not on + // the paragraph itself + for (int i = 4; i < 7; i++) { + XWPFParagraph p = doc.getParagraphs().get(i); + assertEquals(null, p.getStyle()); + assertEquals(null, p.getStyleID()); + assertEquals(1, p.getRuns().size()); + + XWPFRun r = p.getRuns().get(0); + assertEquals("Arial Black", r.getFontFamily()); + assertEquals("Arial Black", r.getFontName()); + assertEquals(16, r.getFontSize()); + assertEquals("548DD4", r.getColor()); + } + + // Check the document styles + // Should have a style defined for each type + assertEquals(4, styles.getNumberOfStyles()); assertNotNull(styles.getStyle("Normal")); - assertNotNull(styles.getStyle("DefaultParagraphFont")); - assertNotNull(styles.getStyle("TableNormal")); - assertNotNull(styles.getStyle("NoList")); - - // We can't do much yet with latent styles - assertEquals(137, styles.getLatentStyles().getNumberOfStyles()); - - // Check the default styles - assertNotNull(styles.getDefaultRunStyle()); - assertNotNull(styles.getDefaultParagraphStyle()); - - assertEquals(11, styles.getDefaultRunStyle().getFontSize()); - assertEquals(200, styles.getDefaultParagraphStyle().getSpacingAfter()); - } + assertNotNull(styles.getStyle("DefaultParagraphFont")); + assertNotNull(styles.getStyle("TableNormal")); + assertNotNull(styles.getStyle("NoList")); + + // We can't do much yet with latent styles + assertEquals(137, styles.getLatentStyles().getNumberOfStyles()); + + // Check the default styles + assertNotNull(styles.getDefaultRunStyle()); + assertNotNull(styles.getDefaultParagraphStyle()); + + assertEquals(11, styles.getDefaultRunStyle().getFontSize()); + assertEquals(200, styles.getDefaultParagraphStyle().getSpacingAfter()); + } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java index 7d185637f1..6f85a05cf0 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java @@ -17,13 +17,12 @@ package org.apache.poi.xwpf.usermodel; import java.math.BigInteger; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.XWPFTestDataSamples; +import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; @@ -122,13 +121,13 @@ public class TestXWPFTable extends TestCase { assertEquals(1, xtab.getCTTbl().getTrArray(0).sizeOfTcArray()); } - - public void testSetGetWidth() { - XWPFDocument doc = new XWPFDocument(); - - CTTbl table = CTTbl.Factory.newInstance(); - table.addNewTblPr().addNewTblW().setW(new BigInteger("1000")); - + + public void testSetGetWidth() { + XWPFDocument doc = new XWPFDocument(); + + CTTbl table = CTTbl.Factory.newInstance(); + table.addNewTblPr().addNewTblW().setW(new BigInteger("1000")); + XWPFTable xtab = new XWPFTable(table, doc); assertEquals(1000, xtab.getWidth()); @@ -146,20 +145,20 @@ public class TestXWPFTable extends TestCase { XWPFTableRow row = xtab.createRow(); row.setHeight(20); assertEquals(20, row.getHeight()); - } - - public void testSetGetMargins() { - // instantiate the following class so it'll get picked up by - // the XmlBean process and added to the jar file. it's required - // for the following XWPFTable methods. - CTTblCellMar ctm = CTTblCellMar.Factory.newInstance(); - assertNotNull(ctm); - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // set margins - table.setCellMargins(50, 50, 250, 450); + } + + public void testSetGetMargins() { + // instantiate the following class so it'll get picked up by + // the XmlBean process and added to the jar file. it's required + // for the following XWPFTable methods. + CTTblCellMar ctm = CTTblCellMar.Factory.newInstance(); + assertNotNull(ctm); + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); + // set margins + table.setCellMargins(50, 50, 250, 450); // get margin components int t = table.getCellMarginTop(); assertEquals(50, t); @@ -169,22 +168,22 @@ public class TestXWPFTable extends TestCase { assertEquals(250, b); int r = table.getCellMarginRight(); assertEquals(450, r); - } - - public void testSetGetHBorders() { - // instantiate the following classes so they'll get picked up by - // the XmlBean process and added to the jar file. they are required - // for the following XWPFTable methods. - CTTblBorders cttb = CTTblBorders.Factory.newInstance(); - assertNotNull(cttb); - STBorder stb = STBorder.Factory.newInstance(); - assertNotNull(stb); - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // set inside horizontal border - table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000"); + } + + public void testSetGetHBorders() { + // instantiate the following classes so they'll get picked up by + // the XmlBean process and added to the jar file. they are required + // for the following XWPFTable methods. + CTTblBorders cttb = CTTblBorders.Factory.newInstance(); + assertNotNull(cttb); + STBorder stb = STBorder.Factory.newInstance(); + assertNotNull(stb); + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); + // set inside horizontal border + table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000"); // get inside horizontal border components int s = table.getInsideHBorderSize(); assertEquals(4, s); @@ -194,26 +193,26 @@ public class TestXWPFTable extends TestCase { assertEquals("FF0000", clr); XWPFBorderType bt = table.getInsideHBorderType(); assertEquals(XWPFBorderType.SINGLE, bt); - } - - public void testSetGetVBorders() { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); + } + + public void testSetGetVBorders() { + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); // set inside vertical border table.setInsideVBorder(XWPFBorderType.DOUBLE, 4, 0, "00FF00"); // get inside vertical border components XWPFBorderType bt = table.getInsideVBorderType(); assertEquals(XWPFBorderType.DOUBLE, bt); int sz = table.getInsideVBorderSize(); - assertEquals(4, sz); - int sp = table.getInsideVBorderSpace(); - assertEquals(0, sp); - String clr = table.getInsideVBorderColor(); - assertEquals("00FF00", clr); - } - + assertEquals(4, sz); + int sp = table.getInsideVBorderSpace(); + assertEquals(0, sp); + String clr = table.getInsideVBorderColor(); + assertEquals("00FF00", clr); + } + public void testSetGetRowBandSize() { XWPFDocument doc = new XWPFDocument(); CTTbl ctTable = CTTbl.Factory.newInstance(); @@ -230,32 +229,30 @@ public class TestXWPFTable extends TestCase { table.setColBandSize(16); int sz = table.getColBandSize(); assertEquals(16, sz); - } - - public void testCreateTable() throws Exception { - // open an empty document - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - - // create a table with 5 rows and 7 columns - int noRows = 5; - int noCols = 7; - XWPFTable table = doc.createTable(noRows,noCols); - - // assert the table is empty - List rows = table.getRows(); - assertEquals("Table has less rows than requested.", noRows, rows.size()); - for (XWPFTableRow xwpfRow : rows) - { - assertNotNull(xwpfRow); - for (int i = 0 ; i < 7 ; i++) - { - XWPFTableCell xwpfCell = xwpfRow.getCell(i); - assertNotNull(xwpfCell); - assertEquals("Empty cells should not have one paragraph.",1,xwpfCell.getParagraphs().size()); - xwpfCell = xwpfRow.getCell(i); - assertEquals("Calling 'getCell' must not modify cells content.",1,xwpfCell.getParagraphs().size()); - } - } - doc.getPackage().revert(); - } + } + + public void testCreateTable() throws Exception { + // open an empty document + XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); + + // create a table with 5 rows and 7 columns + int noRows = 5; + int noCols = 7; + XWPFTable table = doc.createTable(noRows, noCols); + + // assert the table is empty + List rows = table.getRows(); + assertEquals("Table has less rows than requested.", noRows, rows.size()); + for (XWPFTableRow xwpfRow : rows) { + assertNotNull(xwpfRow); + for (int i = 0; i < 7; i++) { + XWPFTableCell xwpfCell = xwpfRow.getCell(i); + assertNotNull(xwpfCell); + assertEquals("Empty cells should not have one paragraph.", 1, xwpfCell.getParagraphs().size()); + xwpfCell = xwpfRow.getCell(i); + assertEquals("Calling 'getCell' must not modify cells content.", 1, xwpfCell.getParagraphs().size()); + } + } + doc.getPackage().revert(); + } } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java index 76dfe38221..34d54c0410 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java @@ -17,71 +17,80 @@ * ==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; - -public class TestXWPFTableCell extends TestCase { - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - public void testSetGetVertAlignment() throws Exception { - // instantiate the following classes so they'll get picked up by - // the XmlBean process and added to the jar file. they are required - // for the following XWPFTableCell methods. - CTShd ctShd = CTShd.Factory.newInstance(); - assertNotNull(ctShd); - CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance(); - assertNotNull(ctVjc); - STShd stShd = STShd.Factory.newInstance(); - assertNotNull(stShd); - STVerticalJc stVjc = STVerticalJc.Factory.newInstance(); - assertNotNull(stVjc); - - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); +package org.apache.poi.xwpf.usermodel; + +import junit.framework.TestCase; +import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHMerge; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcBorders; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; + +public class TestXWPFTableCell extends TestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testSetGetVertAlignment() throws Exception { + // instantiate the following classes so they'll get picked up by + // the XmlBean process and added to the jar file. they are required + // for the following XWPFTableCell methods. + CTShd ctShd = CTShd.Factory.newInstance(); + assertNotNull(ctShd); + CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance(); + assertNotNull(ctVjc); + STShd stShd = STShd.Factory.newInstance(); + assertNotNull(stShd); + STVerticalJc stVjc = STVerticalJc.Factory.newInstance(); + assertNotNull(stVjc); + + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); + // table has a single row by default; grab it + XWPFTableRow tr = table.getRow(0); assertNotNull(tr); // row has a single cell by default; grab it XWPFTableCell cell = tr.getCell(0); - cell.setVerticalAlignment(XWPFVertAlign.BOTH); - XWPFVertAlign al = cell.getVerticalAlignment(); - assertEquals(XWPFVertAlign.BOTH, al); - } - - public void testSetGetColor() throws Exception { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); + cell.setVerticalAlignment(XWPFVertAlign.BOTH); + XWPFVertAlign al = cell.getVerticalAlignment(); + assertEquals(XWPFVertAlign.BOTH, al); + } + + public void testSetGetColor() throws Exception { + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); + // table has a single row by default; grab it + XWPFTableRow tr = table.getRow(0); assertNotNull(tr); // row has a single cell by default; grab it XWPFTableCell cell = tr.getCell(0); - cell.setColor("F0000F"); - String clr = cell.getColor(); - assertEquals("F0000F", clr); - } - - /** - * ensure that CTHMerge & CTTcBorders go in poi-ooxml.jar - */ - public void test54099(){ - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); + cell.setColor("F0000F"); + String clr = cell.getColor(); + assertEquals("F0000F", clr); + } + + /** + * ensure that CTHMerge & CTTcBorders go in poi-ooxml.jar + */ + public void test54099() { + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); XWPFTableRow tr = table.getRow(0); XWPFTableCell cell = tr.getCell(0); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java index abdf1688c9..b01f8e9dc4 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java @@ -15,55 +15,54 @@ limitations under the License. ==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import junit.framework.TestCase; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; - -public class TestXWPFTableRow extends TestCase { - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - public void testCreateRow() throws Exception { - CTRow ctRow = CTRow.Factory.newInstance(); - assertNotNull(ctRow); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testSetGetCantSplitRow() { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - - tr.setCantSplitRow(true); - boolean isCant = tr.isCantSplitRow(); - assert(isCant); - } - - public void testSetGetRepeatHeader() { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - - tr.setRepeatHeader(true); - boolean isRpt = tr.isRepeatHeader(); - assert(isRpt); - } -} +package org.apache.poi.xwpf.usermodel; + +import junit.framework.TestCase; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; + +public class TestXWPFTableRow extends TestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testCreateRow() throws Exception { + CTRow ctRow = CTRow.Factory.newInstance(); + assertNotNull(ctRow); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testSetGetCantSplitRow() { + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); + // table has a single row by default; grab it + XWPFTableRow tr = table.getRow(0); + assertNotNull(tr); + + tr.setCantSplitRow(true); + boolean isCant = tr.isCantSplitRow(); + assert (isCant); + } + + public void testSetGetRepeatHeader() { + // create a table + XWPFDocument doc = new XWPFDocument(); + CTTbl ctTable = CTTbl.Factory.newInstance(); + XWPFTable table = new XWPFTable(ctTable, doc); + // table has a single row by default; grab it + XWPFTableRow tr = table.getRow(0); + assertNotNull(tr); + + tr.setRepeatHeader(true); + boolean isRpt = tr.isRepeatHeader(); + assert (isRpt); + } +} -- 2.39.5