001package bradleyross.library.helpers;
002/**
003 * Common procedures for use with HTML document.
004 * @author Bradley Ross
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                        return;
038                } else if (value.length() == 0) {
039                        System.out.println("Argument has zero length");
040                        return;
041                }
042                System.out.println("*****  *****  *****");
043                System.out.println(value);
044                System.out.println(escape(value));
045                System.out.println(unescape(escape(value)));
046                if (value.equals(unescape(escape(value)))) {
047                        System.out.println("Success");
048                } else {
049                        System.out.println("*****  *****  *****  *****  *****");
050                        System.out.println("*****  Failure");
051                        System.out.println("*****  *****  *****  *****  *****");
052                }
053                System.out.println("*****  *****  *****");
054        }
055        /**
056         * Main driver for test cases.
057         * @param args not used
058         */
059        public static void main(String args[]) {
060                String[] tests = { "<> &&", "&amp;&gt;&lt;" };
061                for (int i = 0; i < tests.length; i++) {
062                        test(tests[i]);
063                }
064        }
065}