Example usage for org.w3c.dom Element getNodeName

List of usage examples for org.w3c.dom Element getNodeName

Introduction

In this page you can find the example usage for org.w3c.dom Element getNodeName.

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:org.docx4j.convert.in.xhtml.XHTMLImporter.java

private void traverse(Box box, List<Object> contentContext, Box parent, TableProperties tableProperties)
        throws Docx4JException {

    log.debug(box.getClass().getName());
    if (box instanceof BlockBox) {
        BlockBox blockBox = ((BlockBox) box);

        Element e = box.getElement();

        // Don't add a new paragraph if this BlockBox is display: inline
        if (e == null) {
            // Shouldn't happen
            log.debug("<NULL>");
        } else {/*from   w  w  w  . ja v a2s  . c o m*/
            log.debug("BB" + "<" + e.getNodeName() + " " + box.getStyle().toStringMine());

            //Map cssMap = styleReference.getCascadedPropertiesMap(e);
            Map<String, CSSValue> cssMap = getCascadedProperties(box.getStyle());

            /* Sometimes, when it is display: inline, the following is not set:
               CSSValue cssValue = (CSSValue)cssMap.get("display");
               if (cssValue !=null) {
             log.debug(cssValue.getCssText() );
               }
            */
            // So do it this way ...
            if (box.getStyle().getDisplayMine().equals("inline")) {
                // Don't add a paragraph for this, unless ..
                if (currentP == null) {
                    currentP = Context.getWmlObjectFactory().createP();
                    contentContext.add(currentP);
                    paraStillEmpty = true;
                }

            } else if (box instanceof org.docx4j.org.xhtmlrenderer.newtable.TableSectionBox) {
                // nb, both TableBox and TableSectionBox 
                // have node name 'table' (or can have),
                // so this else clause is before the TableBox one,
                // to avoid a class cast exception

                // eg <tbody color: #000000; background-color: transparent; background-image: none; background-repeat: repeat; background-attachment: scroll; background-position: [0%, 0%]; background-size: [auto, auto]; border-collapse: collapse; -fs-border-spacing-horizontal: 0; -fs-border-spacing-vertical: 0; -fs-font-metric-src: none; -fs-keep-with-inline: auto; -fs-page-width: auto; -fs-page-height: auto; -fs-page-sequence: auto; -fs-pdf-font-embed: auto; -fs-pdf-font-encoding: Cp1252; -fs-page-orientation: auto; -fs-table-paginate: auto; -fs-text-decoration-extent: line; bottom: auto; caption-side: top; clear: none; ; content: normal; counter-increment: none; counter-reset: none; cursor: auto; ; display: table-row-group; empty-cells: show; float: none; font-style: normal; font-variant: normal; font-weight: normal; font-size: medium; line-height: normal; font-family: serif; -fs-table-cell-colspan: 1; -fs-table-cell-rowspan: 1; height: auto; left: auto; letter-spacing: normal; list-style-type: disc; list-style-position: outside; list-style-image: none; max-height: none; max-width: none; min-height: 0; min-width: 0; orphans: 2; ; ; ; overflow: visible; page: auto; page-break-after: auto; page-break-before: auto; page-break-inside: auto; position: static; ; right: auto; src: none; table-layout: auto; text-align: left; text-decoration: none; text-indent: 0; text-transform: none; top: auto; ; vertical-align: middle; visibility: visible; white-space: normal; word-wrap: normal; widows: 2; width: auto; word-spacing: normal; z-index: auto; border-top-color: #000000; border-right-color: #000000; border-bottom-color: #000000; border-left-color: #000000; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; border-top-width: 2px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 2px; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; 
                log.debug(".. processing <tbody");

                // Do nothing here for now .. the switch statement below traverses children

                // TODO: give effect to this CSS

            } else if (box instanceof org.docx4j.org.xhtmlrenderer.newtable.TableBox) {

                log.debug(".. processing table"); // what happened to <colgroup><col style="width: 2.47in;" /><col style="width: 2.47in;" /> 

                /*
                 * BEWARE: xhtmlrenderer seems to parse tables differently,
                 * depending on whether:
                 * 
                 * (i) the table is contained within a <div>
                 * 
                 * (ii) the table contains <caption>
                 * 
                 * See https://github.com/plutext/flyingsaucer/issues/1
                 * 
                 * Bare table with caption: BlockBox cannot be cast to TableSectionBox in xhtmlrenderer
                 * 
                 * div/table[count(caption)=1] ... table becomes TableBox, children are CONTENT_BLOCK
                 * 
                 * div/table[count(caption)=0] ... table becomes TableBox, children are CONTENT_BLOCK
                 * 
                 * 
                        
                 * 
                 */

                org.docx4j.org.xhtmlrenderer.newtable.TableBox cssTable = (org.docx4j.org.xhtmlrenderer.newtable.TableBox) box;

                tableProperties = new TableProperties();
                tableProperties.setTableBox(cssTable);

                // eg <table color: #000000; background-color: transparent; background-image: none; background-repeat: repeat; background-attachment: scroll; background-position: [0%, 0%]; background-size: [auto, auto]; 
                //           border-collapse: collapse; -fs-border-spacing-horizontal: 2px; -fs-border-spacing-vertical: 2px; -fs-font-metric-src: none; -fs-keep-with-inline: auto; -fs-page-width: auto; -fs-page-height: auto; -fs-page-sequence: auto; -fs-pdf-font-embed: auto; -fs-pdf-font-encoding: Cp1252; -fs-page-orientation: auto; -fs-table-paginate: auto; -fs-text-decoration-extent: line; bottom: auto; caption-side: top; clear: none; ; content: normal; counter-increment: none; counter-reset: none; cursor: auto; ; display: table; empty-cells: show; float: none; font-style: normal; font-variant: normal; font-weight: normal; font-size: medium; line-height: normal; font-family: serif; -fs-table-cell-colspan: 1; -fs-table-cell-rowspan: 1; height: auto; left: auto; letter-spacing: normal; list-style-type: disc; list-style-position: outside; list-style-image: none; max-height: none; max-width: none; min-height: 0; min-width: 0; orphans: 2; ; ; ; overflow: visible; page: auto; page-break-after: auto; page-break-before: auto; page-break-inside: auto; position: relative; ; right: auto; src: none; 
                //           table-layout: fixed; text-align: left; text-decoration: none; text-indent: 0; text-transform: none; top: auto; ; vertical-align: baseline; visibility: visible; white-space: normal; word-wrap: normal; widows: 2; width: auto; word-spacing: normal; z-index: auto; border-top-color: #000000; border-right-color: #000000; border-bottom-color: #000000; border-left-color: #000000; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0in; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0;

                contentContext = nestedTableHierarchyFix(contentContext, parent);

                Tbl tbl = Context.getWmlObjectFactory().createTbl();
                contentContext.add(tbl);
                paraStillEmpty = true;
                contentContext = tbl.getContent();

                TblPr tblPr = Context.getWmlObjectFactory().createTblPr();
                tbl.setTblPr(tblPr);

                TblStyle tblStyle = Context.getWmlObjectFactory().createCTTblPrBaseTblStyle();
                tblStyle.setVal("TableGrid");
                tblPr.setTblStyle(tblStyle);

                // borders.  rudimentary support
                // for now, look just at border-top-style.
                // If it is not 'none', for example 'solid', display a border.
                // cssTable.getBorder requires a CssContext; so just
                FSDerivedValue borderTopStyle = box.getStyle().valueByName(CSSName.BORDER_TOP_STYLE);
                if (borderTopStyle != null // what to default to if its null?
                        && borderTopStyle.asString().toLowerCase().contains("none")) {
                    log.debug("setting borders to none");
                    try {
                        TblBorders borders = (TblBorders) XmlUtils.unmarshalString(WORDML_TABLE_BORDERS,
                                Context.jc, TblBorders.class);
                        tblPr.setTblBorders(borders);
                    } catch (JAXBException e1) {
                    }
                }

                // Table indent.  
                // cssTable.getLeftMBP() which is setLeftMBP((int) margin.left() + (int) border.left() + (int) padding.left());
                // cssTable.getTx(); which is (int) margin.left() + (int) border.left() + (int) padding.left();
                // But want just margin.left
                if (cssTable.getMargin() != null && cssTable.getMargin().left() > 0) {
                    log.debug("Calculating TblInd from margin.left: " + cssTable.getMargin().left());
                    TblWidth tblIW = Context.getWmlObjectFactory().createTblWidth();
                    tblIW.setW(BigInteger.valueOf(Math.round(cssTable.getMargin().left())));
                    tblIW.setType(TblWidth.TYPE_DXA);
                    tblPr.setTblInd(tblIW);
                }

                // <w:tblW w:w="0" w:type="auto"/>
                // for both fixed width and auto fit tables.
                // You'd only set it to something else
                // eg <w:tblW w:w="5670" w:type="dxa"/>
                // for what in Word corresponds to 
                // "Preferred width".  TODO: decide what CSS
                // requires that.
                TblWidth tblW = Context.getWmlObjectFactory().createTblWidth();
                tblW.setW(BigInteger.ZERO);
                tblW.setType(TblWidth.TYPE_AUTO);
                tblPr.setTblW(tblW);

                if (cssTable.getStyle().isIdent(CSSName.TABLE_LAYOUT, IdentValue.AUTO)
                        || cssTable.getStyle().isAutoWidth()) {
                    // Conditions under which FS creates AutoTableLayout

                    tableProperties.setFixedWidth(false);

                    // This is the default, so no need to set 
                    // STTblLayoutType.AUTOFIT

                } else {
                    // FS creates FixedTableLayout
                    tableProperties.setFixedWidth(true);

                    // <w:tblLayout w:type="fixed"/>
                    CTTblLayoutType tblLayout = Context.getWmlObjectFactory().createCTTblLayoutType();
                    tblLayout.setType(STTblLayoutType.FIXED);
                    tblPr.setTblLayout(tblLayout);
                }

                // Word can generally open a table without tblGrid:
                // <w:tblGrid>
                //  <w:gridCol w:w="4621"/>
                //  <w:gridCol w:w="4621"/>
                // </w:tblGrid>
                // but for an AutoFit table (most common), it 
                // is the w:gridCol val which prob specifies the actual width
                TblGrid tblGrid = Context.getWmlObjectFactory().createTblGrid();
                tbl.setTblGrid(tblGrid);

                int[] colPos = tableProperties.getColumnPos();

                for (int i = 1; i <= cssTable.numEffCols(); i++) {

                    TblGridCol tblGridCol = Context.getWmlObjectFactory().createTblGridCol();
                    tblGrid.getGridCol().add(tblGridCol);

                    log.debug("colpos=" + colPos[i]);
                    tblGridCol.setW(BigInteger.valueOf(colPos[i] - colPos[i - 1]));

                }

            } else if (e.getNodeName().equals("table")) {
                // but not instanceof org.docx4j.org.xhtmlrenderer.newtable.TableBox
                // .. this does happen.  See test/resources/block-level-lots.xhtml

                // TODO: look at whether we can style the table in this case

                log.warn("Encountered non-TableBox table: " + box.getClass().getName());

                contentContext = nestedTableHierarchyFix(contentContext, parent);

                Tbl tbl = Context.getWmlObjectFactory().createTbl();
                contentContext.add(tbl);
                paraStillEmpty = true;
                contentContext = tbl.getContent();

            } else if (box instanceof org.docx4j.org.xhtmlrenderer.newtable.TableRowBox) {

                // eg <tr color: #000000; background-color: transparent; background-image: none; background-repeat: repeat; background-attachment: scroll; background-position: [0%, 0%]; background-size: [auto, auto]; border-collapse: collapse; -fs-border-spacing-horizontal: 0; -fs-border-spacing-vertical: 0; -fs-font-metric-src: none; -fs-keep-with-inline: auto; -fs-page-width: auto; -fs-page-height: auto; -fs-page-sequence: auto; -fs-pdf-font-embed: auto; -fs-pdf-font-encoding: Cp1252; -fs-page-orientation: auto; -fs-table-paginate: auto; -fs-text-decoration-extent: line; bottom: auto; caption-side: top; clear: none; ; content: normal; counter-increment: none; counter-reset: none; cursor: auto; ; display: table-row; empty-cells: show; float: none; font-style: normal; font-variant: normal; font-weight: normal; font-size: medium; line-height: normal; font-family: serif; -fs-table-cell-colspan: 1; -fs-table-cell-rowspan: 1; height: auto; left: auto; letter-spacing: normal; list-style-type: disc; list-style-position: outside; list-style-image: none; max-height: none; max-width: none; min-height: 0; min-width: 0; orphans: 2; ; ; ; overflow: visible; page: auto; page-break-after: auto; page-break-before: auto; page-break-inside: auto; position: static; ; right: auto; src: none; table-layout: auto; text-align: left; text-decoration: none; text-indent: 0; text-transform: none; top: auto; ; vertical-align: top; visibility: visible; white-space: normal; word-wrap: normal; widows: 2; width: auto; word-spacing: normal; z-index: auto; border-top-color: #000000; border-right-color: #000000; border-bottom-color: #000000; border-left-color: #000000; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; border-top-width: 2px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 2px; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0;

                // TODO support vertical-align

                log.debug(".. processing <tr");

                Tr tr = Context.getWmlObjectFactory().createTr();
                contentContext.add(tr);
                paraStillEmpty = true;
                contentContext = tr.getContent();

            } else if (box instanceof org.docx4j.org.xhtmlrenderer.newtable.TableCellBox) {

                log.debug(".. processing <td");
                // eg <td color: #000000; background-color: transparent; background-image: none; background-repeat: repeat; background-attachment: scroll; background-position: [0%, 0%]; background-size: [auto, auto]; border-collapse: collapse; -fs-border-spacing-horizontal: 0; -fs-border-spacing-vertical: 0; -fs-font-metric-src: none; -fs-keep-with-inline: auto; -fs-page-width: auto; -fs-page-height: auto; -fs-page-sequence: auto; -fs-pdf-font-embed: auto; -fs-pdf-font-encoding: Cp1252; -fs-page-orientation: auto; -fs-table-paginate: auto; -fs-text-decoration-extent: line; bottom: auto; caption-side: top; clear: none; ; content: normal; counter-increment: none; counter-reset: none; cursor: auto; ; display: table-row; empty-cells: show; float: none; font-style: normal; font-variant: normal; font-weight: normal; font-size: medium; line-height: normal; font-family: serif; -fs-table-cell-colspan: 1; -fs-table-cell-rowspan: 1; height: auto; left: auto; letter-spacing: normal; list-style-type: disc; list-style-position: outside; list-style-image: none; max-height: none; max-width: none; min-height: 0; min-width: 0; orphans: 2; ; ; ; overflow: visible; page: auto; page-break-after: auto; page-break-before: auto; page-break-inside: auto; position: static; ; right: auto; src: none; table-layout: auto; text-align: left; text-decoration: none; text-indent: 0; text-transform: none; top: auto; ; vertical-align: top; visibility: visible; white-space: normal; word-wrap: normal; widows: 2; width: auto; word-spacing: normal; z-index: auto; border-top-color: #000000; border-right-color: #000000; border-bottom-color: #000000; border-left-color: #000000; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; border-top-width: 2px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 2px; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0;

                List<Object> trContext = contentContext;
                org.docx4j.org.xhtmlrenderer.newtable.TableCellBox tcb = (org.docx4j.org.xhtmlrenderer.newtable.TableCellBox) box;
                // tcb.getVerticalAlign()

                // rowspan support: vertically merged cells are
                // represented as a top cell containing the actual content with a vMerge tag with "restart" attribute 
                // and a series of dummy cells having a vMerge tag with no (or "continue") attribute.                  

                // if cell to the left in source is part of a rowspan, 
                // insert dummy cell first                     
                int effCol;
                TableSectionBox section = tcb.getSection();
                effCol = tcb.getTable().colToEffCol(tcb.getCol());
                if (effCol != 0) {
                    TableCellBox prevCell = section.cellAt(tcb.getRow(), tcb.getCol() - 1);
                    log.debug("Got prevCell for " + tcb.getRow() + ", " + tcb.getCol());
                    log.debug("it is  " + prevCell.getRow() + ", " + prevCell.getCol());
                    if (prevCell.getRow() < tcb.getRow() && prevCell.getStyle() != null
                            && prevCell.getStyle().getRowSpan() > 1) {
                        // eg tcb is r2,c1 & prevCell is r1,c0
                        Tc dummy = Context.getWmlObjectFactory().createTc();
                        contentContext.add(dummy);

                        TcPr tcPr = Context.getWmlObjectFactory().createTcPr();
                        dummy.setTcPr(tcPr);

                        VMerge vm = Context.getWmlObjectFactory().createTcPrInnerVMerge();
                        //vm.setVal("continue");
                        tcPr.setVMerge(vm);

                        this.setCellWidthAuto(tcPr);

                        // Must have an empty w:p
                        dummy.getContent().add(new P());
                    }
                }

                // The cell proper
                Tc tc = Context.getWmlObjectFactory().createTc();
                contentContext.add(tc);
                contentContext = tc.getContent();

                // if the td contains bare text (eg <td>apple</td>)
                // we need a p for it
                currentP = Context.getWmlObjectFactory().createP();
                contentContext.add(currentP);
                paraStillEmpty = true;

                // Do we need a vMerge tag with "restart" attribute?
                // get cell below (only 1 section supported at present)
                TcPr tcPr = Context.getWmlObjectFactory().createTcPr();
                tc.setTcPr(tcPr);
                if (tcb.getStyle().getRowSpan() > 1) {

                    VMerge vm = Context.getWmlObjectFactory().createTcPrInnerVMerge();
                    vm.setVal("restart");
                    tcPr.setVMerge(vm);
                }
                // eg <w:tcW w:w="2268" w:type="dxa"/>
                try {
                    TblWidth tblW = Context.getWmlObjectFactory().createTblWidth();
                    tblW.setW(BigInteger.valueOf(tableProperties.getColumnWidth(effCol + 1)));
                    tblW.setType(TblWidth.TYPE_DXA);
                    tcPr.setTcW(tblW);
                } catch (java.lang.ArrayIndexOutOfBoundsException aioob) {
                    // happens with http://en.wikipedia.org/wiki/Office_Open_XML
                    log.error("Problem with getColumnWidth for col" + (effCol + 1));
                }
                /*                  The below works, but the above formulation is simpler
                 * 
                 *                int r = tcb.getRow() + tcb.getStyle().getRowSpan() - 1;
                                    if (r < tcb.getSection().numRows() - 1) {
                // The cell is not in the last row, so use the next row in the
                // section.
                TableCellBox belowCell = section.cellAt( r + 1, effCol);
                                       log.debug("Got belowCell for " + tcb.getRow() + ", " + tcb.getCol() );
                                       log.debug("it is  " + belowCell.getRow() + ", " + belowCell.getCol() );
                if (belowCell.getRow() > tcb.getRow() + 1 ) {
                 TcPr tcPr = Context.getWmlObjectFactory().createTcPr();
                tc.setTcPr(tcPr);
                        
                VMerge vm = Context.getWmlObjectFactory().createTcPrInnerVMerge();
                vm.setVal("restart");
                tcPr.setVMerge(vm);                           
                }
                                    } 
                 */

                // if this is the last real cell in the source,
                // is there a rowspan above and to the right?
                effCol = tcb.getTable().colToEffCol(tcb.getCol() + tcb.getStyle().getColSpan());
                int numEffCols = tcb.getTable().numEffCols();
                if (effCol >= numEffCols) {
                    // we we're already in rightmost col
                } else {
                    TableCellBox nextCell = tcb.getSection().cellAt(tcb.getRow(), effCol);
                    if (nextCell == null) {
                        //throw new Docx4JException("XHTML table import: Null nextCell for row " + tcb.getRow() + ", col " + tcb.getCol()); // Check your table is OK
                        log.error("XHTML table import: Null nextCell for row " + tcb.getRow() + ", col "
                                + tcb.getCol()); // Check your table is OK
                        // eg http://en.wikipedia.org/w/index.php?title=Microsoft_Word&printable=yes
                    } else {
                        log.debug("Got nextCell for " + tcb.getRow() + ", " + tcb.getCol());
                        log.debug("it is  " + nextCell.getRow() + ", " + nextCell.getCol());
                        if (nextCell.getRow() < tcb.getRow()
                                // && nextCell.getStyle().getRowSpan()>1
                                && nextCell.getTable().colToEffCol(
                                        nextCell.getCol() + nextCell.getStyle().getColSpan()) == numEffCols // rightmost
                        ) {
                            log.debug("it has rowspan  " + nextCell.getStyle().getRowSpan());
                            // eg tcb is r2,c1 & nextCell is r1,c2
                            Tc dummy = Context.getWmlObjectFactory().createTc();
                            trContext.add(dummy);

                            TcPr tcPr2 = Context.getWmlObjectFactory().createTcPr();
                            dummy.setTcPr(tcPr2);

                            VMerge vm = Context.getWmlObjectFactory().createTcPrInnerVMerge();
                            //vm.setVal("continue");
                            tcPr2.setVMerge(vm);

                            this.setCellWidthAuto(tcPr2);

                            // Must have an empty w:p
                            dummy.getContent().add(new P());
                        }
                    }
                }

                // colspan support: horizontally merged cells are represented by one cell
                // with a gridSpan attribute; 
                int colspan = tcb.getStyle().getColSpan();
                if (colspan > 1) {

                    if (tc.getTcPr() != null) {
                        log.warn("Trying to add GridSpan, when we've already added VMerge"); // this code doesn't support both at once
                    }

                    TcPr tcPr2 = Context.getWmlObjectFactory().createTcPr();
                    tc.setTcPr(tcPr2);

                    GridSpan gs = Context.getWmlObjectFactory().createTcPrInnerGridSpan();
                    gs.setVal(BigInteger.valueOf(colspan));
                    tcPr2.setGridSpan(gs);

                    this.setCellWidthAuto(tcPr2);
                }

            } else {

                // Avoid creating paragraphs for html, body
                if (contentContext.size() > 0 && paraStillEmpty) {
                    contentContext.remove(contentContext.size() - 1);
                }

                currentP = Context.getWmlObjectFactory().createP();
                contentContext.add(currentP);
                paraStillEmpty = true;

                // Paragraph level styling
                currentP.setPPr(addParagraphProperties(cssMap));

                if (e.getNodeName().equals("li")) {
                    addNumbering(e, cssMap);
                } else if (e.getNodeName().equals("img")) {
                    // TODO, should we be using ReplacedElementFactory approach instead?                     
                    addImage(e);
                }

            }
        }

        // the recursive bit:

        Object lastChild = null;

        log.debug("Processing children of " + box.getElement().getNodeName());
        switch (blockBox.getChildrenContentType()) {
        case BlockBox.CONTENT_BLOCK:
            log.debug(".. which are BlockBox.CONTENT_BLOCK");
            for (Object o : ((BlockBox) box).getChildren()) {

                lastChild = o;

                traverse((Box) o, contentContext, box, tableProperties);
                log.debug(".. processed child " + o.getClass().getName());
            }
            break;
        case BlockBox.CONTENT_INLINE:

            log.debug(".. which are BlockBox.CONTENT_INLINE");

            if (((BlockBox) box).getInlineContent() != null) {

                for (Object o : ((BlockBox) box).getInlineContent()) {
                    //                            log.debug("        " + o.getClass().getName() ); 
                    if (o instanceof InlineBox) {
                        //                                    && ((InlineBox)o).getElement()!=null // skip these (pseudo-elements?)
                        //                                    && ((InlineBox)o).isStartsHere()) {

                        processInlineBox((InlineBox) o, contentContext);

                    } else if (o instanceof BlockBox) {
                        traverse((Box) o, contentContext, box, tableProperties); // commenting out gets rid of unwanted extra parent elements
                    } else {
                        log.debug("What to do with " + box.getClass().getName());
                    }
                    log.debug(".. processed child " + o.getClass().getName());
                }
            }
            break;
        }

        log.debug("Done processing children of " + box.getClass().getName());
        // contentContext gets its old value back each time recursion finishes,
        // ensuring elements are added at the appropriate level (eg inside tr) 

        // An empty tc shouldn't make the table disappear!
        // TODO - make more elegant
        if (e.getNodeName().equals("table")) {
            paraStillEmpty = false;
        }

        //           if ( (lastChild instanceof Box)
        //                 && ((Box)lastChild).getElement().getNodeName().equals("table") ) {
        //              System.out.println("## " + e.getNodeName() );
        //           }       

        // nested tables must end with a <p/> or Word 2010 can't open the docx!
        // ie:
        // <w:tc>
        //   <w:tbl>..</w:tbl>
        //   <w:p/>                <---------- 
        // </w:tc>
        // This fixes the dodgy table/table case
        if (box instanceof TableBox || box.getElement().getNodeName().equals("table")) {

            if ((lastChild instanceof Box) && ((Box) lastChild).getElement().getNodeName().equals("table")) {
                log.debug("Adding <w:p/> after nested table");
                P extraP = Context.getWmlObjectFactory().createP();

                Tr tr = (Tr) contentContext.get(contentContext.size() - 1);
                ((Tc) tr.getContent().get(tr.getContent().size() - 1)).getContent().add(extraP);
                //contentContext.add(extraP);                  
                paraStillEmpty = false; // ??                 
            }
        }

        if (e.getNodeName().equals("td")) { // untested

            if ((lastChild instanceof Box) && ((Box) lastChild).getElement().getNodeName().equals("table")) {
                log.debug("Adding <w:p/> after nested table");
                P extraP = Context.getWmlObjectFactory().createP();

                contentContext.add(extraP);
                paraStillEmpty = false; // ??                 
            }
        }

    } else if (box instanceof AnonymousBlockBox) {
        log.debug("AnonymousBlockBox");
    }

}

