1 /*
2 Copyright 2008 Ernest Micklei @ PhilemonWorks.com
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not 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.
15
16 */
17 package com.philemonworks.selfdiagnose;
18
19 import org.xml.sax.Attributes;
20 /**
21 * PatternMatchingTask is an abstract class that provides the functionality
22 * of matching a String value against a pattern (regular expression).
23 *
24 * @author ernestmicklei
25 */
26 public abstract class PatternMatchingTask extends DiagnosticTask {
27 protected static final String PARAMETER_PATTERN = "pattern";
28 protected String pattern;
29
30 /*
31 * (non-Javadoc)
32 *
33 * @see com.philemonworks.selfdiagnose.DiagnosticTask#initializeFromAttributes(Attributes)
34 */
35 public void initializeFromAttributes(Attributes attributes) {
36 // store variable if specified
37 super.initializeFromAttributes(attributes);
38 // optional
39 this.setPattern(attributes.getValue(PARAMETER_PATTERN));
40 }
41 /**
42 * @return
43 */
44 public String getPattern() {
45 return pattern;
46 }
47 /**
48 * @param string
49 */
50 public void setPattern(String string) {
51 pattern = string;
52 }
53 protected void checkValueAgainstPattern(DiagnosticTaskResult result, String receiver, String accessKind, String propertyName, Object value) {
54 String regex = this.getPattern();
55 String stringValue = "";
56 if (!(value instanceof String)) {
57 stringValue = String.valueOf(value);
58 } else {
59 stringValue = (String) value;
60 }
61 if (regex != null) {
62 // test against given pattern but first make sure it is a String
63 if (stringValue.matches(regex))
64 result.setPassedMessage(DiagnoseUtil.format(
65 "{0} {1} [ {2} = {3} ] matches [{4}]",
66 receiver,accessKind,propertyName,stringValue,regex));
67 else
68 result.setFailedMessage(DiagnoseUtil.format(
69 "{0} {1} [{2}] with value [{3}] does not match with [{4}]",
70 receiver,accessKind,propertyName,stringValue,regex));
71 } else {
72 result.setPassedMessage(DiagnoseUtil.format(
73 "{0} {1} [ {2} = {3} ]", receiver, accessKind, propertyName, stringValue));
74 }
75 }
76 }