KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > format > RegexHandler


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.wcf.format;
14
15 import java.util.List JavaDoc;
16
17 import org.apache.log4j.Logger;
18 import org.apache.regexp.RE;
19 import org.apache.regexp.RESyntaxException;
20
21 import com.tonbeller.wcf.utils.SoftException;
22
23
24 /**
25  * validates string input via regular expression
26  */

27 public class RegexHandler extends FormatHandlerSupport {
28     private static Logger logger = Logger.getLogger(RegexHandler.class);
29   /**
30    * returns the unchanged string value of o.
31    */

32   public String JavaDoc format(Object JavaDoc o, String JavaDoc userPattern) {
33     return String.valueOf(o);
34   }
35
36   /**
37    * throws a FormatException if s does not match the regex
38    * @throws FormatException
39    */

40   public Object JavaDoc parse(String JavaDoc s, String JavaDoc userPattern) throws FormatException {
41     try {
42       String JavaDoc regex = super.findPattern(userPattern);
43       RE re = new RE(regex);
44       if (!re.match(s)) {
45         throw new FormatException(getErrorMessage(s));
46       }
47       return s;
48     } catch (RESyntaxException e) {
49             logger.error("exception caught", e);
50       throw new SoftException(e);
51     }
52   }
53
54   public boolean canHandle(Object JavaDoc value) {
55     return false;
56   }
57
58   public Object JavaDoc toNativeArray(List JavaDoc list) {
59     String JavaDoc[] array = new String JavaDoc[list.size()];
60     for (int i = 0; i < array.length; i++)
61       array[i] = (String JavaDoc)list.get(i);
62     return array;
63   }
64
65
66   public Object JavaDoc[] toObjectArray(Object JavaDoc value) {
67     if (value instanceof String JavaDoc)
68       return new String JavaDoc[] {(String JavaDoc) value };
69     return (String JavaDoc[]) value;
70   }
71   
72 }
Popular Tags