From source file:org.dozer.loader.xml.XMLParser.java

/**
 * Builds object representation of mappings based on content of Xml document
 *
 * @return mapping container/*from  w  ww .j  ava2 s.  c o m*/
 */
public MappingFileData read(Document document) {
    DozerBuilder builder = new DozerBuilder();

    Element theRoot = document.getDocumentElement();
    NodeList nl = theRoot.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element ele = (Element) node;
            log.debug("name: {}", ele.getNodeName());
            if (CONFIGURATION_ELEMENT.equals(ele.getNodeName())) {
                parseConfiguration(ele, builder);
            } else if (MAPPING_ELEMENT.equals(ele.getNodeName())) {
                parseMapping(ele, builder);
            }
        }
    }

    return builder.build();
}

From source file:org.dozer.loader.xml.XMLParser.java

private void parseMapping(Element ele, DozerBuilder builder) {
    DozerBuilder.MappingBuilder definitionBuilder = builder.mapping();

    if (StringUtils.isNotEmpty(getAttribute(ele, DATE_FORMAT))) {
        definitionBuilder.dateFormat(getAttribute(ele, DATE_FORMAT));
    }/*from ww  w  .ja  va2  s. c  om*/
    if (StringUtils.isNotEmpty(getAttribute(ele, MAP_NULL_ATTRIBUTE))) {
        definitionBuilder.mapNull(BooleanUtils.toBoolean(getAttribute(ele, MAP_NULL_ATTRIBUTE)));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, MAP_EMPTY_STRING_ATTRIBUTE))) {
        definitionBuilder.mapEmptyString(BooleanUtils.toBoolean(getAttribute(ele, MAP_EMPTY_STRING_ATTRIBUTE)));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, BEAN_FACTORY))) {
        definitionBuilder.beanFactory(getAttribute(ele, BEAN_FACTORY));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, RELATIONSHIP_TYPE))) {
        String relationshipTypeValue = getAttribute(ele, RELATIONSHIP_TYPE);
        RelationshipType relationshipType = RelationshipType.valueOf(relationshipTypeValue);
        definitionBuilder.relationshipType(relationshipType);
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, WILDCARD))) {
        definitionBuilder.wildcard(Boolean.valueOf(getAttribute(ele, WILDCARD)));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, TRIM_STRINGS))) {
        definitionBuilder.trimStrings(Boolean.valueOf(getAttribute(ele, TRIM_STRINGS)));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, STOP_ON_ERRORS_ATTRIBUTE))) {
        definitionBuilder.stopOnErrors(Boolean.valueOf(getAttribute(ele, STOP_ON_ERRORS_ATTRIBUTE)));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, MAPID_ATTRIBUTE))) {
        definitionBuilder.mapId(getAttribute(ele, MAPID_ATTRIBUTE));
    }
    if (StringUtils.isNotEmpty(getAttribute(ele, TYPE_ATTRIBUTE))) {
        String mappingDirection = getAttribute(ele, TYPE_ATTRIBUTE);
        MappingDirection direction = MappingDirection.valueOf(mappingDirection);
        definitionBuilder.type(direction);
    }
    NodeList nl = ele.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;
            debugElement(element);
            if (CLASS_A_ELEMENT.equals(element.getNodeName())) {
                String typeName = getNodeValue(element);
                DozerBuilder.ClassDefinitionBuilder classBuilder = definitionBuilder.classA(typeName);
                parseClass(element, classBuilder);
            }
            if (CLASS_B_ELEMENT.equals(element.getNodeName())) {
                String typeName = getNodeValue(element);
                DozerBuilder.ClassDefinitionBuilder classBuilder = definitionBuilder.classB(typeName);
                parseClass(element, classBuilder);
            }
            if (FIELD_ELEMENT.equals(element.getNodeName())) {
                parseGenericFieldMap(element, definitionBuilder);
            } else if (FIELD_EXCLUDE_ELEMENT.equals(element.getNodeName())) {
                parseFieldExcludeMap(element, definitionBuilder);
            }
        }
    }
}

