root/trunk/src/java/org/jcoderz/commons/logging/StringEscapeFormat.java

Revision 1011, 6.7 kB (checked in by amandel, 4 years ago)

Aligned svn keyword settings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 *
4 * Copyright 2006, The jCoderZ.org Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 *    * Redistributions of source code must retain the above copyright
11 *      notice, this list of conditions and the following disclaimer.
12 *    * Redistributions in binary form must reproduce the above
13 *      copyright notice, this list of conditions and the following
14 *      disclaimer in the documentation and/or other materials
15 *      provided with the distribution.
16 *    * Neither the name of the jCoderZ.org Project nor the names of
17 *      its contributors may be used to endorse or promote products
18 *      derived from this software without specific prior written
19 *      permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
31 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33package org.jcoderz.commons.logging;
34
35import java.text.FieldPosition;
36import java.text.Format;
37import java.text.ParsePosition;
38
39import org.jcoderz.commons.util.Assert;
40
41
42/**
43 * This formatter is used to escape chars in the source string with a
44 * configured escape char.The default escape char is '\'.
45 *
46 */
47public class StringEscapeFormat
48      extends Format
49{
50   static final char ESCAPE_CHAR = '\\';
51
52   private static final long serialVersionUID = 3257567291389851442L;
53
54   private final char mEscapeChar;
55   private final String mCharsToEscape;
56
57   /**
58    * Creates an instance of this, which will use the default escape char
59    * {@linkplain #ESCAPE_CHAR}.
60    *
61    * @param charsToEscape the characters which will be escaped by
62    * {@linkplain #ESCAPE_CHAR}.
63    */
64   public StringEscapeFormat (final String charsToEscape)
65   {
66      this(charsToEscape, ESCAPE_CHAR);
67   }
68
69   /**
70    * Creates an instance of this and sets the supplied escape char.
71    *
72    * @param charsToEscape The characters which will be escaped by
73    * <code>escapeChar</code>.
74    * @param escapeChar The char by which to escape <code>charToEscape</code>.
75    * This must not be included in <code>charsToEscape</code> and must not be 0.
76    *
77    * @throws IllegalArgumentException if <code>escapeChar</code> is included
78    * within <code>charsToEscape</code> or is <code>0</code>.
79    */
80   public StringEscapeFormat (
81         final String charsToEscape,
82         final char escapeChar)
83   {
84      super();
85      Assert.notNull("charsToEscape", charsToEscape);
86      mEscapeChar = escapeChar;
87      mCharsToEscape = charsToEscape;
88      if (escapeChar == 0)
89      {
90         throw new IllegalArgumentException(
91               "The escape character must not be 0");
92      }
93      if ((charsToEscape != null) && (charsToEscape.indexOf(escapeChar) >= 0))
94      {
95         throw new IllegalArgumentException(
96            "The escape character must not be one of the characters to escape");
97      }
98   }
99
100   /**
101    * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition)
102    *
103    * Parses the source string. All characters configured as characters to
104    * escape are considered as delimiters (thus parsing is stopped at one of
105    * those) if they are not escaped with the configured character.
106    * A new string is created from this substring with all escape chars before
107    * an char to escape removed. Escape chars not being followed by a character
108    * to escape are not removed for the result string.
109    *
110    * @param source The string to parse.
111    * @param pos the position within <code>source</code>.
112    *
113    * @return the String being parsed from <code>source</code> with escape
114    *       chars removed.
115    */
116   public Object parseObject (String source, ParsePosition pos)
117   {
118      final int sourceLen = source.length();
119      final StringBuffer rc = new StringBuffer();
120      final int offs = pos.getIndex();
121
122      int fromIndex = offs;
123      boolean escaped = false;
124      boolean delimiterFound = false;
125      int index;
126      for (index = offs; index < sourceLen && ! delimiterFound; ++index)
127      {
128         final char c = source.charAt(index);
129
130         if (mCharsToEscape.indexOf(c) >= 0)
131         {
132            if (escaped)
133            {
134               if (fromIndex != index - 1)
135               {
136                  // skip over escape char
137                  rc.append(source.substring(fromIndex, index - 1));
138               }
139               fromIndex = index;
140            }
141            else
142            {
143               delimiterFound = true;
144               index--;
145            }
146            escaped = false;
147         }
148         else
149         {
150            escaped = (c == mEscapeChar);
151         }
152      }
153      if (fromIndex < index)
154      {
155         rc.append(source.substring(fromIndex, index));
156      }
157      if (index > offs)
158      {
159         pos.setIndex(index);
160      }
161      return rc.toString();
162   }
163
164   /**
165    * Formats the supplied object by calling the object's toString() method
166    * and escaping the configured chars of this string with the configured
167    * escape char.
168    * @see Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
169    *
170    * @param obj the object to format.
171    * @param toAppendTo the StringBuffer where to append to the formatted
172    * string.
173    * @param pos the field position.
174    *
175    * @return StringBuffer where the formatted Object has been appended to.
176    */
177   public StringBuffer format (Object obj, StringBuffer toAppendTo,
178         FieldPosition pos)
179   {
180      final String objString = String.valueOf(obj);
181      int fromIndex = 0;
182      final int len = objString.length();
183      for (int i = 0; i < len; ++i)
184      {
185         final char currentChar = objString.charAt(i);
186         if (mCharsToEscape.indexOf(currentChar) >= 0)
187         {
188            if (fromIndex < i)
189            {
190               toAppendTo.append(objString.substring(fromIndex, i));
191               fromIndex = i;
192            }
193            toAppendTo.append(mEscapeChar);
194         }
195      }
196      if (fromIndex == 0)
197      {
198         toAppendTo.append(objString);
199      }
200      else
201      {
202         toAppendTo.append(objString.substring(fromIndex));
203      }
204      return toAppendTo;
205   }
206}
Note: See TracBrowser for help on using the browser.