Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import org.w3c.dom.*;

public class Main {
    @SuppressWarnings({ "ChainOfInstanceofChecks" })
    private static void formatElementEnd(/*@Nonnull*/Document document, /*@Nonnull*/Element element, /*@Nonnull*/
            String formatString) {
        Node lastChild = element.getLastChild();

        if (lastChild != null) {
            if (lastChild instanceof Element) {
                element.appendChild(document.createTextNode(formatString));
            } else if (lastChild instanceof Text) {
                Text textNode = (Text) lastChild;
                String text = textNode.getWholeText();

                if (hasOnlyTextSiblings(textNode)) {
                    String trimmedText = text.trim();
                    if (!trimmedText.equals(text)) {
                        textNode.replaceWholeText(trimmedText);
                    }
                } else {
                    if (!formatString.equals(text)) {
                        textNode.replaceWholeText(trimRight(text) + formatString);
                    }
                }
            }
        }
    }

    public static boolean hasOnlyTextSiblings(/*@Nonnull*/Node node) {
        Node leftSibling = node.getPreviousSibling();

        while (leftSibling != null) {
            if (!(leftSibling instanceof Text)) {
                return false;
            }

            leftSibling = leftSibling.getPreviousSibling();
        }

        Node rightSibling = node.getNextSibling();

        while (rightSibling != null) {
            if (!(rightSibling instanceof Text)) {
                return false;
            }

            rightSibling = rightSibling.getNextSibling();
        }

        return true;
    }

    private static String trimRight(/*@Nullable*/String s) {
        if (s == null) {
            return null;
        }

        int lastIndex = s.length() - 1;
        int index = lastIndex;

        while (index >= 0 && s.charAt(index) <= ' ') {
            --index;
        }

        return index == lastIndex ? s : s.substring(0, index + 1);
    }
}