From source file:org.dozer.loader.xml.XMLParser.java

private void parseConfiguration(Element ele, DozerBuilder builder) {
    DozerBuilder.ConfigurationBuilder configBuilder = builder.configuration();
    NodeList nl = ele.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);/*from w ww  .ja  va  2  s  . c o m*/
        if (node instanceof Element) {
            Element element = (Element) node;

            debugElement(element);

            final String nodeValue = getNodeValue(element);

            if (STOP_ON_ERRORS_ELEMENT.equals(element.getNodeName())) {
                configBuilder.stopOnErrors(Boolean.valueOf(nodeValue));
            } else if (DATE_FORMAT.equals(element.getNodeName())) {
                configBuilder.dateFormat(nodeValue);
            } else if (WILDCARD.equals(element.getNodeName())) {
                configBuilder.wildcard(Boolean.valueOf(nodeValue));
            } else if (TRIM_STRINGS.equals(element.getNodeName())) {
                configBuilder.trimStrings(Boolean.valueOf(nodeValue));
            } else if (MAP_NULL.equals(element.getNodeName())) {
                configBuilder.mapNull(Boolean.valueOf(nodeValue));
            } else if (MAP_EMPTY_STRING.equals(element.getNodeName())) {
                configBuilder.mapEmptyString(Boolean.valueOf(nodeValue));
            } else if (RELATIONSHIP_TYPE.equals(element.getNodeName())) {
                RelationshipType relationshipType = RelationshipType.valueOf(nodeValue);
                configBuilder.relationshipType(relationshipType);
            } else if (BEAN_FACTORY.equals(element.getNodeName())) {
                configBuilder.beanFactory(nodeValue);
            } else if (CUSTOM_CONVERTERS_ELEMENT.equals(element.getNodeName())) {
                parseCustomConverters(element, configBuilder);
            } else if (COPY_BY_REFERENCES_ELEMENT.equals(element.getNodeName())) {
                parseCopyByReferences(element, configBuilder);
            } else if (ALLOWED_EXCEPTIONS_ELEMENT.equals(element.getNodeName())) {
                parseAllowedExceptions(element, configBuilder);
            } else if (VARIABLES_ELEMENT.equals(element.getNodeName())) {
                parseVariables(element);
            }
        }
    }
}

