001package bradleyross.library.helpers;
002/**
003 * Common procedures for use with HTML document.
004 * @author bradleyross
005 *
006 */
007public class HtmlHelpers {
008        /**
009         * Replace the characters ampersand, less than, and greater than with
010         * literal strings so that they are not interpreted as HTML control characters.
011         * <p>This process is known as escaping the control characters.</p>
012         * @param value original string
013         * @return escaped string
014         */
015        public static String escape(String value) {
016                if (value == null) { return null; }
017                if (value.length() == 0) { return value; }
018                return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
019        }
020        /**
021         * Reverse the escaping of the control characters to get the original string.
022         * @param value escaped string
023         * @return original string
024         */
025        public static String unescape(String value) {
026                if (value == null) { return value; }
027                if (value.length() == 0) { return value; }
028                return value.replace("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
029        }
030        /**
031         * Test driver for process of escaping strings;
032         * @param value string to be converted
033         */
034        protected static void test(String value) {
035                if (value == null) {
036                        System.out.println("Argument has null value");
037                }
038                if (value.length() == 0) {
039                        System.out.println("Argument has zero length");
040                }
041                System.out.println("*****  *****  *****");
042                System.out.println(value);
043                System.out.println(escape(value));
044                System.out.println(unescape(escape(value)));
045                if (value.equals(unescape(escape(value)))) {
046                        System.out.println("Success");
047                } else {
048                        System.out.println("*****  *****  *****  *****  *****");
049                        System.out.println("*****  Failure");
050                        System.out.println("*****  *****  *****  *****  *****");
051                }
052                System.out.println("*****  *****  *****");
053        }
054        /**
055         * Main driver for test cases.
056         * @param args not used
057         */
058        public static void main(String args[]) {
059                String[] tests = { "<> &&", "&amp;&gt;&lt;" };
060                for (int i = 0; i < tests.length; i++) {
061                        test(tests[i]);
062                }
063        }
064}