You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@velocity.apache.org by Christoph Reck <Ch...@dlr.de> on 2000/12/19 15:59:28 UTC
EncodeXXX context tools [was Re: Rendering Velocity Templates with
Texen]
"Geir Magnusson Jr." wrote:
>
> Christoph Reck wrote:
> >
> > Yep, it does not work with Vel.
> > It does with WM (round instead of curlies).
> >
> > Well, this seems to be a devlish candidate for the parser tests...
> >
> > #set $D = "$"
> > is \$D == ${D}D OK?
>
> If you can type it, Vel should parse it! That's the rule. :)
Well it currently throuws a TokenMgrError: Lexical error at line 1,
column 2. Encountered: <EOF> after : "".
I saw you posted that you'll fix it.
>
> Hey! Where are your ( and ) in your #set() ? Don't fill your logs with
> deprecation messages! ;->
Well; I've not yet moved to Vel, due to shortcomings/bugs...
Has the #set($foo = $somethingReturningNull) been fixed to clear/remove
foo? Shall we allow #set($hashtable.KEY = "value") Shall I provide the
patches? No votes to my proposals yet...
>
> > :P Christoph
> >
> > P.S. I have a ContextTool with formEncode, formDecode, encodeMarkup,
> > and URLEncode. So I can do: #set $D = $Context.formDecode("%24")
> > :)
>
> That would be cool to have. Wanna contribute it?
Code is below, could/should be added to the VelocityFormatter.
>
> (The parser will be fixed though :)
Good
>[snip]
Some other methods are also included which go in the line of the
alternator...
--------------------------- cut here --------------------------
/**
* Translates a string into <code>x-www-form-urlencoded</code> format.
* This method is just a wrapper to java.net.URLEncoder.encode().
*
* @param str The string to encode.
* @return The URL-encoded string.
* @see java.net.URLEncoder
*/
public static String URLEncode(String str)
{
if (str == null)
return null;
return URLEncoder.encode(str);
}
/**
* Encode the characters <, >, " and & to
* &lt;, &gt;, &quot, &amp; respectively.
* <code><input type="text" value="$formater.encodeMarkup($anyText)"></code>
*
* @param text The string to encode.
* @return The HTML encoded string.
*/
public static String encodeMarkup(String text)
{
char[] array = text.toCharArray();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < array.length; i++) {
switch (array[i]) {
case '<':
buffer.append("<");
break;
case'>':
buffer.append(">");
break;
case '&':
buffer.append("&");
break;
case '"':
buffer.append(""");
break;
default:
buffer.append(array[i]);
break;
}
}
return buffer.toString();
}
/**
* Encode space to + and any non alphanumeric character to %XX.
* Taken from Apache Cocoon XSPUtil.
*
* @param text The string to encode.
* @return The form encoded string.
*/
public static String formEncode(String text) throws Exception
{
StringBuffer buffer = new StringBuffer();
char[] c = text.toCharArray();
for (int i = 0; i < c.length; i++)
{
if (isAlphaNumeric(c[i]))
{
buffer.append(c[i]);
}
else if (c[i] == ' ')
{
buffer.append('+');
}
else
{
buffer.append('%');
String hex = Integer.toHexString((byte) c[i]).toUpperCase();
if (hex.length() < 2)
buffer.append('0');
buffer.append(hex);
}
}
return buffer.toString();
}
/**
* Decode space from + and %XX to its character from.
* Taken from Apache Cocoon XSPUtil.
*
* @param text The string to decode.
* @return The decoded string.
*/
public static String formDecode(String s) throws Exception
{
StringBuffer sb = new StringBuffer();
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
switch (c)
{
case '+':
sb.append(' ');
break;
case '%':
try
{
sb.append((char)Integer.parseInt(
s.substring(i+1,i+3),16));
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException();
}
i += 2;
break;
default:
sb.append(c);
}
}
// Undo conversion to external encoding
String result = sb.toString();
byte[] inputBytes = result.getBytes("8859_1");
return new String(inputBytes);
}
/**
* Convenience function to check for alphanumeric characters.
* Taken from Apache Cocoon XSPUtil.
*
* @param c The character to check.
* @return true if it is [_A-Za-z0-9].
*/
public static boolean isAlphaNumeric(char c)
{
return c == '_' ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
}
/**
* Encodes any non alphanumeric character from a string to make
* it usable as a form variable. Any non alphanumeric is deleted
* from the string and the following character is uppercased.
* A following second non alphanumerics is changed to a '_'.
* A string starting with a numeric is prefixed with a '_'. <p>
* Example <code>1abc.def*.ghI.JKL</code> gets converted to
* <code>_1abcDef_GhI_JKL</code>.
*
* @param text String to encode.
* @return Filtered string.
*/
public static String encodeToName(String text)
{
StringBuffer buffer = new StringBuffer( text.length() );
// ensure the string starts with and alpha character
char c = text.charAt(0);
if ( (c >= '0') && (c <= '9') )
buffer.append('_');
boolean makeUppercase = false;
for (int i = 0; i < text.length(); ++i)
{
c = text.charAt(i);
if (isAlphaNumeric(c))
{
if (makeUppercase)
buffer.append( text.substring(i, i+1).toUpperCase() );
else
buffer.append(c);
makeUppercase = (c < 'A') || (c > 'Z');
}
else
{
if (makeUppercase)
buffer.append('_');
// else deleted
makeUppercase = true;
}
}
return buffer.toString();
}
/**
* Convenience function to create an <code>java.lang.Vector</code>
* within a template.
*
* @param size
* @return An empty Vector.
* @see java.lang.Vector
*/
public static Vector newVector(int size)
{
return new Vector(size);
}
/**
* Convenience function to create an <code>java.lang.Hashtable</code>
* within a template.
*
* @param size The default hashsize (avoids the original default of 101).
* @return An empty Hashtable.
* @see java.lang.Hashtable
*/
public static Hashtable newHashtable(int size)
{
return new Hashtable(size);
}
/**
* Convenience function to create an array within a template.<br>
* This can be used as a for-loop replacement:<code>
* #foreach ($index in $formatter.newArray(10))
* ## do something N times or use $index
* #end</code>
*
* @param size
* @return An object array contining the numbers 0 till (size-1).
*/
public static Object newArray(int size)
{
Object[] array = new Object[size];
for (int i = 0; i < size; ++i)
{
array[i] = new Integer(i);
}
}
/**
* Convenience function to access an element of an array
*
* @param index
* @param array
* @return Element at the specified array index.
*/
public static Object getElement(int index, Object[] array)
{
return array[index];
}
/**
* Convenience function sort the elements of an array.
* Needs JDK 1.2.
*
* @param array
* @return The sorted array.
*/
public static Object[] sort(Object[] array)
{
if ((array == null) || (array.length == 0))
return array;
Object[] sorted = new Object[array.length];
System.arraycopy(array, 0, sorted, 0, array.length);
Arrays.sort(sorted);
return sorted;
}
--------------------------- cut here --------------------------
:) Christoph