From source file:org.dozer.loader.xml.XMLParser.java

private void parseVariables(Element element) {
    NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);//www.  j a v a 2 s. com
        if (node instanceof Element) {
            Element ele = (Element) node;

            debugElement(ele);

            if (VARIABLE_ELEMENT.equals(ele.getNodeName())) {
                ELEngine engine = BeanContainer.getInstance().getElEngine();
                if (engine != null) {
                    String name = getAttribute(ele, NAME_ATTRIBUTE);
                    String value = getNodeValue(ele);

                    engine.setVariable(name, value);
                }
            }
        }
    }

}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.TypeLibraryActivator.java

/**
 * Gets the name space.// ww w. j a v  a  2 s  .c o m
 *
 * @param xsdTypeDefinition the xsd type definition
 * @return the name space
 * @throws SOABadParameterException the sOA bad parameter exception
 */
public static String getNameSpace(XSDTypeDefinition xsdTypeDefinition) throws SOABadParameterException {
    for (XSDAnnotation annotation : xsdTypeDefinition.getAnnotations()) {
        for (Element element : annotation.getApplicationInformation()) {
            NodeList children = element.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i);
                if (node instanceof Element) {
                    Element childElement = (Element) node;
                    if (StringUtils.equals(childElement.getNodeName(), SOATypeLibraryConstants.TAG_TYPE_LIB)) {
                        if (StringUtils
                                .isEmpty(childElement.getAttribute(SOATypeLibraryConstants.ATTR_NMSPC))) {
                            throw new SOABadParameterException(StringUtil.formatString(SOAMessages.ERR_NMSPC,
                                    xsdTypeDefinition.getName()));
                        }
                        return childElement.getAttribute(SOATypeLibraryConstants.ATTR_NMSPC);
                    }
                }

            }
        }
    }
    return xsdTypeDefinition.getTargetNamespace();
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.wst.WTPTypeLibUtil.java

