001package bradleyross.library.helpers;
002import java.util.regex.Pattern;
003import java.io.PrintStream;
004import java.io.PrintWriter;
005import java.io.IOException;
006import java.sql.ResultSet;
007import java.sql.SQLException;
008import java.util.regex.Matcher;
009import bradleyross.library.helpers.GenericPrinter;
010/**
011 * Classes for manipulating strings.
012 * @author Bradley Ross
013 *
014 */
015public class StringHelpers 
016{
017        /**
018         * Pads a string with blanks to the right so that it has
019         * a specified size.
020         * 
021         * @param value String to be padded
022         * @param size Desired size of padded string
023         * @return Padded string
024         */
025        public static  String padRight (String value, int size)
026        {
027                if (value == null)
028                {
029                        StringBuffer local = new StringBuffer();
030                        for (int i = 0; i < size; i++)
031                        {
032                                local.append(" ");
033                        }
034                        return new String(local);
035                }
036                if (value.length() >= size)
037                {
038                        return value;
039                }
040                StringBuffer working = new StringBuffer(value);
041                int padding = size - value.length();
042                if (padding <= 0) { return value; }
043                for (int i = 0; i < padding; i++)
044                {
045                        working.append(" ");
046                }
047                return new String(working);
048        }
049        /**
050         * Pads a string with blanks to the left so that it has
051         * a specified size.
052         * 
053         * @param value String to be padded
054         * @param size Desired size of padded string
055         * @return Padded string
056         */
057        public static  String padLeft (String value, int size)
058        {
059                if (value == null)
060                {
061                        StringBuffer local = new StringBuffer();
062                        for (int i = 0; i < size; i++)
063                        {
064                                local.append(" ");
065                        }
066                        return new String(local);
067                }
068                if (value.length() >= size)
069                {
070                        return value;
071                }
072                StringBuffer working = new StringBuffer();
073                int padding = size - value.length();
074                if (padding <= 0) { return value; }
075                for (int i = 0; i < padding; i++)
076                {
077                        working.append(" ");
078                }
079                working.append(value);
080                return new String(working);
081        }
082        /**
083         * Returns true if the string is only composed of numeric
084         * digits.
085         * @param value String to be evaluated
086         * @return True if string only has numeric digits 
087         * as characters.
088         */
089        public static boolean isDigitsOnly(String value)
090        {
091                return Pattern.matches("^[0-9]*$", value.trim());
092        }
093        /**
094         * Returns true if and only if all of the characters in
095         * the string are alphanumeric.
096         * @param value String to be evaluated
097         * @return True if string has only alphanumeric characters
098         */
099        public static boolean isAlphanumericOnly(String value)
100        {
101                return Pattern.matches("^[0-9a-zA-Z]*$", value.trim());
102        }
103        public static void printJustified(String value) throws IOException
104        {
105                printJustified(System.out, value, 72);
106        }
107    public static void printJustified(String value, int length) throws IOException
108    {
109        printJustified(System.out, value, length);
110    }
111    public static void printJustified(PrintStream output, String value) throws IOException
112    {
113        printJustified (output, value, 72);
114    }
115    public static void printJustified(PrintWriter output, String value) throws IOException
116    {
117        printJustified (output, value, 72);
118    }
119    public static void printJustified(GenericPrinter output, String value) throws IOException
120    {
121        printJustified(output, value, 72);
122    }
123        public static void printJustified(PrintStream output, String value, int length) throws IOException
124        {
125                GenericPrinter writer = new GenericPrinter(output);
126                printJustified(writer, value, length);
127        }
128        public static void printJustified(PrintWriter output, String value, int length) throws IOException
129        {
130                GenericPrinter writer = new GenericPrinter(output);
131                printJustified(writer, value, length);
132        }
133        /**
134         * Send a string to an output device, inserting line breaks at the
135         * first space after a specified number of characters on the line.
136         * @param output Output device
137         * @param value String to be sent to output
138         * @param length Number of characters on a line after which the next space
139         *        is to be replaced by a line feed.
140         * @throws IOException if io errors
141         */
142        protected static void printJustified(GenericPrinter output, String value, int length) throws IOException
143        {
144                if (value == null)
145                {
146                        output.println();       
147                        return;
148                }
149                String working = value.trim();
150                if (working.length() == 0)
151                {
152                        output.println();
153                        return;
154                }
155                while (true)
156                {
157                        working = working.trim();
158                        if (working.length() == 0)
159                        {
160                                return;
161                        }
162                        int newLocation = working.indexOf(" ", length);
163                        if (newLocation < 0)
164                        {
165                                output.println(working);
166                                return;
167                        }
168                        output.println(working.substring(0, newLocation).trim());
169                        working = working.substring(newLocation).trim();
170                }
171        }
172        /**
173         * Replace less than signs, greater than signs, and ampersands in a 
174         * string with their HTML representations.
175         * @param value String to be modified
176         * @return Modified string
177         */
178        public static String escapeHTML(String value)
179        {
180                return escapeHTML(value, "NORMAL");
181        }
182        /**
183         * Carry out the HTML escaping of a string twice.
184         * 
185         * @param value String to be escaped
186         * @return Escaped string
187         */
188        public static String doubleEscapeHTML(String value)
189        {
190                return escapeHTML(escapeHTML(value));
191        }
192        /**
193         * Carry out the HTML escaping of a string twice.
194         * 
195         * @param value String to be escaped
196         * @param modeValue Mode of escaping
197         * @return Escaped string
198         */
199        public static String doubleEscapeHTML(String value, String modeValue)
200        {
201                return escapeHTML(escapeHTML(value, modeValue));
202        }
203        /**
204         * Carry out the HTML escaping of a string twice.
205         * 
206         * @param rs Result set containing value
207         * @param parameterName Name of column in result set
208         * @param modeValue Type of processing for escaping
209         * @return Escaped string
210         */
211        public static String doubleEscapeHTML(ResultSet rs, String parameterName, String modeValue)
212        {
213                return escapeHTML(escapeHTML(rs, parameterName, modeValue));
214        }
215        /**
216         * Replace less than signs, greater than signs, and ampersands in a 
217         * string with their HTML representations.
218         * <p>If mode is TEXTAREA or TEXT, do not replace line breaks.  When
219         *    escaping the contents of a TEXTAREA tag, the new line and carriage return
220         *    characters should remain unchanged so that they are properly
221         *    represented in the form.</p>
222         * @param value String to be modified
223         * @param modeValue Mode of operation
224         * @return Modified string
225         */
226        public static String escapeHTML(String value, String modeValue)
227        {
228                String mode = modeValue;
229                if (mode == null)
230                {
231                        modeValue="NORMAL";
232                }
233                if (value == null)
234                {
235                        return " ";
236                }
237                else if (value.trim().length() == 0)
238                {
239                        return " ";
240                }
241                String working = null;
242                Pattern pattern = Pattern.compile("\\&");
243                Matcher matcher = pattern.matcher(value);
244                working =  matcher.replaceAll("&amp;");
245                pattern = Pattern.compile("\\\"");
246                matcher = pattern.matcher(working);
247                working = matcher.replaceAll("&quot;");
248                pattern = Pattern.compile("\\<");
249                matcher = pattern.matcher(working);
250                working = matcher.replaceAll("&lt;");
251                pattern = Pattern.compile("\\>");
252                matcher = pattern.matcher(working);
253                working = matcher.replaceAll("&gt;");
254                if (!(mode.equalsIgnoreCase("TEXTAREA") || mode.equalsIgnoreCase("TEXT")))
255                {
256                        pattern = Pattern.compile("\r\n");
257                        matcher = pattern.matcher(working);
258                        working = matcher.replaceAll("<br />");
259                        pattern = Pattern.compile("\r");
260                        matcher = pattern.matcher(working);
261                        working = matcher.replaceAll("<br />");
262                        pattern = Pattern.compile("\n");
263                        matcher = pattern.matcher(working);
264                        working = matcher.replaceAll("<br />");
265                }
266                return working;
267        }
268        /**
269         * Processes special characters in HTML code so that it will
270         * not be interpreted by browser as commands.
271         * 
272         * <p>Uses @{link {@link #escapeHTML(String, String)}.</p>
273         * @param rs Result set containing value.
274         * @param parameterName Name of column containing value
275         * @param mode Mode of processing to be used
276         * @return Escaped string
277         */
278        public static String escapeHTML(ResultSet rs, String parameterName, String mode)
279        {
280                try
281                {
282                String working = rs.getString(parameterName);
283                if (rs.wasNull())
284                { working = new String(); }
285                return escapeHTML(working, mode);
286                }
287                catch (SQLException e)
288                {
289                        return new String();
290                }
291        }
292        /**
293         * Processes special characters in HTML code so that it will
294         * not be interpreted by browser as commands.
295         * 
296         * <p>Uses @{link {@link #escapeHTML(String)}.</p>
297         * @param rs Result set containing value.
298         * @param parameterName Name of column containing value
299         * @return Escaped string
300         */
301        public static String escapeHTML(ResultSet rs, String parameterName)
302        {
303                return escapeHTML(rs, parameterName, "NORMAL");
304        }
305        /**
306         * Test driver.
307         * @param args Not used
308         */
309        public static void main(String args[])
310        {
311                try {
312                System.out.println("Starting test driver at " + (new java.util.Date()).toString());
313                System.out.println("***");
314                System.out.println("*** Tests for isDigitsOnly");
315                String list[] = { "123456", "-2", "a", "a1", "2" };
316                for (int i = 0; i < list.length; i++)
317                {
318                        System.out.println(Boolean.toString(isDigitsOnly(list[i])) + " " + list[i]);
319                }
320                System.out.println("***");
321                System.out.println("*** Tests for escapeHTML");
322                String list2[] = { "<abc&def>", "&&", "<<<>>>", "\"this\"", "aa\"\"bb", "a'b" };
323                for (int i = 0; i < list2.length; i++)
324                {
325                        System.out.println(list2[i] + "   " + escapeHTML(list2[i]));
326                }
327                System.out.println("***");
328                System.out.println("*** Tests for printJustified");
329                String working = "abcdefghijklmnopqrstuvwxyz  01234567890123456789 " +
330                       "Now is the time for all good men to come to the aid of their country. " +
331                       "The quick brown fox jumped over the lazy dog.";
332                printJustified(working, 70);
333                System.out.println("***");
334                System.out.println("*** Tests for isAlphanumericOnly");
335                String list3[] = {"alpha23", "a b", "abc", "ABc", "a\"b9", "a&b" };
336                for (int i = 0; i < list3.length; i++)
337                {
338                        System.out.println(Boolean.toString(isAlphanumericOnly(list3[i])) + " " + list3[i]);
339                }
340                } catch (IOException e) {
341                        System.out.println(e.getClass().getName() + " " + e.getMessage());
342                }
343        }
344}