File Source: OldUtilities.java

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   *  contributor license agreements.  The ASF licenses this file to You
     4   * under the Apache License, Version 2.0 (the "License"); you may not
     5   * use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.  For additional information regarding
    15   * copyright in this work, please see the NOTICE file in the top level
    16   * directory of this distribution.
    17   */
    18  package org.apache.roller.weblogger.ui.rendering.velocity.deprecated;
    19  
    20  import java.io.IOException;
    21  import java.io.UnsupportedEncodingException;
    22  import java.net.URLDecoder;
    23  import java.net.URLEncoder;
    24  import java.text.SimpleDateFormat;
    25  import java.util.Date;
    26  import java.util.regex.Matcher;
    27  import java.util.regex.Pattern;
    28  import org.apache.commons.lang.StringEscapeUtils;
    29  import org.apache.commons.lang.StringUtils;
    30  import org.apache.commons.logging.Log;
    31  import org.apache.commons.logging.LogFactory;
    32  import org.apache.roller.util.DateUtil;
    33  import org.apache.roller.util.RegexUtil;
    34  import org.apache.roller.weblogger.util.Utilities;
    35  import org.apache.commons.codec.binary.Base64;
    36  
    37  /**
    38   * Utility methods needed by old Roller 2.X macros/templates.
    39   * Deprecated because they are either redundant or unnecesary.
    40   */
         /* 
    P/P   *  Method: void org.apache.roller.weblogger.ui.rendering.velocity.deprecated.OldUtilities()
          */
    41  public class OldUtilities {    
    42      
    43      /** The <code>Log</code> instance for this class. */
             /* 
    P/P       *  Method: org.apache.roller.weblogger.ui.rendering.velocity.deprecated.OldUtilities__static_init
              * 
              *  Postconditions:
              *    init'ed(BR_TAG_PATTERN)
              *    init'ed(CLOSING_A_TAG_PATTERN)
              *    init'ed(CLOSING_BLOCKQUOTE_TAG_PATTERN)
              *    init'ed(CLOSING_B_TAG_PATTERN)
              *    init'ed(CLOSING_I_TAG_PATTERN)
              *    init'ed(CLOSING_LI_TAG_PATTERN)
              *    init'ed(CLOSING_OL_TAG_PATTERN)
              *    init'ed(CLOSING_PRE_TAG_PATTERN)
              *    init'ed(CLOSING_P_TAG_PATTERN)
              *    init'ed(CLOSING_UL_TAG_PATTERN)
              *    ...
              */
    44      private static Log mLogger = LogFactory.getLog(OldUtilities.class);
    45      
    46      private static Pattern mLinkPattern =
    47              Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE);    
    48      private static final Pattern OPENING_B_TAG_PATTERN = 
    49              Pattern.compile("<b>", Pattern.CASE_INSENSITIVE);
    50      private static final Pattern CLOSING_B_TAG_PATTERN = 
    51              Pattern.compile("</b>", Pattern.CASE_INSENSITIVE);
    52      private static final Pattern OPENING_I_TAG_PATTERN = 
    53              Pattern.compile("<i>", Pattern.CASE_INSENSITIVE);
    54      private static final Pattern CLOSING_I_TAG_PATTERN = 
    55              Pattern.compile("</i>", Pattern.CASE_INSENSITIVE);
    56      private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = 
    57              Pattern.compile("<blockquote>", Pattern.CASE_INSENSITIVE);
    58      private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = 
    59              Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE);
    60      private static final Pattern BR_TAG_PATTERN = 
    61              Pattern.compile("<br */*>", Pattern.CASE_INSENSITIVE);
    62      private static final Pattern OPENING_P_TAG_PATTERN = 
    63              Pattern.compile("<p>", Pattern.CASE_INSENSITIVE);
    64      private static final Pattern CLOSING_P_TAG_PATTERN = 
    65              Pattern.compile("</p>", Pattern.CASE_INSENSITIVE);
    66      private static final Pattern OPENING_PRE_TAG_PATTERN = 
    67              Pattern.compile("<pre>", Pattern.CASE_INSENSITIVE);
    68      private static final Pattern CLOSING_PRE_TAG_PATTERN = 
    69              Pattern.compile("</pre>", Pattern.CASE_INSENSITIVE);
    70      private static final Pattern OPENING_UL_TAG_PATTERN = 
    71              Pattern.compile("<ul>", Pattern.CASE_INSENSITIVE);
    72      private static final Pattern CLOSING_UL_TAG_PATTERN = 
    73              Pattern.compile("</ul>", Pattern.CASE_INSENSITIVE);
    74      private static final Pattern OPENING_OL_TAG_PATTERN = 
    75              Pattern.compile("<ol>", Pattern.CASE_INSENSITIVE);
    76      private static final Pattern CLOSING_OL_TAG_PATTERN = 
    77              Pattern.compile("</ol>", Pattern.CASE_INSENSITIVE);
    78      private static final Pattern OPENING_LI_TAG_PATTERN = 
    79              Pattern.compile("<li>", Pattern.CASE_INSENSITIVE);
    80      private static final Pattern CLOSING_LI_TAG_PATTERN = 
    81              Pattern.compile("</li>", Pattern.CASE_INSENSITIVE);
    82      private static final Pattern CLOSING_A_TAG_PATTERN = 
    83              Pattern.compile("</a>", Pattern.CASE_INSENSITIVE);
    84      private static final Pattern OPENING_A_TAG_PATTERN = 
    85              Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE);
    86      private static final Pattern QUOTE_PATTERN = 
    87              Pattern.compile(""", Pattern.CASE_INSENSITIVE);
    88              
    89      public static boolean isEmpty(String str) {
                 /* 
    P/P           *  Method: bool isEmpty(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    str: Inverse{null}, Addr_Set{null}
                  */
    90          if (str == null) return true;
    91          return "".equals(str.trim());
    92      }
    93      
    94      public static boolean isNotEmpty(String str) {
                 /* 
    P/P           *  Method: bool isNotEmpty(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
    95          return !isEmpty(str);
    96      }
    97      
    98      public static String[] split(String str1, String str2) {
                 /* 
    P/P           *  Method: String[] split(String, String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
    99          return StringUtils.split(str1, str2);
   100      }
   101      
   102      public static String replace(String src, String target, String rWith) {
                 /* 
    P/P           *  Method: String replace(String, String, String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   103          return StringUtils.replace(src, target, rWith);
   104      }
   105      
   106      public static String replace(String src, String target, String rWith, int maxCount) {
                 /* 
    P/P           *  Method: String replace(String, String, String, int)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   107          return StringUtils.replace(src, target, rWith, maxCount);
   108      }
   109      
   110      public static boolean equals(String str1, String str2) {
                 /* 
    P/P           *  Method: bool equals(String, String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   111          return StringUtils.equals(str1, str2);
   112      }
   113      
   114      public static boolean isAlphanumeric(String str) {
                 /* 
    P/P           *  Method: bool isAlphanumeric(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   115          return StringUtils.isAlphanumeric(str);
   116      }
   117      
   118      public static String[] stripAll(String[] strs) {
                 /* 
    P/P           *  Method: String[] stripAll(String[])
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   119          return StringUtils.stripAll(strs);
   120      }
   121      
   122      public static String left(String str, int length) {
                 /* 
    P/P           *  Method: String left(String, int)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   123          return StringUtils.left(str, length);
   124      }
   125      
   126      public static String escapeHTML(String str) {
                 /* 
    P/P           *  Method: String escapeHTML(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   127          return StringEscapeUtils.escapeHtml(str);
   128      }
   129      
   130      public static String unescapeHTML(String str) {
                 /* 
    P/P           *  Method: String unescapeHTML(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   131          return StringEscapeUtils.unescapeHtml(str);
   132      }
   133                 
   134      /**
   135       * Remove occurences of html, defined as any text
   136       * between the characters "<" and ">".  Replace
   137       * any HTML tags with a space.
   138       */
   139      public static String removeHTML(String str) {
                 /* 
    P/P           *  Method: String removeHTML(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   140          return removeHTML(str, true);
   141      }
   142      
   143      /**
   144       * Remove occurences of html, defined as any text
   145       * between the characters "<" and ">".
   146       * Optionally replace HTML tags with a space.
   147       */
   148      public static String removeHTML(String str, boolean addSpace) {
                 /* 
    P/P           *  Method: String removeHTML(String, bool)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   149          return Utilities.removeHTML(str, addSpace);
   150      }
   151          
   152      /**
   153       * Autoformat.
   154       */
   155      public static String autoformat(String s) {
                 /* 
    P/P           *  Method: String autoformat(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   156          String ret = StringUtils.replace(s, "\n", "<br />");
   157          return ret;
   158      }
   159      
   160      /**
   161       * Return date for current time.
   162       */
   163      public static Date getNow() {
                 /* 
    P/P           *  Method: Date getNow()
                  * 
                  *  Postconditions:
                  *    return_value == &new Date(getNow#1)
                  *    new Date(getNow#1) num objects == 1
                  */
   164          return new Date();
   165      }
   166      
   167      /**
   168       * Format date using SimpleDateFormat format string.
   169       */
   170      public static String formatDate(Date d, String fmt) {
                 /* 
    P/P           *  Method: String formatDate(Date, String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   171          SimpleDateFormat format = new SimpleDateFormat(fmt);
   172          return format.format(d);
   173      }
   174      
   175      /**
   176       * Format date in ISO-8601 format.
   177       */
   178      public static String formatIso8601Date(Date d) {
                 /* 
    P/P           *  Method: String formatIso8601Date(Date)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   179          return DateUtil.formatIso8601(d);
   180      }
   181      
   182      /**
   183       * Format date in ISO-8601 format.
   184       */
   185      public static String formatIso8601Day(Date d) {
                 /* 
    P/P           *  Method: String formatIso8601Day(Date)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   186          return DateUtil.formatIso8601Day(d);
   187      }
   188      
   189      /**
   190       * Return a date in RFC-822 format.
   191       */
   192      public static String formatRfc822Date(Date date) {
                 /* 
    P/P           *  Method: String formatRfc822Date(Date)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   193          return DateUtil.formatRfc822(date);
   194      }
   195      
   196      /**
   197       * Return a date in RFC-822 format.
   198       */
   199      public static String format8charsDate(Date date) {
                 /* 
    P/P           *  Method: String format8charsDate(Date)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   200          return DateUtil.format8chars(date);
   201      }
   202      
   203      /**
   204       * Strips HTML and truncates.
   205       */
   206      public static String truncate(
   207              String str, int lower, int upper, String appendToEnd) {
   208          // strip markup from the string
                 /* 
    P/P           *  Method: String truncate(String, int, int, String)
                  * 
                  *  Presumptions:
                  *    org.apache.roller.weblogger.util.Utilities:removeHTML(...)@149 != null
                  * 
                  *  Postconditions:
                  *    java.lang.String:substring(...)._tainted == 0
                  *    init'ed(java.lang.StringBuilder:toString(...)._tainted)
                  *    (soft) return_value != null
                  * 
                  *  Test Vectors:
                  *    lower - upper: {-6_442_450_943..0}, {1..6_442_450_943}
                  */
   209          String str2 = removeHTML(str, false);
   210          
   211          // quickly adjust the upper if it is set lower than 'lower'
   212          if (upper < lower) {
   213              upper = lower;
   214          }
   215          
   216          // now determine if the string fits within the upper limit
   217          // if it does, go straight to return, do not pass 'go' and collect $200
   218          if(str2.length() > upper) {
   219              // the magic location int
   220              int loc;
   221              
   222              // first we determine where the next space appears after lower
   223              loc = str2.lastIndexOf(' ', upper);
   224              
   225              // now we'll see if the location is greater than the lower limit
   226              if(loc >= lower) {
   227                  // yes it was, so we'll cut it off here
   228                  str2 = str2.substring(0, loc);
   229              } else {
   230                  // no it wasnt, so we'll cut it off at the upper limit
   231                  str2 = str2.substring(0, upper);
+  232                  loc = upper;
   233              }
   234              
   235              // the string was truncated, so we append the appendToEnd String
   236              str2 = str2 + appendToEnd;
   237          }
   238          
   239          return str2;
   240      }
   241      
   242      public static String truncateNicely(String str, int lower, int upper, String appendToEnd) {
                 /* 
    P/P           *  Method: String truncateNicely(String, int, int, String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   243          return Utilities.truncateNicely(str, lower, upper, appendToEnd);
   244      }
   245      
   246      public static String truncateText(String str, int lower, int upper, String appendToEnd) {
   247          // strip markup from the string
                 /* 
    P/P           *  Method: String truncateText(String, int, int, String)
                  * 
                  *  Preconditions:
                  *    str != null
                  * 
                  *  Presumptions:
                  *    org.apache.roller.weblogger.util.Utilities:removeHTML(...)@149 != null
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuilder:toString(...)._tainted)
                  *    return_value == One-of{str, &java.lang.StringBuilder:toString(...)}
                  *    return_value != null
                  * 
                  *  Test Vectors:
                  *    lower - upper: {-6_442_450_943..0}, {1..6_442_450_943}
                  */
   248          String str2 = removeHTML(str, false);
+  249          boolean diff = (str2.length() < str.length());
   250          
   251          // quickly adjust the upper if it is set lower than 'lower'
   252          if(upper < lower) {
   253              upper = lower;
   254          }
   255          
   256          // now determine if the string fits within the upper limit
   257          // if it does, go straight to return, do not pass 'go' and collect $200
   258          if(str2.length() > upper) {
   259              // the magic location int
   260              int loc;
   261              
   262              // first we determine where the next space appears after lower
   263              loc = str2.lastIndexOf(' ', upper);
   264              
   265              // now we'll see if the location is greater than the lower limit
   266              if(loc >= lower) {
   267                  // yes it was, so we'll cut it off here
   268                  str2 = str2.substring(0, loc);
   269              } else {
   270                  // no it wasnt, so we'll cut it off at the upper limit
   271                  str2 = str2.substring(0, upper);
+  272                  loc = upper;
   273              }
   274              // the string was truncated, so we append the appendToEnd String
   275              str = str2 + appendToEnd;
   276          }
   277          return str;
   278      }    
   279      
   280      public static String hexEncode(String str) {
                 /* 
    P/P           *  Method: String hexEncode(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    org.apache.commons.lang.StringUtils:isEmpty(...)@281: {0}, {1}
                  */
   281          if (StringUtils.isEmpty(str)) return str;
   282          
   283          return RegexUtil.encode(str);
   284      }
   285      
   286      public static String encodeEmail(String str) {
                 /* 
    P/P           *  Method: String encodeEmail(String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   287          return str!=null ? RegexUtil.encodeEmail(str) : null;
   288      }
   289      
   290      /**
   291       * URL encoding.
   292       * @param s a string to be URL-encoded
   293       * @return URL encoding of s using character encoding UTF-8; null if s is null.
   294       */
   295      public static final String encode(String s) {
   296          try {
                     /* 
    P/P               *  Method: String encode(String)
                      * 
                      *  Postconditions:
                      *    init'ed(return_value)
                      * 
                      *  Test Vectors:
                      *    s: Addr_Set{null}, Inverse{null}
                      */
   297              if (s != null)
   298                  return URLEncoder.encode(s, "UTF-8");
   299              else
   300                  return s;
   301          } catch (UnsupportedEncodingException e) {
   302              // Java Spec requires UTF-8 be in all Java environments, so this should not happen
   303              return s;
   304          }
   305      }
   306      
   307      /**
   308       * URL decoding.
   309       * @param s a URL-encoded string to be URL-decoded
   310       * @return URL decoded value of s using character encoding UTF-8; null if s is null.
   311       */
   312      public static final String decode(String s) {
   313          try {
                     /* 
    P/P               *  Method: String decode(String)
                      * 
                      *  Postconditions:
                      *    init'ed(return_value)
                      * 
                      *  Test Vectors:
                      *    s: Addr_Set{null}, Inverse{null}
                      */
   314              if (s != null)
   315                  return URLDecoder.decode(s, "UTF-8");
   316              else
   317                  return s;
   318          } catch (UnsupportedEncodingException e) {
   319              // Java Spec requires UTF-8 be in all Java environments, so this should not happen
   320              return s;
   321          }
   322      }
   323          
   324      /**
   325       * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML.
   326       */
   327      public static String addNofollow(String html) {
                 /* 
    P/P           *  Method: String addNofollow(String)
                  * 
                  *  Preconditions:
                  *    (soft) mLinkPattern != null
                  * 
                  *  Presumptions:
                  *    java.util.regex.Pattern:matcher(...)@331 != null
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuffer:toString(...)._tainted)
                  *    return_value == One-of{html, &java.lang.StringBuffer:toString(...)}
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    html: Addr_Set{null}, Inverse{null}
                  *    java.lang.String:indexOf(...)@338: {-231..-2, 0..232-1}, {-1}
                  *    java.lang.String:length(...)@328: {1..232-1}, {0}
                  *    java.util.regex.Matcher:find(...)@333: {0}, {1}
                  */
   328          if (html == null || html.length() == 0) {
   329              return html;
   330          }
   331          Matcher m = mLinkPattern.matcher(html);
   332          StringBuffer buf = new StringBuffer();
   333          while (m.find()) {
   334              int start = m.start();
   335              int end = m.end();
   336              String link = html.substring(start, end);
   337              buf.append(html.substring(0, start));
   338              if (link.indexOf("rel=\"nofollow\"") == -1) {
   339                  buf.append(
   340                          link.substring(0, link.length() - 1) + " rel=\"nofollow\">");
   341              } else {
   342                  buf.append(link);
   343              }
   344              html = html.substring(end, html.length());
   345              m = mLinkPattern.matcher(html);
   346          }
   347          buf.append(html);
   348          return buf.toString();
   349      }
   350      
   351      /**
   352       * Transforms the given String into a subset of HTML displayable on a web
   353       * page. The subset includes <b>, <i>, <p>, <br>,
   354       * <pre> and <a href> (and their corresponding end tags).
   355       *
   356       * @param s   the String to transform
   357       * @return    the transformed String
   358       */
   359      public static String transformToHTMLSubset(String s) {
   360          
                 /* 
    P/P           *  Method: String transformToHTMLSubset(String)
                  * 
                  *  Presumptions:
                  *    java.util.regex.Matcher:replaceAll(...)@406 != null
                  *    java.util.regex.Pattern:compile(...)@48 != null
                  *    java.util.regex.Pattern:compile(...)@50 != null
                  *    java.util.regex.Pattern:compile(...)@52 != null
                  *    java.util.regex.Pattern:compile(...)@54 != null
                  *    ...
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuilder:toString(...)._tainted)
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    s: Inverse{null}, Addr_Set{null}
                  *    java.util.regex.Matcher:find(...)@387: {0}, {1}
                  */
   361          if (s == null) {
   362              return null;
   363          }
   364          
   365          s = replace(s, OPENING_B_TAG_PATTERN, "<b>");
   366          s = replace(s, CLOSING_B_TAG_PATTERN, "</b>");
   367          s = replace(s, OPENING_I_TAG_PATTERN, "<i>");
   368          s = replace(s, CLOSING_I_TAG_PATTERN, "</i>");
   369          s = replace(s, OPENING_BLOCKQUOTE_TAG_PATTERN, "<blockquote>");
   370          s = replace(s, CLOSING_BLOCKQUOTE_TAG_PATTERN, "</blockquote>");
   371          s = replace(s, BR_TAG_PATTERN, "<br />");
   372          s = replace(s, OPENING_P_TAG_PATTERN, "<p>");
   373          s = replace(s, CLOSING_P_TAG_PATTERN, "</p>");
   374          s = replace(s, OPENING_PRE_TAG_PATTERN, "<pre>");
   375          s = replace(s, CLOSING_PRE_TAG_PATTERN, "</pre>");
   376          s = replace(s, OPENING_UL_TAG_PATTERN, "<ul>");
   377          s = replace(s, CLOSING_UL_TAG_PATTERN, "</ul>");
   378          s = replace(s, OPENING_OL_TAG_PATTERN, "<ol>");
   379          s = replace(s, CLOSING_OL_TAG_PATTERN, "</ol>");
   380          s = replace(s, OPENING_LI_TAG_PATTERN, "<li>");
   381          s = replace(s, CLOSING_LI_TAG_PATTERN, "</li>");
   382          s = replace(s, QUOTE_PATTERN, "\"");
   383          
   384          // HTTP links
   385          s = replace(s, CLOSING_A_TAG_PATTERN, "</a>");
   386          Matcher m = OPENING_A_TAG_PATTERN.matcher(s);
   387          while (m.find()) {
   388              int start = m.start();
   389              int end = m.end();
   390              String link = s.substring(start, end);
   391              link = "<" + link.substring(4, link.length() - 4) + ">";
   392              s = s.substring(0, start) + link + s.substring(end, s.length());
   393              m = OPENING_A_TAG_PATTERN.matcher(s);
   394          }
   395          
   396          // escaped angle brackets
   397          s = s.replaceAll("&lt;", "<");
   398          s = s.replaceAll("&gt;", ">");
   399          s = s.replaceAll("&#", "&#");
   400          
   401          return s;
   402      }
   403      
   404      private static String replace(String string, Pattern pattern, String replacement) {
                 /* 
    P/P           *  Method: String replace(String, Pattern, String)
                  * 
                  *  Preconditions:
                  *    pattern != null
                  * 
                  *  Presumptions:
                  *    java.util.regex.Pattern:matcher(...)@405 != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   405          Matcher m = pattern.matcher(string);
   406          return m.replaceAll(replacement);
   407      }
   408      
   409      /**
   410       * Convert a byte array into a Base64 string (as used in mime formats)
   411       */
   412      public static String toBase64(byte[] aValue) {
   413          
                 /* 
    P/P           *  Method: String toBase64(byte[])
                  * 
                  *  Preconditions:
                  *    aValue != null
                  *    (soft) aValue.length in {0, 3..232-1}
                  *    (soft) init'ed(aValue[...])
                  * 
                  *  Postconditions:
                  *    java.lang.StringBuffer:toString(...)._tainted == 0
                  *    return_value == &java.lang.StringBuffer:toString(...)
                  */
+  414          final String m_strBase64Chars =
   415                  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
   416          
   417          int byte1;
   418          int byte2;
   419          int byte3;
   420          int iByteLen = aValue.length;
   421          StringBuffer tt = new StringBuffer();
   422          
   423          for (int i = 0; i < iByteLen; i += 3) {
   424              boolean bByte2 = (i + 1) < iByteLen;
   425              boolean bByte3 = (i + 2) < iByteLen;
   426              byte1 = aValue[i] & 0xFF;
   427              byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0;
   428              byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0;
   429              
   430              tt.append(m_strBase64Chars.charAt(byte1 / 4));
   431              tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16)));
   432              tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '='));
   433              tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '='));
   434          }
   435          
   436          return tt.toString();
   437      }
   438      
   439      
   440      //------------------------------------------------------------------------
   441      /**
   442       * Escape, but do not replace HTML.
   443       * @param escapeAmpersand Optionally escape
   444       * ampersands (&).
   445       */
   446      public static String escapeHTML(String s, boolean escapeAmpersand) {
                 /* 
    P/P           *  Method: String escapeHTML(String, bool)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   447          return Utilities.escapeHTML(s, escapeAmpersand);
   448      }
   449                  
   450      //------------------------------------------------------------------------
   451      /**
   452       * Replace occurrences of str1 in string str with str2
   453       */
   454      public static String stringReplace(String str, String str1, String str2) {
                 /* 
    P/P           *  Method: String stringReplace(String, String, String)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   455          String ret = StringUtils.replace(str,str1,str2);
   456          return ret;
   457      }
   458      
   459      //------------------------------------------------------------------------
   460      /**
   461       * Replace occurrences of str1 in string str with str2
   462       * @param str String to operate on
   463       * @param str1 String to be replaced
   464       * @param str2 String to be used as replacement
   465       * @param maxCount Number of times to replace, 0 for all
   466       */
   467      public static String stringReplace(
   468              String str,
   469              String str1,
   470              String str2,
   471              int maxCount) {
                 /* 
    P/P           *  Method: String stringReplace(String, String, String, int)
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   472          String ret = StringUtils.replace(str,str1,str2,maxCount);
   473          return ret;
   474      }
   475          
   476  
   477      
   478      /**
   479       * Encode a string using Base64 encoding. Used when storing passwords
   480       * as cookies.
   481       *
   482       * This is weak encoding in that anyone can use the decodeString
   483       * routine to reverse the encoding.
   484       *
   485       * @param str
   486       * @return String
   487       * @throws IOException
   488       */
   489      public static String encodeString(String str) throws IOException {
                 /* 
    P/P           *  Method: String encodeString(String)
                  * 
                  *  Preconditions:
                  *    str != null
                  * 
                  *  Postconditions:
                  *    return_value != null
                  */
+  490          Base64 base64 = new Base64();
   491          String encodedStr = new String(base64.encodeBase64(str.getBytes()));        
   492          return (encodedStr.trim());
   493      }
   494      
   495      /**
   496       * Decode a string using Base64 encoding.
   497       *
   498       * @param str
   499       * @return String
   500       * @throws IOException
   501       */
   502      public static String decodeString(String str) throws IOException {
                 /* 
    P/P           *  Method: String decodeString(String)
                  * 
                  *  Preconditions:
                  *    str != null
                  * 
                  *  Postconditions:
                  *    return_value == &new String(decodeString#2)
                  *    new String(decodeString#2) num objects == 1
                  */
+  503          Base64 base64 = new Base64();
   504          String value = new String(base64.decodeBase64(str.getBytes()));        
   505          return (value);
   506      }
   507                 
   508      /**
   509       * @param str
   510       * @return
   511       */
   512      private static String stripLineBreaks(String str) {
   513          // TODO: use a string buffer, ignore case !
                 /* 
    P/P           *  Method: String stripLineBreaks(String)
                  * 
                  *  Preconditions:
                  *    str != null
                  * 
                  *  Postconditions:
                  *    return_value != null
                  */
   514          str = str.replaceAll("<br>", "");
   515          str = str.replaceAll("<br/>", "");
   516          str = str.replaceAll("<br />", "");
   517          str = str.replaceAll("<p></p>", "");
   518          str = str.replaceAll("<p/>","");
   519          str = str.replaceAll("<p />","");
   520          return str;
   521      }
   522      
   523      /**
   524       * Need need to get rid of any user-visible HTML tags once all text has been
   525       * removed such as <BR>. This sounds like a better approach than removing
   526       * all HTML tags and taking the chance to leave some tags un-closed.
   527       *
   528       * WARNING: this method has serious performance problems a
   529       *
   530       * @author Alexis Moussine-Pouchkine (alexis.moussine-pouchkine@france.sun.com)
   531       * @author Lance Lavandowska
   532       * @param str the String object to modify
   533       * @return the new String object without the HTML "visible" tags
   534       */
   535      private static String removeVisibleHTMLTags(String str) {
                 /* 
    P/P           *  Method: String removeVisibleHTMLTags(String)
                  * 
                  *  Preconditions:
                  *    str != null
                  * 
                  *  Presumptions:
                  *    java.lang.StringBuffer:indexOf(...)@544 + java.lang.String:length(...)@546 in -231..232-1
                  *    java.lang.StringBuffer:indexOf(...)@544 + java.lang.String:length(...)@547 in -231..232-1
                  *    java.lang.StringBuffer:indexOf(...)@550 <= 232-2
                  *    java.lang.StringBuffer:indexOf(...)@568 <= 232-2
                  *    java.lang.StringBuffer:indexOf(...)@571 + java.lang.String:length(...)@574 in -231..232-1
                  *    ...
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuffer:toString(...)._tainted)
                  *    return_value == &java.lang.StringBuffer:toString(...)
                  * 
                  *  Test Vectors:
                  *    java.lang.String:endsWith(...)@545: {0}, {1}
                  *    java.lang.StringBuffer:charAt(...)@580: {0..46, 48..216-1}, {47}
                  *    java.lang.StringBuffer:indexOf(...)@544: {-1}, {-231..-2, 0..232-1}
                  *    java.lang.StringBuffer:indexOf(...)@550: {-231..-1}, {0..232-2}
                  *    java.lang.StringBuffer:indexOf(...)@568: {-231..-1}, {0..232-3}
                  *    java.lang.StringBuffer:indexOf(...)@571: {-231..-1}, {0..232-1}
                  *    java.lang.StringBuffer:indexOf(...)@579: {-231..-2, 0..232-2}, {-1}
                  */
   536          str = stripLineBreaks(str);
   537          StringBuffer result = new StringBuffer(str);
   538          StringBuffer lcresult = new StringBuffer(str.toLowerCase());
   539          
   540          // <img should take care of smileys
   541          String[] visibleTags = {"<img"}; // are there others to add?
   542          int stringIndex;
   543          for ( int j = 0 ;  j < visibleTags.length ; j++ ) {
   544              while ( (stringIndex = lcresult.indexOf(visibleTags[j])) != -1 ) {
   545                  if ( visibleTags[j].endsWith(">") )  {
   546                      result.delete(stringIndex, stringIndex+visibleTags[j].length() );
   547                      lcresult.delete(stringIndex, stringIndex+visibleTags[j].length() );
   548                  } else {
   549                      // need to delete everything up until next closing '>', for <img for instance
   550                      int endIndex = result.indexOf(">", stringIndex);
   551                      if (endIndex > -1) {
   552                          // only delete it if we find the end!  If we don't the HTML may be messed up, but we
   553                          // can't safely delete anything.
   554                          result.delete(stringIndex, endIndex + 1 );
   555                          lcresult.delete(stringIndex, endIndex + 1 );
   556                      }
   557                  }
   558              }
   559          }
   560          
   561          // TODO:  This code is buggy by nature.  It doesn't deal with nesting of tags properly.
   562          // remove certain elements with open & close tags
   563          String[] openCloseTags = {"li", "a", "div", "h1", "h2", "h3", "h4"}; // more ?
   564          for (int j = 0; j < openCloseTags.length; j++) {
   565              // could this be better done with a regular expression?
   566              String closeTag = "</"+openCloseTags[j]+">";
   567              int lastStringIndex = 0;
   568              while ( (stringIndex = lcresult.indexOf( "<"+openCloseTags[j], lastStringIndex)) > -1) {
   569                  lastStringIndex = stringIndex;
   570                  // Try to find the matching closing tag  (ignores possible nesting!)
   571                  int endIndex = lcresult.indexOf(closeTag, stringIndex);
   572                  if (endIndex > -1) {
   573                      // If we found it delete it.
   574                      result.delete(stringIndex, endIndex+closeTag.length());
   575                      lcresult.delete(stringIndex, endIndex+closeTag.length());
   576                  } else {
   577                      // Try to see if it is a self-closed empty content tag, i.e. closed with />.
   578                      endIndex = lcresult.indexOf(">", stringIndex);
   579                      int nextStart = lcresult.indexOf("<", stringIndex+1);
   580                      if (endIndex > stringIndex && lcresult.charAt(endIndex-1) == '/' && (endIndex < nextStart || nextStart == -1)) {
   581                          // Looks like it, so remove it.
   582                          result.delete(stringIndex, endIndex + 1);
   583                          lcresult.delete(stringIndex, endIndex + 1);
   584                          
   585                      }
   586                  }
   587              }
   588          }
   589          
   590          return result.toString();
   591      }
   592      
   593      
   594      /**
   595       * Converts a character to HTML or XML entity.
   596       *
   597       * @param ch The character to convert.
   598       * @param xml Convert the character to XML if set to true.
   599       * @author Erik C. Thauvin
   600       *
   601       * @return The converted string.
   602       */
   603      public static final String charToHTML(char ch, boolean xml) {
   604          int c;
   605          
   606          // Convert left bracket
                 /* 
    P/P           *  Method: String charToHTML(char, bool)
                  * 
                  *  Postconditions:
                  *    java.lang.String:valueOf(...)._tainted == 0
                  *    return_value in Addr_Set{&"&amp;quot;",&"&amp;#39;",&java.lang.String:valueOf(...),&"&amp;amp;",&"&amp;gt;",&"&amp;lt;"}
                  * 
                  *  Test Vectors:
                  *    ch: {39}, {60}, {62}, {38}, {34}
                  *    xml: {0}, {1}
                  */
   607          if (ch == '<') {
   608              return ("<");
   609          }
   610          
   611          // Convert left bracket
   612          else if (ch == '>') {
   613              return (">");
   614          }
   615          
   616          // Convert ampersand
   617          else if (ch == '&') {
   618              return ("&");
   619          }
   620          
   621          // Commented out to eliminate redundant numeric character codes (ROL-507)
   622          // High-ASCII character
   623          //else if (ch >= 128)
   624          //{
   625          //c = ch;
   626          //return ("&#" + c + ';');
   627          //}
   628          
   629          // Convert double quote
   630          else if (xml && (ch == '"')) {
   631              return (""");
   632          }
   633          
   634          // Convert single quote
   635          else if (xml && (ch == '\'')) {
   636              return ("&#39;");
   637          }
   638          
   639          // No conversion
   640          else {
   641              // Return character as string
   642              return (String.valueOf(ch));
   643          }
   644      }
   645      
   646      /**
   647       * Converts a text string to HTML or XML entities.
   648       *
   649       * @author Erik C. Thauvin
   650       * @param text The string to convert.
   651       * @param xml Convert the string to XML if set to true.
   652       *
   653       * @return The converted string.
   654       */
   655      public static final String textToHTML(String text, boolean xml) {
                 /* 
    P/P           *  Method: String textToHTML(String, bool)
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuffer:toString(...)._tainted)
                  *    return_value in Addr_Set{&java.lang.StringBuffer:toString(...),&"null"}
                  * 
                  *  Test Vectors:
                  *    text: Inverse{null}, Addr_Set{null}
                  */
   656          if (text == null) return "null";
   657          final StringBuffer html = new StringBuffer();
   658          
   659          // Loop thru each characters of the text
   660          for (int i = 0; i < text.length(); i++) {
   661              // Convert character to HTML/XML
   662              html.append(charToHTML(text.charAt(i), xml));
   663          }
   664          
   665          // Return HTML/XML string
   666          return html.toString();
   667      }
   668      
   669      /**
   670       * Converts a text string to HTML or XML entities.
   671       *
   672       * @param text The string to convert.
   673       * @author Erik C. Thauvin
   674       * @return The converted string.
   675       */
   676      public static final String textToHTML(String text) {
                 /* 
    P/P           *  Method: String textToHTML(String)
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuffer:toString(...)._tainted)
                  *    return_value == One-of{&"null", &java.lang.StringBuffer:toString(...)}
                  *    return_value in Addr_Set{&"null",&java.lang.StringBuffer:toString(...)}
                  */
   677          return textToHTML(text, false);
   678      }
   679      
   680      /**
   681       * Converts a text string to XML entities.
   682       *
   683       * @param text The string to convert.
   684       * @author Erik C. Thauvin
   685       * @return The converted string.
   686       */
   687      public static final String textToXML(String text) {
                 /* 
    P/P           *  Method: String textToXML(String)
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuffer:toString(...)._tainted)
                  *    return_value == One-of{&"null", &java.lang.StringBuffer:toString(...)}
                  *    return_value in Addr_Set{&"null",&java.lang.StringBuffer:toString(...)}
                  */
   688          return textToHTML(text, true);
   689      }
   690      
   691      /**
   692       * Converts a text string to HTML or XML entities.
   693       * @param text The string to convert.
   694       * @return The converted string.
   695       */
   696      public static final String textToCDATA(String text) {
                 /* 
    P/P           *  Method: String textToCDATA(String)
                  * 
                  *  Postconditions:
                  *    init'ed(java.lang.StringBuffer:toString(...)._tainted)
                  *    return_value in Addr_Set{&java.lang.StringBuffer:toString(...),&"null"}
                  * 
                  *  Test Vectors:
                  *    text: Inverse{null}, Addr_Set{null}
                  */
   697          if (text == null) return "null";
   698          final StringBuffer html = new StringBuffer();
   699          
   700          // Loop thru each characters of the text
   701          for (int i = 0; i < text.length(); i++) {
   702              // Convert character to HTML/XML
   703              html.append(charToCDATA(text.charAt(i)));
   704          }
   705          
   706          // Return HTML/XML string
   707          return html.toString();
   708      }
   709      
   710      /**
   711       * Converts a character to CDATA character.
   712       * @param ch The character to convert.
   713       * @return The converted string.
   714       */
   715      public static final String charToCDATA(char ch) {
   716          int c;
   717          
                 /* 
    P/P           *  Method: String charToCDATA(char)
                  * 
                  *  Postconditions:
                  *    java.lang.String:valueOf(...)._tainted == 0
                  *    java.lang.StringBuilder:toString(...)._tainted == 0
                  *    return_value in Addr_Set{&java.lang.String:valueOf(...),&java.lang.StringBuilder:toString(...)}
                  * 
                  *  Test Vectors:
                  *    ch: {0..127}, {128..216-1}
                  */
   718          if (ch >= 128) {
   719              c = ch;
   720              
   721              return ("&#" + c + ';');
   722          }
   723          
   724          // No conversion
   725          else {
   726              // Return character as string
   727              return (String.valueOf(ch));
   728          }
   729      }
   730      
   731  }








SofCheck Inspector Build Version : 2.18479
OldUtilities.java 2009-Jan-02 14:25:10
OldUtilities.class 2009-Sep-04 03:12:45