public static String getNameSpace(XSDTypeDefinition xsdTypeDefinition) throws SOABadParameterException {
    for (XSDAnnotation annotation : xsdTypeDefinition.getAnnotations()) {
        for (Element element : annotation.getApplicationInformation()) {
            NodeList children = element.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i);
                if (node instanceof Element) {
                    Element childElement = (Element) node;
                    if (StringUtils.equals(childElement.getNodeName(), SOATypeLibraryConstants.TAG_TYPE_LIB)) {
                        if (StringUtils
                                .isEmpty(childElement.getAttribute(SOATypeLibraryConstants.ATTR_NMSPC))) {
                            throw new SOABadParameterException(StringUtil.formatString(SOAMessages.ERR_NMSPC,
                                    xsdTypeDefinition.getName()));
                        }/*from ww  w  .j a  v  a2 s .  c  o  m*/
                        return childElement.getAttribute(SOATypeLibraryConstants.ATTR_NMSPC);
                    }
                }

            }
        }
    }
    return xsdTypeDefinition.getTargetNamespace();
}

From source file:org.eclipse.ecr.common.xmap.XMLBuilder.java

private static Element getOrCreateElement(Element parent, String segment) {
    NodeList list = parent.getChildNodes();
    for (int i = 0, len = list.getLength(); i < len; i++) {
        Element e = (Element) list.item(i);
        if (segment.equals(e.getNodeName())) {
            return e;
        }//from w  ww.j  a v  a  2s  .  c o m
    }
    // node not found, create one
    return addElement(parent, segment);
}

From source file:org.eclipse.lyo.samples.sharepoint.SharepointConnector.java

public int createDocument(HttpServletResponse response, String library, FileItem item)
        throws UnrecognizedValueTypeException, ShareServerException {
    //   System.out.println("createDocument: uri='" + uri + "'");
    //SharepointResource sharepointResource = new SharepointResource(uri);

    //       String filename = resource.getSource();
    //       /* w w  w .j  ava  2s  .c o m*/
    //      OEntity newProduct = odatac.createEntity("Empire").properties(OProperties.int32("Id", 10))
    //                                                       .properties(OProperties.string("Name", filename))
    //                                                       .properties(OProperties.string("ContentType","Document"))
    //                                                       .properties(OProperties.string("Title","Architecture"))
    //                                                       .properties(OProperties.string("ApprovalStatus","2"))
    //                                                       .properties(OProperties.string("Path","/Empire"))   
    //                                                         .execute();  

    // no obvious API in odata4j to create a document, default apache http Create
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    BufferedReader br = null;
    int returnCode = 500;
    PostMethod method = null;
    try {
        client.setConnectionTimeout(8000);

        method = new PostMethod(SharepointInitializer.getSharepointUri() + "/" + library);
        String userPassword = SharepointInitializer.getUsername() + ":" + SharepointInitializer.getPassword();
        String encoding = Base64.encodeBase64String(userPassword.getBytes());
        encoding = encoding.replaceAll("\r\n?", "");
        method.setRequestHeader("Authorization", "Basic " + encoding);
        method.addRequestHeader("Content-type", item.getContentType());
        method.addRequestHeader(IConstants.HDR_SLUG, "/" + library + "/" + item.getName());

        //InputStream is =  new FileInputStream("E:\\odata\\sharepoint\\DeathStarTest.doc");

        RequestEntity entity = new InputStreamRequestEntity(item.getInputStream(), "application/msword");
        method.setRequestEntity(entity);
        method.setDoAuthentication(true);

        returnCode = client.executeMethod(method);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
            // still consume the response body
            method.getResponseBodyAsString();
        } else {
            //br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            InputStream is = method.getResponseBodyAsStream();
            //br = new BufferedReader(new InputStreamReader(is));          
            //    String readLine;
            //    while(((readLine = br.readLine()) != null)) {
            //      System.out.println(readLine);
            //    }

            response.setContentType("text/html");
            //response.setContentType("application/atom+xml");
            //response.setContentLength(is.getBytes().length);
            response.setStatus(IConstants.SC_OK);
            //response.getWriter().write("<html><head><title>hello world</title></head><body><p>hello world!</p></body></html>");
            //response.getWriter().write(method.getResponseBodyAsString());

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document doc = parser.parse(is);
            Element root = doc.getDocumentElement();

            System.out.println("Root element of the doc is " + root.getNodeName());

            //         String msftdPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            //         String msftmPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

            String id = null;
            String name = null;
            NodeList nl = root.getElementsByTagName("d:Id");
            if (nl.getLength() > 0) {
                id = nl.item(0).getFirstChild().getNodeValue();
            }

            //nl = root.getElementsByTagName("d:ContentType");         
            //if (nl.getLength() > 0) {
            //   type = nl.item(0).getFirstChild().getNodeValue(); 
            //}

            nl = root.getElementsByTagName("d:Name");
            if (nl.getLength() > 0) {
                name = nl.item(0).getFirstChild().getNodeValue();
            }

            response.getWriter().write("<html>");
            response.getWriter().write("<head>");
            response.getWriter().write("</head>");
            response.getWriter().write("<body>");
            response.getWriter().write("<p>" + name + " was created with an Id =" + id + "</p>");
            response.getWriter().write("</body>");
            response.getWriter().write("</html>");

            //response.getWriter().write(is.content);
            //String readLine;
            //while(((readLine = br.readLine()) != null)) {
            //   response.getWriter().write(readLine);
            //}
            //response.setContentType(IConstants.CT_XML);
            //response.getWriter().write(is.toString()); 
            //response.setStatus(IConstants.SC_OK);
            //test 
            //   String readLine;
            //   while(((readLine = br.readLine()) != null)) {
            //     System.out.println(readLine);
            //   }
        }
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace();
    } finally {
        if (method != null)
            method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }
    return returnCode;
}

From source file:org.eclipse.skalli.core.extension.DataMigration11.java

/**
 * Changes from model version 11 -> 12:
 * <ol>//  w  w w .  ja v a2  s.c om
 *   <li>Project members now in separate collections</li>
 * </ol>
 */
@Override
public void migrate(Document doc) {
    Map<String, String> roleCache = new HashMap<String, String>();

    List<String> members = new LinkedList<String>();
    List<String> leads = new LinkedList<String>();
    List<String> productOwners = new LinkedList<String>();
    List<String> scrumMasters = new LinkedList<String>();

    // reading old project members and their roles
    NodeList nodes = doc.getElementsByTagName("org.eclipse.skalli.model.core.ProjectMember");
    for (int i = 0; i < nodes.getLength(); i++) {
        Element member = (Element) nodes.item(i);
        String userId = member.getElementsByTagName("userID").item(0).getTextContent();
        LOG.debug("Reading User '" + userId + "' for Migration.");

        NodeList roles = member.getElementsByTagName("roles").item(0).getChildNodes();
        for (int j = 0; j < roles.getLength(); j++) {
            Node roleNode = (Node) roles.item(j);
            if (roleNode instanceof Element && !roleNode.getNodeName().equals("no-comparator")) {
                Element roleElement = (Element) roleNode;
                String role = null;
                if (StringUtils.isBlank(roleElement.getAttribute("reference"))) {
                    role = roleElement.getElementsByTagName("technicalName").item(0).getTextContent();
                    roleCache.put(roleElement.getNodeName(), role);
                } else {
                    role = roleCache.get(roleElement.getNodeName());
                }
                LOG.debug("User '" + userId + "' has role '" + role + "'.");
                if (role.equals("projectmember")) {
                    members.add(userId);
                } else if (role.equals("projectlead")) {
                    leads.add(userId);
                } else if (role.equals("scrummaster")) {
                    scrumMasters.add(userId);
                } else if (role.equals("productowner")) {
                    productOwners.add(userId);
                } else {
                    throw new RuntimeException("unknown role: " + role);
                }
            }
        }
    }

    // remove current "members" section
    Node membersNode = doc.getElementsByTagName("members").item(0);
    if (membersNode == null) {
        throw new RuntimeException(doc.toString());
    }
    Node projectNode = membersNode.getParentNode();
    projectNode.removeChild(membersNode);

    // add (new) members
    addPeopleSection(doc, projectNode, "members", members);

    // add leads
    addPeopleSection(doc, projectNode, "leads", leads);

    // add scrum people
    if (scrumMasters.size() > 0 || productOwners.size() > 0) {
        Node scrumExt = doc.getElementsByTagName("org.eclipse.skalli.model.ext.scrum.ScrumProjectExt").item(0);

        if (scrumExt == null) {
            LOG.warn("there were scrum people, but no scrum extension.");
        } else {
            // add scrum masters
            addPeopleSection(doc, scrumExt, "scrumMasters", scrumMasters);

            // add product owners
            addPeopleSection(doc, scrumExt, "productOwners", productOwners);
        }
    }
}