View | Details | Raw Unified | Return to bug 183055 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/core/tests/internal/databinding/BindingMessagesTest.java (-2 / +3 lines)
Lines 12-17 Link Here
12
 *
12
 *
13
 * Contributors:
13
 * Contributors:
14
 *     IBM Corporation - initial API and implementation
14
 *     IBM Corporation - initial API and implementation
15
 *     Ovidio Mallo - bug 183055
15
 ******************************************************************************/
16
 ******************************************************************************/
16
17
17
/**
18
/**
Lines 21-33 Link Here
21
public class BindingMessagesTest extends TestCase {
22
public class BindingMessagesTest extends TestCase {
22
	public void testFormatString() throws Exception {
23
	public void testFormatString() throws Exception {
23
		String key = "Validate_NumberOutOfRangeError";
24
		String key = "Validate_NumberOutOfRangeError";
24
		String result = BindingMessages.formatString(key, new Object[] {"1", "2"});
25
		String result = BindingMessages.getFormattedString(key, new Object[] {"1", "2"});
25
		assertFalse("key should not be returned", key.equals(result));
26
		assertFalse("key should not be returned", key.equals(result));
26
	}
27
	}
27
	
28
	
28
	public void testFormatStringForKeyNotFound() throws Exception {
29
	public void testFormatStringForKeyNotFound() throws Exception {
29
		String key = "key_that_does_not_exist";
30
		String key = "key_that_does_not_exist";
30
		String result = BindingMessages.formatString(key, null);
31
		String result = BindingMessages.getFormattedString(key, null);
31
		assertTrue(key.equals(result));
32
		assertTrue(key.equals(result));
32
	}
33
	}
33
}
34
}
(-)src/org/eclipse/core/internal/databinding/conversion/StringToNumberParser.java (-4 / +22 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Ovidio Mallo - bug 183055
10
 *******************************************************************************/
11
 *******************************************************************************/
11
12
12
package org.eclipse.core.internal.databinding.conversion;
13
package org.eclipse.core.internal.databinding.conversion;
Lines 115-126 Link Here
115
				.getErrorIndex() : position.getIndex();
116
				.getErrorIndex() : position.getIndex();
116
117
117
		if (errorIndex < value.length()) {
118
		if (errorIndex < value.length()) {
118
			return BindingMessages.formatString(
119
			return BindingMessages.getFormattedString(
119
					BindingMessages.VALIDATE_NUMBER_PARSE_ERROR, new Object[] {
120
					BindingMessages.VALIDATE_NUMBER_PARSE_ERROR, new Object[] {
120
							value, new Integer(errorIndex + 1),
121
							value, new Integer(errorIndex + 1),
121
							new Character(value.charAt(errorIndex)) });
122
							new Character(value.charAt(errorIndex)) });
122
		}
123
		}
123
		return BindingMessages.formatString(
124
		return BindingMessages.getFormattedString(
124
				BindingMessages.VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER,
125
				BindingMessages.VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER,
125
				new Object[] { value, new Integer(errorIndex + 1) });
126
				new Object[] { value, new Integer(errorIndex + 1) });
126
	}
127
	}
Lines 136-141 Link Here
136
	 */
137
	 */
137
	public static String createOutOfRangeMessage(Number minValue,
138
	public static String createOutOfRangeMessage(Number minValue,
138
			Number maxValue, NumberFormat numberFormat) {
139
			Number maxValue, NumberFormat numberFormat) {
140
		return createOutOfRangeMessage(BindingMessages
141
				.getString(BindingMessages.VALIDATE_NUMBER_OUT_OF_RANGE_ERROR),
142
				minValue, maxValue, numberFormat);
143
	}
144
145
	/**
146
	 * Formats an appropriate message for an out of range error.
147
	 * 
148
	 * @param message
149
	 * @param minValue
150
	 * @param maxValue
151
	 * @param numberFormat
152
	 *            when accessed method synchronizes on instance
153
	 * @return message
154
	 */
155
	public static String createOutOfRangeMessage(String message,
156
			Number minValue, Number maxValue, NumberFormat numberFormat) {
139
		String min = null;
157
		String min = null;
140
		String max = null;
158
		String max = null;
141
159
Lines 144-151 Link Here
144
			max = numberFormat.format(maxValue);
162
			max = numberFormat.format(maxValue);
145
		}
163
		}
146
164
147
		return BindingMessages.formatString(
165
		return BindingMessages
148
				"Validate_NumberOutOfRangeError", new Object[] { min, max }); //$NON-NLS-1$
166
				.formatMessage(message, new Object[] { min, max });
149
	}
167
	}
150
168
151
	/**
169
	/**
(-)src/org/eclipse/core/internal/databinding/conversion/StringToBooleanPrimitiveConverter.java (-4 / +35 lines)
Lines 9-14 Link Here
9
 * Contributors:
9
 * Contributors:
10
 *     db4objects - Initial API and implementation
10
 *     db4objects - Initial API and implementation
11
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
11
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
12
 *     Ovidio Mallo - bug 183055
12
 */
13
 */
13
package org.eclipse.core.internal.databinding.conversion;
14
package org.eclipse.core.internal.databinding.conversion;
14
15
Lines 24-42 Link Here
24
 * StringToBooleanPrimitiveConverter.
25
 * StringToBooleanPrimitiveConverter.
25
 */
26
 */
26
public class StringToBooleanPrimitiveConverter implements IConverter {
27
public class StringToBooleanPrimitiveConverter implements IConverter {
27
	private static final String[] trueValues;
28
28
29
	private static final String[] falseValues;
29
	private static final String[] DEFAULT_TRUE_VALUES;
30
	private static final String[] DEFAULT_FALSE_VALUES;
30
31
31
	static {
32
	static {
32
		String delimiter = BindingMessages.getString(BindingMessages.VALUE_DELIMITER);
33
		String delimiter = BindingMessages.getString(BindingMessages.VALUE_DELIMITER);
33
		String values = BindingMessages.getString(BindingMessages.TRUE_STRING_VALUES);
34
		String values = BindingMessages.getString(BindingMessages.TRUE_STRING_VALUES);
34
		trueValues = valuesToSortedArray(delimiter, values);
35
		DEFAULT_TRUE_VALUES = valuesToSortedArray(delimiter, values);
35
36
36
		values = BindingMessages.getString(BindingMessages.FALSE_STRING_VALUES);
37
		values = BindingMessages.getString(BindingMessages.FALSE_STRING_VALUES);
37
		falseValues = valuesToSortedArray(delimiter, values);
38
		DEFAULT_FALSE_VALUES = valuesToSortedArray(delimiter, values);
38
	}
39
	}
39
40
41
	private String[] trueValues = DEFAULT_TRUE_VALUES;
42
	private String[] falseValues = DEFAULT_FALSE_VALUES;
43
40
	/**
44
	/**
41
	 * Returns a sorted array with all values converted to upper case.
45
	 * Returns a sorted array with all values converted to upper case.
42
	 *
46
	 *
Lines 57-62 Link Here
57
		return array;
61
		return array;
58
	}
62
	}
59
63
64
	/**
65
	 * Sets the string values which are considered to represent a
66
	 * <code>true</code> and <code>false</code> value, respectively.
67
	 * 
68
	 * <p>
69
	 * Note that the capitalization of the provided strings is ignored.
70
	 * </p>
71
	 * 
72
	 * @param trueValues
73
	 *            The set of strings representing a <code>true</code> value.
74
	 * @param falseValues
75
	 *            The set of strings representing a <code>false</code> value.
76
	 */
77
	public final void setSourceStrings(String[] trueValues, String[] falseValues) {
78
		this.trueValues = new String[trueValues.length];
79
		for (int i = 0; i < trueValues.length; i++) {
80
			this.trueValues[i] = trueValues[i].toUpperCase();
81
		}
82
		Arrays.sort(this.trueValues); // for binary search
83
84
		this.falseValues = new String[falseValues.length];
85
		for (int i = 0; i < falseValues.length; i++) {
86
			this.falseValues[i] = falseValues[i].toUpperCase();
87
		}
88
		Arrays.sort(this.falseValues); // for binary search
89
	}
90
60
	/*
91
	/*
61
	 * (non-Javadoc)
92
	 * (non-Javadoc)
62
	 *
93
	 *
(-)src/org/eclipse/core/internal/databinding/conversion/DateConversionSupport.java (+15 lines)
Lines 10-15 Link Here
10
 *     db4objects - Initial API and implementation
10
 *     db4objects - Initial API and implementation
11
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
11
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
12
 *     Matthew Hall - bug 121110
12
 *     Matthew Hall - bug 121110
13
 *     Ovidio Mallo - bug 183055
13
 ******************************************************************************/
14
 ******************************************************************************/
14
package org.eclipse.core.internal.databinding.conversion;
15
package org.eclipse.core.internal.databinding.conversion;
15
16
Lines 52-57 Link Here
52
	};
53
	};
53
54
54
	/**
55
	/**
56
	 * Sets the {@link DateFormat}s to be used for parsing/formatting dates. Any
57
	 * of the supplied formats will be used for {@link #parse(String) parsing} a
58
	 * date from a string while the first format in the array will be used for
59
	 * {@link #format(Date) formatting} a date as a string.
60
	 * 
61
	 * @param formatters
62
	 *            The {@link DateFormat}s to be used for parsing/formatting
63
	 *            dates.
64
	 */
65
	public final void setFormatters(DateFormat[] formatters) {
66
		this.formatters = formatters;
67
	}
68
69
	/**
55
	 * Tries all available formatters to parse the given string according to the
70
	 * Tries all available formatters to parse the given string according to the
56
	 * default locale or as a raw millisecond value and returns the result of the
71
	 * default locale or as a raw millisecond value and returns the result of the
57
	 * first successful run.
72
	 * first successful run.
(-)src/org/eclipse/core/databinding/UpdateStrategy.java (-2 / +3 lines)
Lines 9-14 Link Here
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Matt Carter - bug 180392
10
 *     Matt Carter - bug 180392
11
 *                 - bug 197679 (Character support completed)
11
 *                 - bug 197679 (Character support completed)
12
 *     Ovidio Mallo - bug 183055
12
 *******************************************************************************/
13
 *******************************************************************************/
13
14
14
package org.eclipse.core.databinding;
15
package org.eclipse.core.databinding;
Lines 24-29 Link Here
24
import org.eclipse.core.databinding.util.Policy;
25
import org.eclipse.core.databinding.util.Policy;
25
import org.eclipse.core.internal.databinding.ClassLookupSupport;
26
import org.eclipse.core.internal.databinding.ClassLookupSupport;
26
import org.eclipse.core.internal.databinding.Pair;
27
import org.eclipse.core.internal.databinding.Pair;
28
import org.eclipse.core.internal.databinding.conversion.BooleanToStringConverter;
27
import org.eclipse.core.internal.databinding.conversion.CharacterToStringConverter;
29
import org.eclipse.core.internal.databinding.conversion.CharacterToStringConverter;
28
import org.eclipse.core.internal.databinding.conversion.IdentityConverter;
30
import org.eclipse.core.internal.databinding.conversion.IdentityConverter;
29
import org.eclipse.core.internal.databinding.conversion.IntegerToStringConverter;
31
import org.eclipse.core.internal.databinding.conversion.IntegerToStringConverter;
Lines 35-41 Link Here
35
import org.eclipse.core.internal.databinding.conversion.NumberToIntegerConverter;
37
import org.eclipse.core.internal.databinding.conversion.NumberToIntegerConverter;
36
import org.eclipse.core.internal.databinding.conversion.NumberToLongConverter;
38
import org.eclipse.core.internal.databinding.conversion.NumberToLongConverter;
37
import org.eclipse.core.internal.databinding.conversion.NumberToShortConverter;
39
import org.eclipse.core.internal.databinding.conversion.NumberToShortConverter;
38
import org.eclipse.core.internal.databinding.conversion.ObjectToStringConverter;
39
import org.eclipse.core.internal.databinding.conversion.StringToByteConverter;
40
import org.eclipse.core.internal.databinding.conversion.StringToByteConverter;
40
import org.eclipse.core.internal.databinding.conversion.StringToCharacterConverter;
41
import org.eclipse.core.internal.databinding.conversion.StringToCharacterConverter;
41
import org.eclipse.core.internal.databinding.conversion.StringToShortConverter;
42
import org.eclipse.core.internal.databinding.conversion.StringToShortConverter;
Lines 307-313 Link Here
307
							new Pair(BOOLEAN_CLASS, "java.lang.Boolean"), new IdentityConverter(Boolean.class, Boolean.class)); //$NON-NLS-1$
308
							new Pair(BOOLEAN_CLASS, "java.lang.Boolean"), new IdentityConverter(Boolean.class, Boolean.class)); //$NON-NLS-1$
308
			converterMap
309
			converterMap
309
					.put(
310
					.put(
310
							new Pair(BOOLEAN_CLASS, "java.lang.String"), new ObjectToStringConverter(Boolean.class)); //$NON-NLS-1$
311
							new Pair(BOOLEAN_CLASS, "java.lang.String"), new BooleanToStringConverter(Boolean.class)); //$NON-NLS-1$
311
			converterMap
312
			converterMap
312
					.put(
313
					.put(
313
							new Pair(BOOLEAN_CLASS, "java.lang.Object"), new IdentityConverter(Boolean.class, Object.class)); //$NON-NLS-1$
314
							new Pair(BOOLEAN_CLASS, "java.lang.Object"), new IdentityConverter(Boolean.class, Object.class)); //$NON-NLS-1$
(-)src/org/eclipse/core/internal/databinding/validation/StringToCharacterValidator.java (-3 / +16 lines)
Lines 8-13 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     Matt Carter - initial API and implementation
9
 *     Matt Carter - initial API and implementation
10
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
10
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
11
 *     Ovidio Mallo - bug 183055
11
 ******************************************************************************/
12
 ******************************************************************************/
12
13
13
package org.eclipse.core.internal.databinding.validation;
14
package org.eclipse.core.internal.databinding.validation;
Lines 26-31 Link Here
26
27
27
	private final StringToCharacterConverter converter;
28
	private final StringToCharacterConverter converter;
28
29
30
	private String parseErrorMessage = BindingMessages.getString(BindingMessages.VALIDATE_CHARACTER_HELP);
31
29
	/**
32
	/**
30
	 * @param converter
33
	 * @param converter
31
	 */
34
	 */
Lines 33-38 Link Here
33
		this.converter = converter;
36
		this.converter = converter;
34
	}
37
	}
35
38
39
	/**
40
	 * Sets the validation message to be used in case the source string does not
41
	 * represent a valid character.
42
	 * 
43
	 * @param message
44
	 *            The validation message to be used in case the source string
45
	 *            does not represent a valid character.
46
	 */
47
	public final void setParseErrorMessage(String message) {
48
		this.parseErrorMessage  = message;
49
	}
50
36
	/*
51
	/*
37
	 * (non-Javadoc)
52
	 * (non-Javadoc)
38
	 *
53
	 *
Lines 44-53 Link Here
44
		} catch (IllegalArgumentException e) {
59
		} catch (IllegalArgumentException e) {
45
			// The StringToCharacterConverter throws an IllegalArgumentException
60
			// The StringToCharacterConverter throws an IllegalArgumentException
46
			// if it cannot convert.
61
			// if it cannot convert.
47
			return ValidationStatus.error(BindingMessages
62
			return ValidationStatus.error(parseErrorMessage);
48
					.getString(BindingMessages.VALIDATE_CHARACTER_HELP));
49
		}
63
		}
50
		return Status.OK_STATUS;
64
		return Status.OK_STATUS;
51
	}
65
	}
52
53
}
66
}
(-)src/org/eclipse/core/internal/databinding/validation/StringToDateValidator.java (-8 / +24 lines)
Lines 8-13 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
10
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
11
 *     Ovidio Mallo - bug 183055
11
 *******************************************************************************/
12
 *******************************************************************************/
12
13
13
package org.eclipse.core.internal.databinding.validation;
14
package org.eclipse.core.internal.databinding.validation;
Lines 28-33 Link Here
28
public class StringToDateValidator implements IValidator {
29
public class StringToDateValidator implements IValidator {
29
	private final StringToDateConverter converter;
30
	private final StringToDateConverter converter;
30
31
32
	private String parseErrorMessage = null;
33
31
	/**
34
	/**
32
	 * @param converter
35
	 * @param converter
33
	 */
36
	 */
Lines 35-40 Link Here
35
		this.converter = converter;
38
		this.converter = converter;
36
	}
39
	}
37
40
41
	/**
42
	 * Sets the validation message to be used in case the source string does not
43
	 * represent a valid date.
44
	 * 
45
	 * @param message
46
	 *            The validation message to be used in case the source string
47
	 *            does not represent a valid date.
48
	 */
49
	public final void setParseErrorMessage(String message) {
50
		this.parseErrorMessage = message;
51
	}
52
38
	/*
53
	/*
39
	 * (non-Javadoc)
54
	 * (non-Javadoc)
40
	 *
55
	 *
Lines 47-64 Link Here
47
		Object convertedValue = converter.convert(value);
62
		Object convertedValue = converter.convert(value);
48
		//The StringToDateConverter returns null if it can't parse the date.
63
		//The StringToDateConverter returns null if it can't parse the date.
49
		if (convertedValue == null) {
64
		if (convertedValue == null) {
50
			return ValidationStatus.error(getErrorMessage());
65
			return ValidationStatus.error(getParseErrorMessage());
51
		}
66
		}
52
67
53
		return Status.OK_STATUS;
68
		return Status.OK_STATUS;
54
	}
69
	}
55
70
56
	/*
71
	private String getParseErrorMessage() {
57
	 * (non-Javadoc)
72
		if (parseErrorMessage != null) {
58
	 *
73
			return parseErrorMessage;
59
	 * @see org.eclipse.core.internal.databinding.validation.WrappedConverterValidator#getErrorMessage()
74
		}
60
	 */
75
61
	protected String getErrorMessage() {
62
		Date sampleDate = new Date();
76
		Date sampleDate = new Date();
63
77
64
		// FIXME We need to use the information from the
78
		// FIXME We need to use the information from the
Lines 73-79 Link Here
73
		samples.append('\'');
87
		samples.append('\'');
74
		samples.append(util.format(sampleDate, 0));
88
		samples.append(util.format(sampleDate, 0));
75
		samples.append('\'');
89
		samples.append('\'');
76
		return BindingMessages.getString(BindingMessages.EXAMPLES) + ": " + samples + ",..."; //$NON-NLS-1$//$NON-NLS-2$
90
		parseErrorMessage = BindingMessages.getString(BindingMessages.EXAMPLES) + ": " + samples + ",..."; //$NON-NLS-1$//$NON-NLS-2$
91
92
		return parseErrorMessage;
77
	}
93
	}
78
94
79
	private static class FormatUtil extends DateConversionSupport {
95
	private static class FormatUtil extends DateConversionSupport {
(-)src/org/eclipse/core/internal/databinding/validation/AbstractStringToNumberValidator.java (-9 / +56 lines)
Lines 7-18 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Ovidio Mallo - bug 183055
10
 ******************************************************************************/
11
 ******************************************************************************/
11
12
12
package org.eclipse.core.internal.databinding.validation;
13
package org.eclipse.core.internal.databinding.validation;
13
14
15
import java.text.ParsePosition;
16
14
import org.eclipse.core.databinding.validation.IValidator;
17
import org.eclipse.core.databinding.validation.IValidator;
15
import org.eclipse.core.databinding.validation.ValidationStatus;
18
import org.eclipse.core.databinding.validation.ValidationStatus;
19
import org.eclipse.core.internal.databinding.BindingMessages;
16
import org.eclipse.core.internal.databinding.conversion.StringToNumberParser;
20
import org.eclipse.core.internal.databinding.conversion.StringToNumberParser;
17
import org.eclipse.core.internal.databinding.conversion.StringToNumberParser.ParseResult;
21
import org.eclipse.core.internal.databinding.conversion.StringToNumberParser.ParseResult;
18
import org.eclipse.core.runtime.IStatus;
22
import org.eclipse.core.runtime.IStatus;
Lines 31-37 Link Here
31
	private final Number min;
35
	private final Number min;
32
	private final Number max;
36
	private final Number max;
33
37
34
	private String outOfRangeMessage;
38
	private String parseErrorMessage;
39
40
	private String outOfRangeMessage = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_OUT_OF_RANGE_ERROR);
41
	private String formattedOutOfRangeMessage;
35
42
36
	/**
43
	/**
37
	 * Constructs a new instance.
44
	 * Constructs a new instance.
Lines 55-60 Link Here
55
	}
62
	}
56
63
57
	/**
64
	/**
65
	 * Sets the validation message pattern to be used in case the source string
66
	 * does not represent a valid number.
67
	 * 
68
	 * @param message
69
	 *            The validation message pattern to be used in case the source
70
	 *            string does not represent a valid number.
71
	 */
72
	public final void setParseErrorMessage(String message) {
73
		this.parseErrorMessage = message;
74
	}
75
76
	/**
77
	 * Sets the validation message pattern to be used in case the parsed number
78
	 * lies outside the value range supported by the number type associated to
79
	 * this validator.
80
	 * 
81
	 * @param message
82
	 *            The validation message pattern to be used in case the parsed
83
	 *            number lies outside the supported value range. Can be
84
	 *            parameterized by the <code>Integer.MIN_VALUE</code> and
85
	 *            <code>Integer.MAX_VALUE</code> values.
86
	 */
87
	public final void setOutOfRangeMessage(String message) {
88
		this.outOfRangeMessage = message;
89
		this.formattedOutOfRangeMessage = null;
90
	}
91
92
	/**
58
	 * Validates the provided <code>value</code>.  An error status is returned if:
93
	 * Validates the provided <code>value</code>.  An error status is returned if:
59
	 * <ul>
94
	 * <ul>
60
	 * <li>The value cannot be parsed.</li>
95
	 * <li>The value cannot be parsed.</li>
Lines 69-84 Link Here
69
104
70
		if (result.getNumber() != null) {
105
		if (result.getNumber() != null) {
71
			if (!isInRange(result.getNumber())) {
106
			if (!isInRange(result.getNumber())) {
72
				if (outOfRangeMessage == null) {
107
				return ValidationStatus.error(getFormattedOutOfRangeMessage());
73
					outOfRangeMessage = StringToNumberParser
74
							.createOutOfRangeMessage(min, max, converter
75
									.getNumberFormat());
76
				}
77
78
				return ValidationStatus.error(outOfRangeMessage);
79
			}
108
			}
80
		} else if (result.getPosition() != null) {
109
		} else if (result.getPosition() != null) {
81
			String parseErrorMessage = StringToNumberParser.createParseErrorMessage(
110
			String parseErrorMessage = createParseErrorMessage(
82
					(String) value, result.getPosition());
111
					(String) value, result.getPosition());
83
112
84
			return ValidationStatus.error(parseErrorMessage);
113
			return ValidationStatus.error(parseErrorMessage);
Lines 94-97 Link Here
94
	 * @return <code>true</code> if in range
123
	 * @return <code>true</code> if in range
95
	 */
124
	 */
96
	protected abstract boolean isInRange(Number number);
125
	protected abstract boolean isInRange(Number number);
126
127
	private String createParseErrorMessage(String input,
128
			ParsePosition parsePosition) {
129
		if (parseErrorMessage == null) {
130
			return StringToNumberParser.createParseErrorMessage(input,
131
					parsePosition);
132
		}
133
		return parseErrorMessage;
134
	}
135
136
	private String getFormattedOutOfRangeMessage() {
137
		if (formattedOutOfRangeMessage == null) {
138
			formattedOutOfRangeMessage = StringToNumberParser
139
					.createOutOfRangeMessage(outOfRangeMessage, min, max,
140
							converter.getNumberFormat());
141
		}
142
		return formattedOutOfRangeMessage;
143
	}
97
}
144
}
(-)META-INF/MANIFEST.MF (+2 lines)
Lines 8-14 Link Here
8
Bundle-Localization: plugin
8
Bundle-Localization: plugin
9
Export-Package: org.eclipse.core.databinding,
9
Export-Package: org.eclipse.core.databinding,
10
 org.eclipse.core.databinding.conversion;x-internal:=false,
10
 org.eclipse.core.databinding.conversion;x-internal:=false,
11
 org.eclipse.core.databinding.editing,
11
 org.eclipse.core.databinding.validation;x-internal:=false,
12
 org.eclipse.core.databinding.validation;x-internal:=false,
13
 org.eclipse.core.databinding.validation.constraint,
12
 org.eclipse.core.internal.databinding;x-friends:="org.eclipse.core.databinding.beans",
14
 org.eclipse.core.internal.databinding;x-friends:="org.eclipse.core.databinding.beans",
13
 org.eclipse.core.internal.databinding.conversion;x-friends:="org.eclipse.jface.tests.databinding",
15
 org.eclipse.core.internal.databinding.conversion;x-friends:="org.eclipse.jface.tests.databinding",
14
 org.eclipse.core.internal.databinding.validation;x-friends:="org.eclipse.jface.tests.databinding"
16
 org.eclipse.core.internal.databinding.validation;x-friends:="org.eclipse.jface.tests.databinding"
(-)src/org/eclipse/core/internal/databinding/messages.properties (+45 lines)
Lines 43-48 Link Here
43
TrueStringValues=yes,true
43
TrueStringValues=yes,true
44
FalseStringValues=no,false
44
FalseStringValues=no,false
45
45
46
Validate_InvalidBooleanString=The boolean string is invalid.
47
46
Validate_NumberOutOfRangeError=Please enter a value between [{0}] and [{1}] and with a similar format.
48
Validate_NumberOutOfRangeError=Please enter a value between [{0}] and [{1}] and with a similar format.
47
Validate_NumberParseError=Invalid character for value [{0}] at position [{1}] character [{2}].
49
Validate_NumberParseError=Invalid character for value [{0}] at position [{1}] character [{2}].
48
Validate_NumberParseErrorNoCharacter=Missing character for value [{0}] at position [{1}].
50
Validate_NumberParseErrorNoCharacter=Missing character for value [{0}] at position [{1}].
Lines 53-56 Link Here
53
Validate_NoChangeAllowedHelp=Changes are not allowed in this field
55
Validate_NoChangeAllowedHelp=Changes are not allowed in this field
54
Validate_CharacterHelp=Please type a character
56
Validate_CharacterHelp=Please type a character
55
57
58
#CharacterValidator
59
Validate_CharacterNoWhitespace=The character must be no whitespace.
60
Validate_CharacterNoSpace=The character must be no space.
61
Validate_CharacterLetter=The character must be a letter.
62
Validate_CharacterDigit=The character must be a digit.
63
Validate_CharacterLetterOrDigit=The character must be a letter or digit.
64
65
#NonNullValidator
66
Validate_NonNull=The value must not be empty.
67
68
#NonEmptyStringValidator
69
Validate_NonEmptyString=The string must not be empty.
70
71
#StringRegexValidator
72
Validate_NonStringRegex=The string must match the following pattern: {0}.
73
74
#NumberRangeValidator
75
Validate_NumberRangeGreater=The value must be greater than {0}.
76
Validate_NumberRangeGreaterEqual=The value must be greater than or equal to {0}.
77
Validate_NumberRangeLess=The value must be less than {0}.
78
Validate_NumberRangeLessEqual=The value must be less than or equal to {0}.
79
Validate_NumberRangeWithinRange=The value must lie between {0} and {1}.
80
Validate_NumberRangePositive=The value must be positive.
81
Validate_NumberRangeNonNegative=The value must not be negative.
82
83
#DateRangeValidator
84
Validate_DateRangeAfter=The date must be after {0}.
85
Validate_DateRangeAfterEqual=The date must be after or on {0}.
86
Validate_DateRangeBefore=The date must be before {0}.
87
Validate_DateRangeBeforeEqual=The date must be before or on {0}.
88
Validate_DateRangeWithinRange=The date must lie between {0} and {1}.
89
90
#StringLengthValidator
91
Validate_StringLengthMin=The string must have at least {0} characters.
92
Validate_StringLengthMax=The string must not have more than {0} characters.
93
Validate_StringLengthRange=The string must have between {0} and {1} characters.
94
95
#DecimalScaleValidator
96
Validate_DecimalMaxScale=The decimal must not have more than {0} fractional digits.
97
98
#DecimalPrecisionValidator
99
Validate_DecimalMaxPrecision=The decimal must not have more than {0} significant digits.
100
56
Examples=Examples
101
Examples=Examples
(-)src/org/eclipse/core/internal/databinding/BindingMessages.java (-4 / +146 lines)
Lines 8-13 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
10
 *     Tom Schindl<tom.schindl@bestsolution.at> - bugfix for 217940
11
 *     Ovidio Mallo - bug 183055
11
 *******************************************************************************/
12
 *******************************************************************************/
12
package org.eclipse.core.internal.databinding;
13
package org.eclipse.core.internal.databinding;
13
14
Lines 69-74 Link Here
69
	public static final String FALSE_STRING_VALUES = "FalseStringValues"; //$NON-NLS-1$
70
	public static final String FALSE_STRING_VALUES = "FalseStringValues"; //$NON-NLS-1$
70
71
71
	/**
72
	/**
73
	 * Key to be used for a "Validate_InvalidBooleanString" message
74
	 */
75
	public static final String VALIDATE_INVALID_BOOLEAN_STRING = "Validate_InvalidBooleanString"; //$NON-NLS-1$
76
77
	/**
72
	 * Key to be used for a "Validate_NumberOutOfRangeError" message
78
	 * Key to be used for a "Validate_NumberOutOfRangeError" message
73
	 */
79
	 */
74
	public static final String VALIDATE_NUMBER_OUT_OF_RANGE_ERROR = "Validate_NumberOutOfRangeError"; //$NON-NLS-1$
80
	public static final String VALIDATE_NUMBER_OUT_OF_RANGE_ERROR = "Validate_NumberOutOfRangeError"; //$NON-NLS-1$
Lines 99-104 Link Here
99
	public static final String VALIDATE_CHARACTER_HELP = "Validate_CharacterHelp"; //$NON-NLS-1$
105
	public static final String VALIDATE_CHARACTER_HELP = "Validate_CharacterHelp"; //$NON-NLS-1$
100
106
101
	/**
107
	/**
108
	 * Key to be used for a "Validate_CharacterNoWhitespace" message
109
	 */
110
	public static final String VALIDATE_CHARACTER_NO_WHITESPACE = "Validate_CharacterNoWhitespace"; //$NON-NLS-1$
111
112
	/**
113
	 * Key to be used for a "Validate_CharacterNoSpace" message
114
	 */
115
	public static final String VALIDATE_CHARACTER_NO_SPACE = "Validate_CharacterNoSpace"; //$NON-NLS-1$
116
117
	/**
118
	 * Key to be used for a "Validate_CharacterLetter" message
119
	 */
120
	public static final String VALIDATE_CHARACTER_LETTER = "Validate_CharacterLetter"; //$NON-NLS-1$
121
122
	/**
123
	 * Key to be used for a "Validate_CharacterDigit" message
124
	 */
125
	public static final String VALIDATE_CHARACTER_DIGIT = "Validate_CharacterDigit"; //$NON-NLS-1$
126
127
	/**
128
	 * Key to be used for a "Validate_CharacterLetterOrDigit" message
129
	 */
130
	public static final String VALIDATE_CHARACTER_LETTER_OR_DIGIT = "Validate_CharacterLetterOrDigit"; //$NON-NLS-1$
131
132
	/**
102
	 * Key to be used for a "Examples" message
133
	 * Key to be used for a "Examples" message
103
	 */
134
	 */
104
	public static final String EXAMPLES = "Examples"; //$NON-NLS-1$
135
	public static final String EXAMPLES = "Examples"; //$NON-NLS-1$
Lines 109-118 Link Here
109
	public static final String VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER = "Validate_NumberParseErrorNoCharacter"; //$NON-NLS-1$
140
	public static final String VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER = "Validate_NumberParseErrorNoCharacter"; //$NON-NLS-1$
110
141
111
	/**
142
	/**
143
	 * Key to be used for a "Validate_NonNull" message
144
	 */
145
	public static final String VALIDATE_NON_NULL = "Validate_NonNull"; //$NON-NLS-1$
146
147
	/**
148
	 * Key to be used for a "Validate_NonEmptyString" message
149
	 */
150
	public static final String VALIDATE_NON_EMPTY_STRING = "Validate_NonEmptyString"; //$NON-NLS-1$
151
152
	/**
153
	 * Key to be used for a "Validate_NonStringRegex" message
154
	 */
155
	public static final String VALIDATE_STRING_REGEX = "Validate_NonStringRegex"; //$NON-NLS-1$
156
157
	/**
158
	 * Key to be used for a "Validate_NumberRangeGreater" message
159
	 */
160
	public static final String VALIDATE_NUMBER_RANGE_GREATER = "Validate_NumberRangeGreater"; //$NON-NLS-1$
161
162
	/**
163
	 * Key to be used for a "Validate_NumberRangeGreaterEqual" message
164
	 */
165
	public static final String VALIDATE_NUMBER_RANGE_GREATER_EQUAL = "Validate_NumberRangeGreaterEqual"; //$NON-NLS-1$
166
167
	/**
168
	 * Key to be used for a "Validate_NumberRangeLess" message
169
	 */
170
	public static final String VALIDATE_NUMBER_RANGE_LESS = "Validate_NumberRangeLess"; //$NON-NLS-1$
171
172
	/**
173
	 * Key to be used for a "Validate_NumberRangeLessEqual" message
174
	 */
175
	public static final String VALIDATE_NUMBER_RANGE_LESS_EQUAL = "Validate_NumberRangeLessEqual"; //$NON-NLS-1$
176
177
	/**
178
	 * Key to be used for a "Validate_NumberRangeWithinRange" message
179
	 */
180
	public static final String VALIDATE_NUMBER_RANGE_WITHIN_RANGE = "Validate_NumberRangeWithinRange"; //$NON-NLS-1$
181
182
	/**
183
	 * Key to be used for a "Validate_NumberRangePositive" message
184
	 */
185
	public static final String VALIDATE_NUMBER_RANGE_POSITIVE = "Validate_NumberRangePositive"; //$NON-NLS-1$
186
187
	/**
188
	 * Key to be used for a "Validate_NumberRangeNonNegative" message
189
	 */
190
	public static final String VALIDATE_NUMBER_RANGE_NON_NEGATIVE = "Validate_NumberRangeNonNegative"; //$NON-NLS-1$
191
192
	/**
193
	 * Key to be used for a "Validate_DateRangeAfter" message
194
	 */
195
	public static final String VALIDATE_DATE_RANGE_AFTER = "Validate_DateRangeAfter"; //$NON-NLS-1$
196
197
	/**
198
	 * Key to be used for a "Validate_DateRangeAfterEqual" message
199
	 */
200
	public static final String VALIDATE_DATE_RANGE_AFTER_EQUAL = "Validate_DateRangeAfterEqual"; //$NON-NLS-1$
201
202
	/**
203
	 * Key to be used for a "Validate_DateRangeBefore" message
204
	 */
205
	public static final String VALIDATE_DATE_RANGE_BEFORE = "Validate_DateRangeBefore"; //$NON-NLS-1$
206
207
	/**
208
	 * Key to be used for a "Validate_DateRangeBeforeEqual" message
209
	 */
210
	public static final String VALIDATE_DATE_RANGE_BEFORE_EQUAL = "Validate_DateRangeBeforeEqual"; //$NON-NLS-1$
211
212
	/**
213
	 * Key to be used for a "Validate_DateRangeWithinRange" message
214
	 */
215
	public static final String VALIDATE_DATE_RANGE_WITHIN_RANGE = "Validate_DateRangeWithinRange"; //$NON-NLS-1$
216
217
	/**
218
	 * Key to be used for a "Validate_StringLengthMin" message
219
	 */
220
	public static final String VALIDATE_STRING_LENGTH_MIN = "Validate_StringLengthMin"; //$NON-NLS-1$
221
222
	/**
223
	 * Key to be used for a "Validate_StringLengthMax" message
224
	 */
225
	public static final String VALIDATE_STRING_LENGTH_MAX = "Validate_StringLengthMax"; //$NON-NLS-1$
226
227
	/**
228
	 * Key to be used for a "Validate_StringLengthRange" message
229
	 */
230
	public static final String VALIDATE_STRING_LENGTH_RANGE = "Validate_StringLengthRange"; //$NON-NLS-1$
231
232
	/**
233
	 * Key to be used for a "Validate_DecimalMaxScale" message
234
	 */
235
	public static final String VALIDATE_DECIMAL_MAX_SCALE = "Validate_DecimalMaxScale"; //$NON-NLS-1$
236
237
	/**
238
	 * Key to be used for a "Validate_DecimalMaxPrecision" message
239
	 */
240
	public static final String VALIDATE_DECIMAL_MAX_PRECISION = "Validate_DecimalMaxPrecision"; //$NON-NLS-1$
241
242
	/**
112
	 * Returns the resource object with the given key in the resource bundle for
243
	 * Returns the resource object with the given key in the resource bundle for
113
	 * JFace Data Binding. If there isn't any value under the given key, the key
244
	 * JFace Data Binding. If there isn't any value under the given key, the key
114
	 * is returned.
245
	 * is returned.
115
	 *
246
	 * 
116
	 * @param key
247
	 * @param key
117
	 *            the resource name
248
	 *            the resource name
118
	 * @return the string
249
	 * @return the string
Lines 128-143 Link Here
128
	/**
259
	/**
129
	 * Returns a formatted string with the given key in the resource bundle for
260
	 * Returns a formatted string with the given key in the resource bundle for
130
	 * JFace Data Binding.
261
	 * JFace Data Binding.
131
	 *
262
	 * 
132
	 * @param key
263
	 * @param key
133
	 * @param arguments
264
	 * @param arguments
134
	 * @return formatted string, the key if the key is invalid
265
	 * @return formatted string, the key if the key is invalid
135
	 */
266
	 */
136
	public static String formatString(String key, Object[] arguments) {
267
	public static String getFormattedString(String key, Object[] arguments) {
137
		try {
268
		try {
138
			return MessageFormat.format(bundle.getString(key), arguments);
269
			return formatMessage(getString(key), arguments);
139
		} catch (MissingResourceException e) {
270
		} catch (MissingResourceException e) {
140
			return key;
271
			return key;
141
		}
272
		}
142
	}
273
	}
274
275
	/**
276
	 * Formats the given message pattern with the provided arguments.
277
	 * 
278
	 * @param pattern
279
	 * @param arguments
280
	 * @return formatted string
281
	 */
282
	public static String formatMessage(String pattern, Object[] arguments) {
283
		return MessageFormat.format(pattern, arguments);
284
	}
143
}
285
}
(-)src/org/eclipse/core/databinding/editing/StringEditing.java (+172 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.conversion.IConverter;
15
import org.eclipse.core.databinding.validation.constraint.Constraints;
16
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
17
import org.eclipse.core.internal.databinding.conversion.StringStripConverter;
18
import org.eclipse.core.internal.databinding.conversion.StringTrimConverter;
19
20
/**
21
 * @noextend This class is not intended to be subclassed by clients.
22
 * @since 1.3
23
 */
24
public class StringEditing extends Editing {
25
26
	/**
27
	 * Creates a new editing object for booleans.
28
	 * 
29
	 * @param targetConverter
30
	 *            The {@link #setTargetConverter(IConverter) target converter}
31
	 *            to use for editing.
32
	 * 
33
	 * @noreference This constructor is not intended to be referenced by
34
	 *              clients.
35
	 */
36
	protected StringEditing(IConverter targetConverter) {
37
		setTargetConverter(targetConverter);
38
	}
39
40
	/**
41
	 * Creates a new editing object for strings which performs no validation or
42
	 * conversion.
43
	 * 
44
	 * @return The new editing object which performs no validation or
45
	 *         conversion.
46
	 */
47
	public static StringEditing withDefaults() {
48
		return new StringEditing(null);
49
	}
50
51
	/**
52
	 * Creates a new editing object which strips whitespace from both ends of
53
	 * the input string.
54
	 * 
55
	 * @return The new editing object which strips whitespace from both ends of
56
	 *         the input string.
57
	 * 
58
	 * @see Character#isWhitespace(char)
59
	 */
60
	public static StringEditing stripped() {
61
		return new StringEditing(new StringStripConverter(false));
62
	}
63
64
	/**
65
	 * Creates a new editing object which strips whitespace from both ends of
66
	 * the input string. In case stripping the input string results in an empty
67
	 * string, the input string will be converted to <code>null</code>.
68
	 * 
69
	 * @return The new editing object which strips whitespace from both ends of
70
	 *         the input string. Resulting empty strings are converted to
71
	 *         <code>null</code>.
72
	 * 
73
	 * @see Character#isWhitespace(char)
74
	 */
75
	public static StringEditing strippedToNull() {
76
		return new StringEditing(new StringStripConverter(true));
77
	}
78
79
	/**
80
	 * Creates a new editing object which {@link String#trim()}s the input
81
	 * string.
82
	 * 
83
	 * @return The new editing object which trims whitespace from both ends of
84
	 *         the input string.
85
	 * 
86
	 * @see String#trim()
87
	 */
88
	public static StringEditing trimmed() {
89
		return new StringEditing(new StringTrimConverter(false));
90
	}
91
92
	/**
93
	 * Creates a new editing object which {@link String#trim()}s the input
94
	 * string. In case trimming the input string results in an empty string, the
95
	 * input string will be converted to <code>null</code>.
96
	 * 
97
	 * @return The new editing object which trims whitespace from both ends of
98
	 *         the input string. Resulting empty strings are converted to
99
	 *         <code>null</code>.
100
	 * 
101
	 * @see String#trim()
102
	 */
103
	public static StringEditing trimmedToNull() {
104
		return new StringEditing(new StringTrimConverter(true));
105
	}
106
107
	/**
108
	 * Returns the target constraints to apply.
109
	 * 
110
	 * <p>
111
	 * This method provides a typesafe access to the {@link StringConstraints
112
	 * string target constraints} of this editing object and is equivalent to
113
	 * {@code (StringConstraints) targetConstraints()}.
114
	 * </p>
115
	 * 
116
	 * @return The target constraints to apply.
117
	 * 
118
	 * @see #targetConstraints()
119
	 * @see StringConstraints
120
	 */
121
	public StringConstraints targetStringConstraints() {
122
		return (StringConstraints) targetConstraints();
123
	}
124
125
	/**
126
	 * Returns the model constraints to apply.
127
	 * 
128
	 * <p>
129
	 * This method provides a typesafe access to the {@link StringConstraints
130
	 * string model constraints} of this editing object and is equivalent to
131
	 * {@code (StringConstraints) modelConstraints()}.
132
	 * </p>
133
	 * 
134
	 * @return The model constraints to apply.
135
	 * 
136
	 * @see #modelConstraints()
137
	 * @see StringConstraints
138
	 */
139
	public StringConstraints modelStringConstraints() {
140
		return (StringConstraints) modelConstraints();
141
	}
142
143
	/**
144
	 * Returns the before-set model constraints to apply.
145
	 * 
146
	 * <p>
147
	 * This method provides a typesafe access to the {@link StringConstraints
148
	 * string before-set model constraints} of this editing object and is
149
	 * equivalent to {@code (StringConstraints) beforeSetModelConstraints()}.
150
	 * </p>
151
	 * 
152
	 * @return The before-set model constraints to apply.
153
	 * 
154
	 * @see #beforeSetModelConstraints()
155
	 * @see StringConstraints
156
	 */
157
	public StringConstraints beforeSetModelStringConstraints() {
158
		return (StringConstraints) beforeSetModelConstraints();
159
	}
160
161
	protected Constraints createTargetConstraints() {
162
		return new StringConstraints();
163
	}
164
165
	protected Constraints createModelConstraints() {
166
		return new StringConstraints();
167
	}
168
169
	protected Constraints createBeforeSetModelConstraints() {
170
		return new StringConstraints();
171
	}
172
}
(-)src/org/eclipse/core/internal/databinding/validation/DateRangeValidator.java (+243 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.text.MessageFormat;
15
import java.util.Date;
16
17
import org.eclipse.core.databinding.validation.IValidator;
18
import org.eclipse.core.databinding.validation.ValidationStatus;
19
import org.eclipse.core.internal.databinding.BindingMessages;
20
import org.eclipse.core.runtime.IStatus;
21
22
import com.ibm.icu.text.DateFormat;
23
24
/**
25
 * Provides validations for date which must lie within an open/closed range.
26
 * 
27
 * @since 1.3
28
 */
29
public class DateRangeValidator implements IValidator {
30
31
	// The set of constraint types for the lower/upper bound of the date range.
32
	private static final int UNDEFINED = -1;
33
	private static final int AFTER = 0;
34
	private static final int AFTER_EQUAL = 1;
35
	private static final int BEFORE = 2;
36
	private static final int BEFORE_EQUAL = 3;
37
38
	// The default validation messages.
39
	private static final String AFTER_MESSAGE = BindingMessages
40
			.getString(BindingMessages.VALIDATE_DATE_RANGE_AFTER);
41
	private static final String AFTER_EQUAL_MESSAGE = BindingMessages
42
			.getString(BindingMessages.VALIDATE_DATE_RANGE_AFTER_EQUAL);
43
	private static final String BEFORE_MESSAGE = BindingMessages
44
			.getString(BindingMessages.VALIDATE_DATE_RANGE_BEFORE);
45
	private static final String BEFORE_EQUAL_MESSAGE = BindingMessages
46
			.getString(BindingMessages.VALIDATE_DATE_RANGE_BEFORE_EQUAL);
47
	private static final String WITHIN_RANGE_MESSAGE = BindingMessages
48
			.getString(BindingMessages.VALIDATE_DATE_RANGE_WITHIN_RANGE);
49
50
	private final Date min;
51
	private final Date max;
52
	private final int minConstraint;
53
	private final int maxConstraint;
54
	private final String validationMessage;
55
	private String formattedValidationMessage;
56
	private final DateFormat format;
57
58
	/**
59
	 * Single constructor which supports the individual date range types.
60
	 * 
61
	 * @param min
62
	 *            The min date of the range or <code>null</code> in case no
63
	 *            lower bound is defined.
64
	 * @param max
65
	 *            The max date of the range or <code>null</code> in case no
66
	 *            upper bound is defined.
67
	 * @param minConstraint
68
	 *            The type of constraint imposed by the lower bound of the
69
	 *            range.
70
	 * @param maxConstraint
71
	 *            The type of constraint imposed by the upper bound of the
72
	 *            range.
73
	 * @param validationMessage
74
	 *            The validation message pattern to use. Can be parameterized by
75
	 *            the lower and upper bound of the range, if defined.
76
	 * @param format
77
	 *            The date format to use for formatting dates in the validation
78
	 *            message.
79
	 */
80
	private DateRangeValidator(Date min, Date max, int minConstraint,
81
			int maxConstraint, String validationMessage, DateFormat format) {
82
		this.min = min;
83
		this.max = max;
84
		this.minConstraint = minConstraint;
85
		this.maxConstraint = maxConstraint;
86
		this.validationMessage = validationMessage;
87
		this.format = format;
88
	}
89
90
	/**
91
	 * Creates a validator which checks that an input date is after the given
92
	 * date.
93
	 * 
94
	 * @param date
95
	 *            The reference date of the after constraint.
96
	 * @param validationMessage
97
	 *            The validation message pattern to use. Can be parameterized
98
	 *            with the given reference date.
99
	 * @param format
100
	 *            The display format to use for formatting dates in the
101
	 *            validation message.
102
	 * @return The validator instance.
103
	 */
104
	public static DateRangeValidator after(Date date, String validationMessage,
105
			DateFormat format) {
106
		return new DateRangeValidator(date, null, AFTER, UNDEFINED,
107
				defaultIfNull(validationMessage, AFTER_MESSAGE), format);
108
	}
109
110
	/**
111
	 * Creates a validator which checks that an input date is after or on the
112
	 * given date.
113
	 * 
114
	 * @param date
115
	 *            The reference date of the after-equal constraint.
116
	 * @param validationMessage
117
	 *            The validation message pattern to use. Can be parameterized
118
	 *            with the given reference date.
119
	 * @param format
120
	 *            The display format to use for formatting dates in the
121
	 *            validation message.
122
	 * @return The validator instance.
123
	 */
124
	public static DateRangeValidator afterEqual(Date date,
125
			String validationMessage, DateFormat format) {
126
		return new DateRangeValidator(date, null, AFTER_EQUAL, UNDEFINED,
127
				defaultIfNull(validationMessage, AFTER_EQUAL_MESSAGE), format);
128
	}
129
130
	/**
131
	 * Creates a validator which checks that an input date is before the given
132
	 * date.
133
	 * 
134
	 * @param date
135
	 *            The reference date of the before constraint.
136
	 * @param validationMessage
137
	 *            The validation message pattern to use. Can be parameterized
138
	 *            with the given reference date.
139
	 * @param format
140
	 *            The display format to use for formatting dates in the
141
	 *            validation message.
142
	 * @return The validator instance.
143
	 */
144
	public static DateRangeValidator before(Date date,
145
			String validationMessage, DateFormat format) {
146
		return new DateRangeValidator(null, date, UNDEFINED, BEFORE,
147
				defaultIfNull(validationMessage, BEFORE_MESSAGE), format);
148
	}
149
150
	/**
151
	 * Creates a validator which checks that an input date is before or on the
152
	 * given date.
153
	 * 
154
	 * @param date
155
	 *            The reference date of the before-equal constraint.
156
	 * @param validationMessage
157
	 *            The validation message pattern to use. Can be parameterized
158
	 *            with the given reference date.
159
	 * @param format
160
	 *            The display format to use for formatting dates in the
161
	 *            validation message.
162
	 * @return The validator instance.
163
	 */
164
	public static DateRangeValidator beforeEqual(Date date,
165
			String validationMessage, DateFormat format) {
166
		return new DateRangeValidator(null, date, UNDEFINED, BEFORE_EQUAL,
167
				defaultIfNull(validationMessage, BEFORE_EQUAL_MESSAGE), format);
168
	}
169
170
	/**
171
	 * Creates a validator which checks that an input date is within the given
172
	 * range.
173
	 * 
174
	 * @param min
175
	 *            The lower bound of the range (inclusive).
176
	 * @param max
177
	 *            The upper bound of the range (inclusive).
178
	 * @param validationMessage
179
	 *            The validation message pattern to use. Can be parameterized
180
	 *            with the range's lower and upper bound.
181
	 * @param format
182
	 *            The display format to use for formatting dates in the
183
	 *            validation message.
184
	 * @return The validator instance.
185
	 */
186
	public static DateRangeValidator range(Date min, Date max,
187
			String validationMessage, DateFormat format) {
188
		return new DateRangeValidator(min, max, AFTER_EQUAL, BEFORE_EQUAL,
189
				defaultIfNull(validationMessage, WITHIN_RANGE_MESSAGE), format);
190
	}
191
192
	public IStatus validate(Object value) {
193
		if (value != null) {
194
			Date date = (Date) value;
195
			if ((min != null && !fulfillsConstraint(date, min, minConstraint))
196
					|| (max != null && !fulfillsConstraint(date, max,
197
							maxConstraint))) {
198
				return ValidationStatus.error(getFormattedValidationMessage());
199
			}
200
		}
201
		return ValidationStatus.ok();
202
	}
203
204
	private boolean fulfillsConstraint(Date date1, Date date2, int constraint) {
205
		switch (constraint) {
206
		case AFTER:
207
			return date1.after(date2);
208
		case AFTER_EQUAL:
209
			return date1.after(date2) || date1.equals(date2);
210
		case BEFORE:
211
			return date1.before(date2);
212
		case BEFORE_EQUAL:
213
			return date1.before(date2) || date1.equals(date2);
214
		case UNDEFINED:
215
		default:
216
			throw new IllegalArgumentException(
217
					"Unsupported constraint: " + constraint); //$NON-NLS-1$
218
		}
219
	}
220
221
	private synchronized String getFormattedValidationMessage() {
222
		if (formattedValidationMessage == null) {
223
			formattedValidationMessage = MessageFormat.format(
224
					validationMessage, getValidationMessageArguments());
225
		}
226
		return formattedValidationMessage;
227
	}
228
229
	private String[] getValidationMessageArguments() {
230
		synchronized (format) {
231
			if (min == null) {
232
				return new String[] { format.format(max) };
233
			} else if (max == null) {
234
				return new String[] { format.format(min) };
235
			}
236
			return new String[] { format.format(min), format.format(max) };
237
		}
238
	}
239
240
	private static String defaultIfNull(String string, String defaultString) {
241
		return (string != null) ? string : defaultString;
242
	}
243
}
(-)src/org/eclipse/core/internal/databinding/validation/NumberRangeValidator.java (+156 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.text.MessageFormat;
15
16
import org.eclipse.core.databinding.validation.IValidator;
17
import org.eclipse.core.databinding.validation.ValidationStatus;
18
import org.eclipse.core.internal.databinding.BindingMessages;
19
import org.eclipse.core.runtime.IStatus;
20
21
import com.ibm.icu.text.NumberFormat;
22
23
/**
24
 * Provides validations for numbers which must lie within an open/closed range.
25
 * 
26
 * @since 1.3
27
 */
28
public abstract class NumberRangeValidator implements IValidator {
29
30
	// The set of constraint types for the lower/upper bound of the date range.
31
	protected static final int UNDEFINED = -1;
32
	protected static final int GREATER = 0;
33
	protected static final int GREATER_EQUAL = 1;
34
	protected static final int LESS = 2;
35
	protected static final int LESS_EQUAL = 3;
36
37
	// The default validation messages.
38
	protected static final String GREATER_MESSAGE = BindingMessages
39
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_GREATER);
40
	protected static final String GREATER_EQUAL_MESSAGE = BindingMessages
41
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_GREATER_EQUAL);
42
	protected static final String LESS_MESSAGE = BindingMessages
43
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_LESS);
44
	protected static final String LESS_EQUAL_MESSAGE = BindingMessages
45
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_LESS_EQUAL);
46
	protected static final String WITHIN_RANGE_MESSAGE = BindingMessages
47
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_WITHIN_RANGE);
48
	protected static final String POSITIVE_MESSAGE = BindingMessages
49
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_POSITIVE);
50
	protected static final String NON_NEGATIVE_MESSAGE = BindingMessages
51
			.getString(BindingMessages.VALIDATE_NUMBER_RANGE_NON_NEGATIVE);
52
53
	private final Number min;
54
	private final Number max;
55
	private final int minConstraint;
56
	private final int maxConstraint;
57
	private final String validationMessage;
58
	private String formattedValidationMessage;
59
	private final NumberFormat format;
60
61
	/**
62
	 * Single constructor which supports the individual number range types.
63
	 * 
64
	 * @param min
65
	 *            The min number of the range or <code>null</code> in case no
66
	 *            lower bound is defined.
67
	 * @param max
68
	 *            The max number of the range or <code>null</code> in case no
69
	 *            upper bound is defined.
70
	 * @param minConstraint
71
	 *            The type of constraint imposed by the lower bound of the
72
	 *            range.
73
	 * @param maxConstraint
74
	 *            The type of constraint imposed by the upper bound of the
75
	 *            range.
76
	 * @param validationMessage
77
	 *            The validation message pattern to use. Can be parameterized by
78
	 *            the lower and upper bound of the range, if defined.
79
	 * @param format
80
	 *            The integer format to use for formatting numbers in the
81
	 *            validation message.
82
	 */
83
	protected NumberRangeValidator(Number min, Number max, int minConstraint,
84
			int maxConstraint, String validationMessage, NumberFormat format) {
85
		this.min = min;
86
		this.max = max;
87
		this.minConstraint = minConstraint;
88
		this.maxConstraint = maxConstraint;
89
		this.validationMessage = validationMessage;
90
		this.format = format;
91
	}
92
93
	public IStatus validate(Object value) {
94
		if (value != null) {
95
			Number number = (Number) value;
96
			if ((min != null && !fulfillsConstraint(number, min, minConstraint))
97
					|| (max != null && !fulfillsConstraint(number, max,
98
							maxConstraint))) {
99
				return ValidationStatus.error(getFormattedValidationMessage());
100
			}
101
		}
102
		return ValidationStatus.ok();
103
	}
104
105
	private boolean fulfillsConstraint(Number number1, Number number2,
106
			int constraint) {
107
		int compareResult = compare(number1, number2);
108
		switch (constraint) {
109
		case GREATER:
110
			return compareResult > 0;
111
		case GREATER_EQUAL:
112
			return compareResult >= 0;
113
		case LESS:
114
			return compareResult < 0;
115
		case LESS_EQUAL:
116
			return compareResult <= 0;
117
		case UNDEFINED:
118
		default:
119
			throw new IllegalArgumentException(
120
					"Unsupported constraint: " + constraint); //$NON-NLS-1$
121
		}
122
	}
123
124
	/**
125
	 * Comparator method to be implemented by subclasses in order to compare two
126
	 * instances of the concrete number type.
127
	 * 
128
	 * @param number1
129
	 *            The first number to compare.
130
	 * @param number2
131
	 *            The second number to compare.
132
	 * @return A negative number, zero, or a positive number in case the first
133
	 *         number is smaller than, equal to, or greater than the second
134
	 *         number, respectively.
135
	 */
136
	protected abstract int compare(Number number1, Number number2);
137
138
	private synchronized String getFormattedValidationMessage() {
139
		if (formattedValidationMessage == null) {
140
			formattedValidationMessage = MessageFormat.format(
141
					validationMessage, getValidationMessageArguments());
142
		}
143
		return formattedValidationMessage;
144
	}
145
146
	private String[] getValidationMessageArguments() {
147
		synchronized (format) {
148
			if (min == null) {
149
				return new String[] { format.format(max) };
150
			} else if (max == null) {
151
				return new String[] { format.format(min) };
152
			}
153
			return new String[] { format.format(min), format.format(max) };
154
		}
155
	}
156
}
(-)src/org/eclipse/core/databinding/validation/constraint/CharacterConstraints.java (+199 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import org.eclipse.core.internal.databinding.validation.CharacterValidator;
15
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
16
17
/**
18
 * Provides a set of constraints to apply to <code>Character</code>s.
19
 * 
20
 * <p>
21
 * Instances of this class can be used to define a set of constraints to apply
22
 * to characters. In addition, the validation messages to be issued for the
23
 * individual constraints can be configured.
24
 * </p>
25
 * 
26
 * @noextend This class is not intended to be subclassed by clients.
27
 * @since 1.3
28
 */
29
public class CharacterConstraints extends Constraints {
30
31
	private String requiredMessage = null;
32
33
	private String noWhitespaceMessage = null;
34
35
	private String noSpaceMessage = null;
36
37
	private String letterMessage = null;
38
39
	private String digitMessage = null;
40
41
	private String letterOrDigitMessage = null;
42
43
	/**
44
	 * Adds a validator ensuring that the character is not <code>null</code> .
45
	 * Uses the current {@link #requiredMessage(String) validation message}.
46
	 * 
47
	 * @return This constraints instance for method chaining.
48
	 */
49
	public CharacterConstraints required() {
50
		addValidator(new NonNullValidator(requiredMessage));
51
		return this;
52
	}
53
54
	/**
55
	 * Sets the validation message for the {@link #required()} constraint.
56
	 * 
57
	 * @param message
58
	 *            The validation message for the {@link #required()} constraint.
59
	 * @return This constraints instance for method chaining.
60
	 * 
61
	 * @see #required()
62
	 */
63
	public CharacterConstraints requiredMessage(String message) {
64
		this.requiredMessage = message;
65
		return this;
66
	}
67
68
	/**
69
	 * Adds a validator ensuring that the character is no
70
	 * {@link Character#isWhitespace(char) whitespace}. Uses the current
71
	 * {@link #noWhitespaceMessage(String) validation message}.
72
	 * 
73
	 * @return This constraints instance for method chaining.
74
	 */
75
	public CharacterConstraints noWhitespace() {
76
		addValidator(CharacterValidator.noWhitespace(noWhitespaceMessage));
77
		return this;
78
	}
79
80
	/**
81
	 * Sets the validation message for the {@link #noWhitespace()} constraint.
82
	 * 
83
	 * @param message
84
	 *            The validation message for the {@link #noWhitespace()}
85
	 *            constraint.
86
	 * @return This constraints instance for method chaining.
87
	 * 
88
	 * @see #noWhitespace()
89
	 */
90
	public CharacterConstraints noWhitespaceMessage(String message) {
91
		this.noWhitespaceMessage = message;
92
		return this;
93
	}
94
95
	/**
96
	 * Adds a validator ensuring that the character is no
97
	 * {@link Character#isSpaceChar(char) space}. Uses the current
98
	 * {@link #noSpaceMessage(String) validation message}.
99
	 * 
100
	 * @return This constraints instance for method chaining.
101
	 */
102
	public CharacterConstraints noSpace() {
103
		addValidator(CharacterValidator.noSpace(noSpaceMessage));
104
		return this;
105
	}
106
107
	/**
108
	 * Sets the validation message for the {@link #noSpace()} constraint.
109
	 * 
110
	 * @param message
111
	 *            The validation message for the {@link #noSpace()} constraint.
112
	 * @return This constraints instance for method chaining.
113
	 * 
114
	 * @see #noSpace()
115
	 */
116
	public CharacterConstraints noSpaceMessage(String message) {
117
		this.noSpaceMessage = message;
118
		return this;
119
	}
120
121
	/**
122
	 * Adds a validator ensuring that the character is a
123
	 * {@link Character#isLetter(char) letter}. Uses the current
124
	 * {@link #letterMessage(String) validation message}.
125
	 * 
126
	 * @return This constraints instance for method chaining.
127
	 */
128
	public CharacterConstraints letter() {
129
		addValidator(CharacterValidator.letter(letterMessage));
130
		return this;
131
	}
132
133
	/**
134
	 * Sets the validation message for the {@link #letter()} constraint.
135
	 * 
136
	 * @param message
137
	 *            The validation message for the {@link #letter()} constraint.
138
	 * @return This constraints instance for method chaining.
139
	 * 
140
	 * @see #letter()
141
	 */
142
	public CharacterConstraints letterMessage(String message) {
143
		this.letterMessage = message;
144
		return this;
145
	}
146
147
	/**
148
	 * Adds a validator ensuring that the character is a
149
	 * {@link Character#isDigit(char) digit}. Uses the current
150
	 * {@link #digitMessage(String) validation message}.
151
	 * 
152
	 * @return This constraints instance for method chaining.
153
	 */
154
	public CharacterConstraints digit() {
155
		addValidator(CharacterValidator.digit(digitMessage));
156
		return this;
157
	}
158
159
	/**
160
	 * Sets the validation message for the {@link #digit()} constraint.
161
	 * 
162
	 * @param message
163
	 *            The validation message for the {@link #digit()} constraint.
164
	 * @return This constraints instance for method chaining.
165
	 * 
166
	 * @see #digit()
167
	 */
168
	public CharacterConstraints digitMessage(String message) {
169
		this.digitMessage = message;
170
		return this;
171
	}
172
173
	/**
174
	 * Adds a validator ensuring that the character is a
175
	 * {@link Character#isLetterOrDigit(char) letter or digit}. Uses the current
176
	 * {@link #letterOrDigitMessage(String) validation message}.
177
	 * 
178
	 * @return This constraints instance for method chaining.
179
	 */
180
	public CharacterConstraints letterOrDigit() {
181
		addValidator(CharacterValidator.letterOrDigit(letterOrDigitMessage));
182
		return this;
183
	}
184
185
	/**
186
	 * Sets the validation message for the {@link #letterOrDigit()} constraint.
187
	 * 
188
	 * @param message
189
	 *            The validation message for the {@link #letterOrDigit()}
190
	 *            constraint.
191
	 * @return This constraints instance for method chaining.
192
	 * 
193
	 * @see #letterOrDigit()
194
	 */
195
	public CharacterConstraints letterOrDigitMessage(String message) {
196
		this.letterOrDigitMessage = message;
197
		return this;
198
	}
199
}
(-)src/org/eclipse/core/internal/databinding/validation/StringLengthValidator.java (+167 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.text.MessageFormat;
15
16
import org.eclipse.core.databinding.validation.IValidator;
17
import org.eclipse.core.databinding.validation.ValidationStatus;
18
import org.eclipse.core.internal.databinding.BindingMessages;
19
import org.eclipse.core.runtime.IStatus;
20
21
import com.ibm.icu.text.NumberFormat;
22
23
/**
24
 * Provides validations for strings which must have a specified length.
25
 * 
26
 * @since 1.3
27
 */
28
public class StringLengthValidator implements IValidator {
29
30
	// The default validation messages.
31
	private static final String MIN_LENGTH_MESSAGE = BindingMessages
32
			.getString(BindingMessages.VALIDATE_STRING_LENGTH_MIN);
33
	private static final String MAX_LENGTH_MESSAGE = BindingMessages
34
			.getString(BindingMessages.VALIDATE_STRING_LENGTH_MAX);
35
	private static final String LENGTH_RANGE_MESSAGE = BindingMessages
36
			.getString(BindingMessages.VALIDATE_STRING_LENGTH_RANGE);
37
38
	private final Integer minLength;
39
	private final Integer maxLength;
40
	private final String validationMessage;
41
	private String formattedValidationMessage;
42
	private final NumberFormat format;
43
44
	/**
45
	 * Creates a string length validator defining a minimum and/or maximum
46
	 * length for a string.
47
	 * 
48
	 * @param minLength
49
	 *            The minimum length of the string or <code>null</code> in case
50
	 *            no minimum length is defined.
51
	 * @param maxLength
52
	 *            The maximum length of the string or <code>null</code> in case
53
	 *            no maximum length is defined.
54
	 * @param validationMessage
55
	 *            The validation message pattern to use. Can be parameterized by
56
	 *            the lower and upper bound of the range, if defined.
57
	 * @param format
58
	 *            The number format to use for formatting integers (the length
59
	 *            bounds) in the validation message.
60
	 */
61
	private StringLengthValidator(Integer minLength, Integer maxLength,
62
			String validationMessage, NumberFormat format) {
63
		this.minLength = minLength;
64
		this.maxLength = maxLength;
65
		this.validationMessage = validationMessage;
66
		this.format = format;
67
	}
68
69
	/**
70
	 * Creates a validator which checks that an input string has the given
71
	 * minimum length.
72
	 * 
73
	 * @param minLength
74
	 *            The minimum length which the input string must have.
75
	 * @param validationMessage
76
	 *            The validation message pattern to use. Can be parameterized
77
	 *            with the given minimum length.
78
	 * @param format
79
	 *            The display format to use for formatting integers (the minimum
80
	 *            length) in the validation message.
81
	 * @return The validator instance.
82
	 */
83
	public static StringLengthValidator min(int minLength,
84
			String validationMessage, NumberFormat format) {
85
		return new StringLengthValidator(new Integer(minLength), null,
86
				defaultIfNull(validationMessage, MIN_LENGTH_MESSAGE), format);
87
	}
88
89
	/**
90
	 * Creates a validator which checks that an input string has the given
91
	 * maximum length.
92
	 * 
93
	 * @param maxLength
94
	 *            The maximum length which the input string must have.
95
	 * @param validationMessage
96
	 *            The validation message pattern to use. Can be parameterized
97
	 *            with the given maximum length.
98
	 * @param format
99
	 *            The display format to use for formatting integers (the maximum
100
	 *            length) in the validation message.
101
	 * @return The validator instance.
102
	 */
103
	public static StringLengthValidator max(int maxLength,
104
			String validationMessage, NumberFormat format) {
105
		return new StringLengthValidator(null, new Integer(maxLength),
106
				defaultIfNull(validationMessage, MAX_LENGTH_MESSAGE), format);
107
	}
108
109
	/**
110
	 * Creates a validator which checks that the length of an input string lies
111
	 * in the given range.
112
	 * 
113
	 * @param minLength
114
	 *            The minimum length which the input string must have.
115
	 * @param maxLength
116
	 *            The maximum length which the input string must have.
117
	 * @param validationMessage
118
	 *            The validation message pattern to use. Can be parameterized
119
	 *            with the given minimum and maximum lengths.
120
	 * @param format
121
	 *            The display format to use for formatting integers (the
122
	 *            minimum/maximum length) in the validation message.
123
	 * @return The validator instance.
124
	 */
125
	public static StringLengthValidator range(int minLength, int maxLength,
126
			String validationMessage, NumberFormat format) {
127
		return new StringLengthValidator(new Integer(minLength), new Integer(
128
				maxLength), defaultIfNull(validationMessage,
129
				LENGTH_RANGE_MESSAGE), format);
130
	}
131
132
	public IStatus validate(Object value) {
133
		String input = (String) value;
134
		if (input != null) {
135
			int inputLength = input.length();
136
			if ((minLength != null && inputLength < minLength.intValue())
137
					|| maxLength != null && inputLength > maxLength.intValue()) {
138
				return ValidationStatus.error(getFormattedValidationMessage());
139
			}
140
		}
141
		return ValidationStatus.ok();
142
	}
143
144
	private synchronized String getFormattedValidationMessage() {
145
		if (formattedValidationMessage == null) {
146
			formattedValidationMessage = MessageFormat.format(
147
					validationMessage, getValidationMessageArguments());
148
		}
149
		return formattedValidationMessage;
150
	}
151
152
	private String[] getValidationMessageArguments() {
153
		synchronized (format) {
154
			if (minLength == null) {
155
				return new String[] { format.format(maxLength) };
156
			} else if (maxLength == null) {
157
				return new String[] { format.format(minLength) };
158
			}
159
			return new String[] { format.format(minLength),
160
					format.format(maxLength) };
161
		}
162
	}
163
164
	private static String defaultIfNull(String string, String defaultString) {
165
		return (string != null) ? string : defaultString;
166
	}
167
}
(-)src/org/eclipse/core/databinding/validation/constraint/DecimalConstraints.java (+424 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import org.eclipse.core.internal.databinding.validation.DecimalPrecisionValidator;
15
import org.eclipse.core.internal.databinding.validation.DecimalRangeValidator;
16
import org.eclipse.core.internal.databinding.validation.DecimalScaleValidator;
17
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
18
19
import com.ibm.icu.text.NumberFormat;
20
21
/**
22
 * Provides a set of constraints to apply to decimal numbers.
23
 * 
24
 * <p>
25
 * Instances of this class can be used to define a set of constraints to apply
26
 * to decimal numbers. In addition, the validation messages to be issued for the
27
 * individual constraints as well as the way in which model objects are
28
 * formatted in the validation messages can be configured.
29
 * </p>
30
 * 
31
 * <p>
32
 * The decimal types supported by this class are <code>double</code>, and
33
 * <code>float</code>.
34
 * </p>
35
 * 
36
 * @noextend This class is not intended to be subclassed by clients.
37
 * @since 1.3
38
 */
39
public class DecimalConstraints extends Constraints {
40
41
	private NumberFormat decimalFormat = NumberFormat.getNumberInstance();
42
43
	private NumberFormat scaleFormat = NumberFormat.getIntegerInstance();
44
45
	private NumberFormat precisionFormat = NumberFormat.getIntegerInstance();
46
47
	private String requiredMessage = null;
48
49
	private String greaterMessage = null;
50
51
	private String greaterEqualMessage = null;
52
53
	private String lessMessage = null;
54
55
	private String lessEqualMessage = null;
56
57
	private String rangeMessage = null;
58
59
	private String positiveMessage = null;
60
61
	private String nonNegativeMessage = null;
62
63
	private String maxScaleMessage = null;
64
65
	private String maxPrecisionMessage = null;
66
67
	/**
68
	 * Sets the format to use when formatting a decimal to be included in any of
69
	 * the validation messages.
70
	 * 
71
	 * @param format
72
	 *            The format to use for displaying decimals in validation
73
	 *            messages.
74
	 * @return This constraints instance for method chaining.
75
	 */
76
	public DecimalConstraints decimalFormat(NumberFormat format) {
77
		this.decimalFormat = format;
78
		return this;
79
	}
80
81
	/**
82
	 * Adds a validator ensuring that the input decimal is not <code>null</code>
83
	 * . Uses the current {@link #requiredMessage(String) validation message}.
84
	 * 
85
	 * @return This constraints instance for method chaining.
86
	 */
87
	public DecimalConstraints required() {
88
		addValidator(new NonNullValidator(requiredMessage));
89
		return this;
90
	}
91
92
	/**
93
	 * Sets the validation message for the {@link #required()} constraint.
94
	 * 
95
	 * @param message
96
	 *            The validation message for the {@link #required()} constraint.
97
	 * @return This constraints instance for method chaining.
98
	 * 
99
	 * @see #required()
100
	 */
101
	public DecimalConstraints requiredMessage(String message) {
102
		this.requiredMessage = message;
103
		return this;
104
	}
105
106
	/**
107
	 * Adds a validator ensuring that the input decimal is greater than the
108
	 * given number. Uses the current {@link #greaterMessage(String) validation
109
	 * message} and {@link #decimalFormat(NumberFormat) decimal format}.
110
	 * 
111
	 * @param number
112
	 *            The number which the input decimal must be greater than.
113
	 * @return This constraints instance for method chaining.
114
	 */
115
	public DecimalConstraints greater(double number) {
116
		addValidator(DecimalRangeValidator.greater(number, greaterMessage,
117
				decimalFormat));
118
		return this;
119
	}
120
121
	/**
122
	 * Sets the validation message pattern for the {@link #greater(double)}
123
	 * constraint.
124
	 * 
125
	 * @param message
126
	 *            The validation message pattern for the
127
	 *            {@link #greater(double)} constraint. Can be parameterized with
128
	 *            the number ({0}) which the input decimal must be greater than.
129
	 * @return This constraints instance for method chaining.
130
	 * 
131
	 * @see #greater(double)
132
	 */
133
	public DecimalConstraints greaterMessage(String message) {
134
		this.greaterMessage = message;
135
		return this;
136
	}
137
138
	/**
139
	 * Adds a validator ensuring that the input decimal is greater than or equal
140
	 * to the given number. Uses the current
141
	 * {@link #greaterEqualMessage(String) validation message} and
142
	 * {@link #decimalFormat(NumberFormat) decimal format}.
143
	 * 
144
	 * @param number
145
	 *            The number which the input decimal must be greater than or
146
	 *            equal to.
147
	 * @return This constraints instance for method chaining.
148
	 */
149
	public DecimalConstraints greaterEqual(double number) {
150
		addValidator(DecimalRangeValidator.greaterEqual(number,
151
				greaterEqualMessage, decimalFormat));
152
		return this;
153
	}
154
155
	/**
156
	 * Sets the validation message pattern for the {@link #greaterEqual(double)}
157
	 * constraint.
158
	 * 
159
	 * @param message
160
	 *            The validation message pattern for the
161
	 *            {@link #greaterEqual(double)} constraint. Can be parameterized
162
	 *            with the number ({0}) which the input decimal must be greater
163
	 *            than or equal to.
164
	 * @return This constraints instance for method chaining.
165
	 * 
166
	 * @see #greaterEqual(double)
167
	 */
168
	public DecimalConstraints greaterEqualMessage(String message) {
169
		this.greaterEqualMessage = message;
170
		return this;
171
	}
172
173
	/**
174
	 * Adds a validator ensuring that the input decimal is less than the given
175
	 * number. Uses the current {@link #lessMessage(String) validation message}
176
	 * and {@link #decimalFormat(NumberFormat) decimal format}.
177
	 * 
178
	 * @param number
179
	 *            The number which the input decimal must be less than.
180
	 * @return This constraints instance for method chaining.
181
	 */
182
	public DecimalConstraints less(double number) {
183
		addValidator(DecimalRangeValidator.less(number, lessMessage,
184
				decimalFormat));
185
		return this;
186
	}
187
188
	/**
189
	 * Sets the validation message pattern for the {@link #less(double)}
190
	 * constraint.
191
	 * 
192
	 * @param message
193
	 *            The validation message pattern for the {@link #less(double)}
194
	 *            constraint. Can be parameterized with the number ({0}) which
195
	 *            the input decimal must be less than.
196
	 * @return This constraints instance for method chaining.
197
	 * 
198
	 * @see #less(double)
199
	 */
200
	public DecimalConstraints lessMessage(String message) {
201
		this.lessMessage = message;
202
		return this;
203
	}
204
205
	/**
206
	 * Adds a validator ensuring that the input decimal is less than or equal to
207
	 * the given number. Uses the current {@link #lessEqualMessage(String)
208
	 * validation message} and {@link #decimalFormat(NumberFormat) decimal
209
	 * format}.
210
	 * 
211
	 * @param number
212
	 *            The number which the input decimal must be less than or equal
213
	 *            to.
214
	 * @return This constraints instance for method chaining.
215
	 */
216
	public DecimalConstraints lessEqual(double number) {
217
		addValidator(DecimalRangeValidator.greaterEqual(number,
218
				lessEqualMessage, decimalFormat));
219
		return this;
220
	}
221
222
	/**
223
	 * Sets the validation message pattern for the {@link #lessEqual(double)}
224
	 * constraint.
225
	 * 
226
	 * @param message
227
	 *            The validation message pattern for the
228
	 *            {@link #lessEqual(double)} constraint. Can be parameterized
229
	 *            with the number ({0}) which the input decimal must be less
230
	 *            than or equal to.
231
	 * @return This constraints instance for method chaining.
232
	 * 
233
	 * @see #lessEqual(double)
234
	 */
235
	public DecimalConstraints lessEqualMessage(String message) {
236
		this.lessEqualMessage = message;
237
		return this;
238
	}
239
240
	/**
241
	 * Adds a validator ensuring that the input decimal is within the given
242
	 * range. Uses the current {@link #rangeMessage(String) validation message}
243
	 * and {@link #decimalFormat(NumberFormat) decimal format}.
244
	 * 
245
	 * @param min
246
	 *            The lower bound of the range (inclusive).
247
	 * @param max
248
	 *            The upper bound of the range (inclusive).
249
	 * @return This constraints instance for method chaining.
250
	 */
251
	public DecimalConstraints range(double min, double max) {
252
		addValidator(DecimalRangeValidator.range(min, max, rangeMessage,
253
				decimalFormat));
254
		return this;
255
	}
256
257
	/**
258
	 * Sets the validation message pattern for the
259
	 * {@link #range(double, double)} constraint.
260
	 * 
261
	 * @param message
262
	 *            The validation message pattern for the
263
	 *            {@link #range(double, double)} constraint. Can be
264
	 *            parameterized with the min ({0}) and max ({1}) values of the
265
	 *            range in which the input decimal must lie.
266
	 * @return This constraints instance for method chaining.
267
	 * 
268
	 * @see #range(double, double)
269
	 */
270
	public DecimalConstraints rangeMessage(String message) {
271
		this.rangeMessage = message;
272
		return this;
273
	}
274
275
	/**
276
	 * Adds a validator ensuring that the input decimal is positive. Uses the
277
	 * current {@link #positiveMessage(String) validation message}.
278
	 * 
279
	 * @return This constraints instance for method chaining.
280
	 */
281
	public DecimalConstraints positive() {
282
		addValidator(DecimalRangeValidator.positive(positiveMessage,
283
				decimalFormat));
284
		return this;
285
	}
286
287
	/**
288
	 * Sets the validation message for the {@link #positive()} constraint.
289
	 * 
290
	 * @param message
291
	 *            The validation message for the {@link #positive()} constraint.
292
	 * @return This constraints instance for method chaining.
293
	 * 
294
	 * @see #positive()
295
	 */
296
	public DecimalConstraints positiveMessage(String message) {
297
		this.positiveMessage = message;
298
		return this;
299
	}
300
301
	/**
302
	 * Adds a validator ensuring that the input decimal is non-negative. Uses
303
	 * the current {@link #nonNegativeMessage(String) validation message}.
304
	 * 
305
	 * @return This constraints instance for method chaining.
306
	 */
307
	public DecimalConstraints nonNegative() {
308
		addValidator(DecimalRangeValidator.nonNegative(nonNegativeMessage,
309
				decimalFormat));
310
		return this;
311
	}
312
313
	/**
314
	 * Sets the validation message for the {@link #nonNegative()} constraint.
315
	 * 
316
	 * @param message
317
	 *            The validation message for the {@link #nonNegative()}
318
	 *            constraint.
319
	 * @return This constraints instance for method chaining.
320
	 * 
321
	 * @see #nonNegative()
322
	 */
323
	public DecimalConstraints nonNegativeMessage(String message) {
324
		this.nonNegativeMessage = message;
325
		return this;
326
	}
327
328
	/**
329
	 * Sets the format to use when formatting the scale in any of the validation
330
	 * messages stemming from a scale constraint.
331
	 * 
332
	 * @param format
333
	 *            The format to use for displaying the scale in validation
334
	 *            messages stemming from a scale constraint.
335
	 * @return This constraints instance for method chaining.
336
	 * 
337
	 * @see #maxScale(int)
338
	 */
339
	public DecimalConstraints scaleFormat(NumberFormat format) {
340
		this.scaleFormat = format;
341
		return this;
342
	}
343
344
	/**
345
	 * Adds a validator ensuring that the input decimal's scale is not greater
346
	 * than the given one. Uses the current {@link #maxScaleMessage(String)
347
	 * validation message} and {@link #scaleFormat(NumberFormat) scale format}.
348
	 * 
349
	 * @param scale
350
	 *            The maximum scale to enforce on the input decimal.
351
	 * @return This constraints instance for method chaining.
352
	 */
353
	public DecimalConstraints maxScale(int scale) {
354
		addValidator(DecimalScaleValidator.max(scale, maxScaleMessage,
355
				scaleFormat));
356
		return this;
357
	}
358
359
	/**
360
	 * Sets the validation message pattern for the {@link #maxScale(int)}
361
	 * constraint.
362
	 * 
363
	 * @param message
364
	 *            The validation message pattern for the {@link #maxScale(int)}
365
	 *            constraint. Can be parameterized with the maximum scale ({0})
366
	 *            of the decimal.
367
	 * @return This constraints instance for method chaining.
368
	 * 
369
	 * @see #maxScale(int)
370
	 */
371
	public DecimalConstraints maxScaleMessage(String message) {
372
		this.maxScaleMessage = message;
373
		return this;
374
	}
375
376
	/**
377
	 * Sets the format to use when formatting the precision in any of the
378
	 * validation messages stemming from a precision constraint.
379
	 * 
380
	 * @param format
381
	 *            The format to use for displaying the precision in validation
382
	 *            messages stemming from a precision constraint.
383
	 * @return This constraints instance for method chaining.
384
	 * 
385
	 * @see #maxPrecision(int)
386
	 */
387
	public DecimalConstraints precisionFormat(NumberFormat format) {
388
		this.precisionFormat = format;
389
		return this;
390
	}
391
392
	/**
393
	 * Adds a validator ensuring that the input decimal's precision is not
394
	 * greater than the given one. Uses the current
395
	 * {@link #maxPrecisionMessage(String) validation message} and
396
	 * {@link #precisionFormat(NumberFormat) precision format}.
397
	 * 
398
	 * @param precision
399
	 *            The maximum precision to enforce on the input decimal.
400
	 * @return This constraints instance for method chaining.
401
	 */
402
	public DecimalConstraints maxPrecision(int precision) {
403
		addValidator(DecimalPrecisionValidator.max(precision,
404
				maxPrecisionMessage, precisionFormat));
405
		return this;
406
	}
407
408
	/**
409
	 * Sets the validation message pattern for the {@link #maxPrecision(int)}
410
	 * constraint.
411
	 * 
412
	 * @param message
413
	 *            The validation message pattern for the
414
	 *            {@link #maxPrecision(int)} constraint. Can be parameterized
415
	 *            with the maximum precision ({0}) of the decimal.
416
	 * @return This constraints instance for method chaining.
417
	 * 
418
	 * @see #maxPrecision(int)
419
	 */
420
	public DecimalConstraints maxPrecisionMessage(String message) {
421
		this.maxPrecisionMessage = message;
422
		return this;
423
	}
424
}
(-)src/org/eclipse/core/databinding/validation/constraint/DateConstraints.java (+260 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import java.util.Date;
15
16
import org.eclipse.core.internal.databinding.validation.DateRangeValidator;
17
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
18
19
import com.ibm.icu.text.DateFormat;
20
21
/**
22
 * Provides a set of constraints to apply to <code>Date</code>s.
23
 * 
24
 * <p>
25
 * Instances of this class can be used to define a set of constraints to apply
26
 * to dates. In addition, the validation messages to be issued for the
27
 * individual constraints as well as the way in which model objects are
28
 * formatted in the validation messages can be configured.
29
 * </p>
30
 * 
31
 * @see Date
32
 * 
33
 * @noextend This class is not intended to be subclassed by clients.
34
 * @since 1.3
35
 */
36
public class DateConstraints extends Constraints {
37
38
	private DateFormat dateFormat = DateFormat.getDateInstance();
39
40
	private String requiredMessage = null;
41
42
	private String afterMessage = null;
43
44
	private String afterEqualMessage = null;
45
46
	private String beforeMessage = null;
47
48
	private String beforeEqualMessage = null;
49
50
	private String rangeMessage = null;
51
52
	/**
53
	 * Sets the format to use when formatting a date to be included in any of
54
	 * the validation messages.
55
	 * 
56
	 * @param format
57
	 *            The format to use for displaying dates in validation messages.
58
	 * @return This constraints instance for method chaining.
59
	 */
60
	public DateConstraints dateFormat(DateFormat format) {
61
		this.dateFormat = format;
62
		return this;
63
	}
64
65
	/**
66
	 * Adds a validator ensuring that the input date is not <code>null</code>.
67
	 * Uses the current {@link #requiredMessage(String) validation message}.
68
	 * 
69
	 * @return This constraints instance for method chaining.
70
	 */
71
	public DateConstraints required() {
72
		addValidator(new NonNullValidator(requiredMessage));
73
		return this;
74
	}
75
76
	/**
77
	 * Sets the validation message for the {@link #required()} constraint.
78
	 * 
79
	 * @param message
80
	 *            The validation message for the {@link #required()} constraint.
81
	 * @return This constraints instance for method chaining.
82
	 * 
83
	 * @see #required()
84
	 */
85
	public DateConstraints requiredMessage(String message) {
86
		this.requiredMessage = message;
87
		return this;
88
	}
89
90
	/**
91
	 * Adds a validator ensuring that the input date is after the given date.
92
	 * Uses the current {@link #afterMessage(String) validation message} and
93
	 * {@link #dateFormat(DateFormat) date format}.
94
	 * 
95
	 * @param date
96
	 *            The date which the input date must be after.
97
	 * @return This constraints instance for method chaining.
98
	 * 
99
	 * @see Date#after(Date)
100
	 */
101
	public DateConstraints after(Date date) {
102
		addValidator(DateRangeValidator.after(date, afterMessage, dateFormat));
103
		return this;
104
	}
105
106
	/**
107
	 * Sets the validation message pattern for the {@link #after(Date)}
108
	 * constraint.
109
	 * 
110
	 * @param message
111
	 *            The validation message pattern for the {@link #after(Date)}
112
	 *            constraint. Can be parameterized with the date ({0}) which the
113
	 *            input date must be after.
114
	 * @return This constraints instance for method chaining.
115
	 * 
116
	 * @see #after(Date)
117
	 */
118
	public DateConstraints afterMessage(String message) {
119
		this.afterMessage = message;
120
		return this;
121
	}
122
123
	/**
124
	 * Adds a validator ensuring that the input date is after or on the given
125
	 * date. Uses the current {@link #afterEqualMessage(String) validation
126
	 * message} and {@link #dateFormat(DateFormat) date format}.
127
	 * 
128
	 * @param date
129
	 *            The date which the input date must be after or on.
130
	 * @return This constraints instance for method chaining.
131
	 * 
132
	 * @see Date#after(Date)
133
	 * @see Date#equals(Object)
134
	 */
135
	public DateConstraints afterEqual(Date date) {
136
		addValidator(DateRangeValidator.afterEqual(date, afterEqualMessage,
137
				dateFormat));
138
		return this;
139
	}
140
141
	/**
142
	 * Sets the validation message pattern for the {@link #afterEqual(Date)}
143
	 * constraint.
144
	 * 
145
	 * @param message
146
	 *            The validation message pattern for the
147
	 *            {@link #afterEqual(Date)} constraint. Can be parameterized
148
	 *            with the date ({0}) which the input date must be after or on.
149
	 * @return This constraints instance for method chaining.
150
	 * 
151
	 * @see #afterEqual(Date)
152
	 */
153
	public DateConstraints afterEqualMessage(String message) {
154
		this.afterEqualMessage = message;
155
		return this;
156
	}
157
158
	/**
159
	 * Adds a validator ensuring that the input date is before the given date.
160
	 * Uses the current {@link #beforeMessage(String) validation message} and
161
	 * {@link #dateFormat(DateFormat) date format}.
162
	 * 
163
	 * @param date
164
	 *            The date which the input date must be before
165
	 * @return This constraints instance for method chaining.
166
	 * 
167
	 * @see Date#before(Date)
168
	 */
169
	public DateConstraints before(Date date) {
170
		addValidator(DateRangeValidator.before(date, beforeMessage, dateFormat));
171
		return this;
172
	}
173
174
	/**
175
	 * Sets the validation message pattern for the {@link #before(Date)}
176
	 * constraint.
177
	 * 
178
	 * @param message
179
	 *            The validation message pattern for the {@link #before(Date)}
180
	 *            constraint. Can be parameterized with the date ({0}) which the
181
	 *            input date must be before.
182
	 * @return This constraints instance for method chaining.
183
	 * 
184
	 * @see #before(Date)
185
	 */
186
	public DateConstraints beforeMessage(String message) {
187
		this.beforeMessage = message;
188
		return this;
189
	}
190
191
	/**
192
	 * Adds a validator ensuring that the input date is before or on the given
193
	 * date. Uses the current {@link #beforeEqualMessage(String) validation
194
	 * message} and {@link #dateFormat(DateFormat) date format}.
195
	 * 
196
	 * @param date
197
	 *            The date which the input date must be before or on.
198
	 * @return This constraints instance for method chaining.
199
	 * 
200
	 * @see Date#before(Date)
201
	 * @see Date#equals(Object)
202
	 */
203
	public DateConstraints beforeEqual(Date date) {
204
		addValidator(DateRangeValidator.beforeEqual(date, beforeEqualMessage,
205
				dateFormat));
206
		return this;
207
	}
208
209
	/**
210
	 * Sets the validation message pattern for the {@link #beforeEqual(Date)}
211
	 * constraint.
212
	 * 
213
	 * @param message
214
	 *            The validation message pattern for the
215
	 *            {@link #beforeEqual(Date)} constraint. Can be parameterized
216
	 *            ({0}) with the date which the input date must be before or on.
217
	 * @return This constraints instance for method chaining.
218
	 * 
219
	 * @see #beforeEqual(Date)
220
	 */
221
	public DateConstraints beforeEqualMessage(String message) {
222
		this.beforeEqualMessage = message;
223
		return this;
224
	}
225
226
	/**
227
	 * Adds a validator ensuring that the input date is within the given range.
228
	 * Uses the current {@link #rangeMessage(String) validation message} and
229
	 * {@link #dateFormat(DateFormat) date format}.
230
	 * 
231
	 * @param minDate
232
	 *            The lower bound of the range (inclusive).
233
	 * @param maxDate
234
	 *            The upper bound of the range (inclusive).
235
	 * @return This constraints instance for method chaining.
236
	 */
237
	public DateConstraints range(Date minDate, Date maxDate) {
238
		addValidator(DateRangeValidator.range(minDate, maxDate, rangeMessage,
239
				dateFormat));
240
		return this;
241
	}
242
243
	/**
244
	 * Sets the validation message pattern for the {@link #range(Date, Date)}
245
	 * constraint.
246
	 * 
247
	 * @param message
248
	 *            The validation message pattern for the
249
	 *            {@link #range(Date, Date)} constraint. Can be parameterized
250
	 *            with the min ({0}) and max ({1}) dates of the range in which
251
	 *            the input date must lie.
252
	 * @return This constraints instance for method chaining.
253
	 * 
254
	 * @see #range(Date, Date)
255
	 */
256
	public DateConstraints rangeMessage(String message) {
257
		this.rangeMessage = message;
258
		return this;
259
	}
260
}
(-)src/org/eclipse/core/internal/databinding/conversion/StringTrimConverter.java (+45 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.conversion;
13
14
import org.eclipse.core.databinding.conversion.Converter;
15
16
/**
17
 * @since 1.3
18
 */
19
public class StringTrimConverter extends Converter {
20
21
	private final boolean trimToNull;
22
23
	/**
24
	 * 
25
	 * @param trimToNull
26
	 */
27
	public StringTrimConverter(boolean trimToNull) {
28
		super(String.class, String.class);
29
		this.trimToNull = trimToNull;
30
	}
31
32
	public Object convert(Object fromObject) {
33
		String string = (String) fromObject;
34
35
		if (string != null) {
36
			string = string.trim();
37
38
			if (trimToNull && string.length() == 0) {
39
				string = null;
40
			}
41
		}
42
43
		return string;
44
	}
45
}
(-)src/org/eclipse/core/databinding/editing/BooleanEditing.java (+204 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.validation.constraint.BooleanConstraints;
15
import org.eclipse.core.databinding.validation.constraint.Constraints;
16
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
17
import org.eclipse.core.internal.databinding.conversion.BooleanToStringConverter;
18
import org.eclipse.core.internal.databinding.conversion.StringToBooleanConverter;
19
import org.eclipse.core.internal.databinding.validation.StringToBooleanValidator;
20
21
/**
22
 * @noextend This class is not intended to be subclassed by clients.
23
 * @since 1.3
24
 */
25
public class BooleanEditing extends Editing {
26
27
	/**
28
	 * Creates a new editing object for booleans.
29
	 * 
30
	 * @param trueValues
31
	 *            The set of strings representing a <code>true</code> value.
32
	 * @param falseValues
33
	 *            The set of strings representing a <code>false</code> value.
34
	 * @param parseErrorMessage
35
	 *            The validation message issued in case the input string cannot
36
	 *            be parsed to a boolean.
37
	 * 
38
	 * @noreference This constructor is not intended to be referenced by
39
	 *              clients.
40
	 */
41
	protected BooleanEditing(String[] trueValues, String[] falseValues,
42
			String parseErrorMessage) {
43
		StringToBooleanConverter targetConverter = new StringToBooleanConverter();
44
		BooleanToStringConverter modelConverter = new BooleanToStringConverter(
45
				Boolean.class);
46
47
		StringToBooleanValidator targetValidator = new StringToBooleanValidator();
48
		if (parseErrorMessage != null) {
49
			targetValidator.setParseErrorMessage(parseErrorMessage);
50
		}
51
52
		if (trueValues != null && falseValues != null) {
53
			targetValidator.setSourceStrings(trueValues, falseValues);
54
			targetConverter.setSourceStrings(trueValues, falseValues);
55
			modelConverter.setTargetStrings(trueValues[0], falseValues[0]);
56
		}
57
58
		setTargetConverter(targetConverter);
59
		setModelConverter(modelConverter);
60
		targetConstraints().addValidator(targetValidator);
61
	}
62
63
	/**
64
	 * Creates a new editing object which uses the default set of string
65
	 * representations for boolean values for parsing and displaying.
66
	 * 
67
	 * @return The new editing object for the default set of string
68
	 *         representations for boolean values.
69
	 */
70
	public static BooleanEditing withDefaults() {
71
		return withDefaults(null);
72
	}
73
74
	/**
75
	 * Creates a new editing object which uses the default set of string
76
	 * representations for boolean values for parsing and displaying. Uses the
77
	 * specified custom validation message.
78
	 * 
79
	 * @param parseErrorMessage
80
	 *            The validation message issued in case the input string cannot
81
	 *            be parsed to a boolean.
82
	 * @return The new editing object for the default set of string
83
	 *         representations for boolean values.
84
	 */
85
	public static BooleanEditing withDefaults(String parseErrorMessage) {
86
		return new BooleanEditing(null, null, parseErrorMessage);
87
	}
88
89
	/**
90
	 * Creates a new editing object which uses the given set of string
91
	 * representations for boolean values for parsing and displaying.
92
	 * 
93
	 * <p>
94
	 * For parsing, the given string values will be considered valid
95
	 * representations of {@code true} and {@code false}, respectively. For
96
	 * displaying, the first element of the respective array will be used for
97
	 * representing the corresponding boolean value.
98
	 * </p>
99
	 * 
100
	 * @param trueValues
101
	 *            The set of strings representing a <code>true</code> value.
102
	 * @param falseValues
103
	 *            The set of strings representing a <code>false</code> value.
104
	 * @return The new editing object for the given set of string
105
	 *         representations for boolean values.
106
	 */
107
	public static BooleanEditing forStringValues(String[] trueValues,
108
			String[] falseValues) {
109
		return forStringValues(trueValues, falseValues, null);
110
	}
111
112
	/**
113
	 * Creates a new editing object which uses the given set of string
114
	 * representations for boolean values for parsing and displaying. Uses the
115
	 * specified custom validation message.
116
	 * 
117
	 * <p>
118
	 * For parsing, the given string values will be considered valid
119
	 * representations of {@code true} and {@code false}, respectively. For
120
	 * displaying, the first element of the respective array will be used for
121
	 * representing the corresponding boolean value.
122
	 * </p>
123
	 * 
124
	 * @param trueValues
125
	 *            The set of strings representing a <code>true</code> value.
126
	 * @param falseValues
127
	 *            The set of strings representing a <code>false</code> value.
128
	 * @param parseErrorMessage
129
	 *            The validation message issued in case the input string cannot
130
	 *            be parsed to a boolean.
131
	 * @return The new editing object for the given set of string
132
	 *         representations for boolean values.
133
	 */
134
	public static BooleanEditing forStringValues(String[] trueValues,
135
			String[] falseValues, String parseErrorMessage) {
136
		return new BooleanEditing(trueValues, falseValues, parseErrorMessage);
137
	}
138
139
	/**
140
	 * Returns the target constraints to apply.
141
	 * 
142
	 * <p>
143
	 * This method provides a typesafe access to the {@link StringConstraints
144
	 * string target constraints} of this editing object and is equivalent to
145
	 * {@code (StringConstraints) targetConstraints()}.
146
	 * </p>
147
	 * 
148
	 * @return The target constraints to apply.
149
	 * 
150
	 * @see #targetConstraints()
151
	 * @see StringConstraints
152
	 */
153
	public StringConstraints targetStringConstraints() {
154
		return (StringConstraints) targetConstraints();
155
	}
156
157
	/**
158
	 * Returns the model constraints to apply.
159
	 * 
160
	 * <p>
161
	 * This method provides a typesafe access to the {@link BooleanConstraints
162
	 * bool model constraints} of this editing object and is equivalent to
163
	 * {@code (BooleanConstraints) modelConstraints()}.
164
	 * </p>
165
	 * 
166
	 * @return The model constraints to apply.
167
	 * 
168
	 * @see #modelConstraints()
169
	 * @see BooleanConstraints
170
	 */
171
	public BooleanConstraints modelBooleanConstraints() {
172
		return (BooleanConstraints) modelConstraints();
173
	}
174
175
	/**
176
	 * Returns the before-set model constraints to apply.
177
	 * 
178
	 * <p>
179
	 * This method provides a typesafe access to the {@link BooleanConstraints
180
	 * bool before-set model constraints} of this editing object and is
181
	 * equivalent to {@code (BooleanConstraints) beforeSetModelConstraints()}.
182
	 * </p>
183
	 * 
184
	 * @return The before-set model constraints to apply.
185
	 * 
186
	 * @see #beforeSetModelConstraints()
187
	 * @see BooleanConstraints
188
	 */
189
	public BooleanConstraints beforeSetModelBooleanConstraints() {
190
		return (BooleanConstraints) beforeSetModelConstraints();
191
	}
192
193
	protected Constraints createTargetConstraints() {
194
		return new StringConstraints();
195
	}
196
197
	protected Constraints createModelConstraints() {
198
		return new BooleanConstraints();
199
	}
200
201
	protected Constraints createBeforeSetModelConstraints() {
202
		return new BooleanConstraints();
203
	}
204
}
(-)src/org/eclipse/core/databinding/validation/constraint/BigDecimalConstraints.java (+430 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import java.math.BigDecimal;
15
16
import org.eclipse.core.internal.databinding.validation.BigDecimalRangeValidator;
17
import org.eclipse.core.internal.databinding.validation.DecimalPrecisionValidator;
18
import org.eclipse.core.internal.databinding.validation.DecimalScaleValidator;
19
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
20
21
import com.ibm.icu.text.NumberFormat;
22
23
/**
24
 * Provides a set of constraints to apply to <code>BigDecimal</code>s.
25
 * 
26
 * <p>
27
 * Instances of this class can be used to define a set of constraints to apply
28
 * to BigDecimal numbers. In addition, the validation messages to be issued for
29
 * the individual constraints as well as the way in which model objects are
30
 * formatted in the validation messages can be configured.
31
 * </p>
32
 * 
33
 * @see BigDecimal
34
 * 
35
 * @noextend This class is not intended to be subclassed by clients.
36
 * @since 1.3
37
 */
38
public class BigDecimalConstraints extends Constraints {
39
40
	private NumberFormat bigDecimalFormat = NumberFormat.getNumberInstance();
41
42
	private NumberFormat scaleFormat = NumberFormat.getIntegerInstance();
43
44
	private NumberFormat precisionFormat = NumberFormat.getIntegerInstance();
45
46
	private String requiredMessage = null;
47
48
	private String greaterMessage = null;
49
50
	private String greaterEqualMessage = null;
51
52
	private String lessMessage = null;
53
54
	private String lessEqualMessage = null;
55
56
	private String rangeMessage = null;
57
58
	private String positiveMessage = null;
59
60
	private String nonNegativeMessage = null;
61
62
	private String maxScaleMessage = null;
63
64
	private String maxPrecisionMessage = null;
65
66
	/**
67
	 * Sets the format to use when formatting a BigDecimal to be included in any
68
	 * of the validation messages.
69
	 * 
70
	 * @param format
71
	 *            The format to use for displaying BigDecimals in validation
72
	 *            messages.
73
	 * @return This constraints instance for method chaining.
74
	 */
75
	public BigDecimalConstraints bigDecimalFormat(NumberFormat format) {
76
		this.bigDecimalFormat = format;
77
		return this;
78
	}
79
80
	/**
81
	 * Adds a validator ensuring that the input BigDecimal is not
82
	 * <code>null</code>. Uses the current {@link #requiredMessage(String)
83
	 * validation message}.
84
	 * 
85
	 * @return This constraints instance for method chaining.
86
	 */
87
	public BigDecimalConstraints required() {
88
		addValidator(new NonNullValidator(requiredMessage));
89
		return this;
90
	}
91
92
	/**
93
	 * Sets the validation message for the {@link #required()} constraint.
94
	 * 
95
	 * @param message
96
	 *            The validation message for the {@link #required()} constraint.
97
	 * @return This constraints instance for method chaining.
98
	 * 
99
	 * @see #required()
100
	 */
101
	public BigDecimalConstraints requiredMessage(String message) {
102
		this.requiredMessage = message;
103
		return this;
104
	}
105
106
	/**
107
	 * Adds a validator ensuring that the input BigDecimal is greater than the
108
	 * given number. Uses the current {@link #greaterMessage(String) validation
109
	 * message} and {@link #bigDecimalFormat(NumberFormat) BigDecimal format}.
110
	 * 
111
	 * @param number
112
	 *            The number which the input BigDecimal must be greater than.
113
	 * @return This constraints instance for method chaining.
114
	 */
115
	public BigDecimalConstraints greater(BigDecimal number) {
116
		addValidator(BigDecimalRangeValidator.greater(number, greaterMessage,
117
				bigDecimalFormat));
118
		return this;
119
	}
120
121
	/**
122
	 * Sets the validation message pattern for the {@link #greater(BigDecimal)}
123
	 * constraint.
124
	 * 
125
	 * @param message
126
	 *            The validation message pattern for the
127
	 *            {@link #greater(BigDecimal)} constraint. Can be parameterized
128
	 *            with the number ({0}) which the input BigDecimal must be
129
	 *            greater than.
130
	 * @return This constraints instance for method chaining.
131
	 * 
132
	 * @see #greater(BigDecimal)
133
	 */
134
	public BigDecimalConstraints greaterMessage(String message) {
135
		this.greaterMessage = message;
136
		return this;
137
	}
138
139
	/**
140
	 * Adds a validator ensuring that the input BigDecimal is greater than or
141
	 * equal to the given number. Uses the current
142
	 * {@link #greaterEqualMessage(String) validation message} and
143
	 * {@link #bigDecimalFormat(NumberFormat) BigDecimal format}.
144
	 * 
145
	 * @param number
146
	 *            The number which the input BigDecimal must be greater than or
147
	 *            equal to.
148
	 * @return This constraints instance for method chaining.
149
	 */
150
	public BigDecimalConstraints greaterEqual(BigDecimal number) {
151
		addValidator(BigDecimalRangeValidator.greaterEqual(number,
152
				greaterEqualMessage, bigDecimalFormat));
153
		return this;
154
	}
155
156
	/**
157
	 * Sets the validation message pattern for the
158
	 * {@link #greaterEqual(BigDecimal)} constraint.
159
	 * 
160
	 * @param message
161
	 *            The validation message pattern for the
162
	 *            {@link #greaterEqual(BigDecimal)} constraint. Can be
163
	 *            parameterized with the number ({0}) which the input BigDecimal
164
	 *            must be greater than or equal to.
165
	 * @return This constraints instance for method chaining.
166
	 * 
167
	 * @see #greaterEqual(BigDecimal)
168
	 */
169
	public BigDecimalConstraints greaterEqualMessage(String message) {
170
		this.greaterEqualMessage = message;
171
		return this;
172
	}
173
174
	/**
175
	 * Adds a validator ensuring that the input BigDecimal is less than the
176
	 * given number. Uses the current {@link #lessMessage(String) validation
177
	 * message} and {@link #bigDecimalFormat(NumberFormat) BigDecimal format}.
178
	 * 
179
	 * @param number
180
	 *            The number which the input BigDecimal must be less than.
181
	 * @return This constraints instance for method chaining.
182
	 */
183
	public BigDecimalConstraints less(BigDecimal number) {
184
		addValidator(BigDecimalRangeValidator.less(number, lessMessage,
185
				bigDecimalFormat));
186
		return this;
187
	}
188
189
	/**
190
	 * Sets the validation message pattern for the {@link #less(BigDecimal)}
191
	 * constraint.
192
	 * 
193
	 * @param message
194
	 *            The validation message pattern for the
195
	 *            {@link #less(BigDecimal)} constraint. Can be parameterized
196
	 *            with the number ({0}) which the input BigDecimal must be less
197
	 *            than.
198
	 * @return This constraints instance for method chaining.
199
	 * 
200
	 * @see #less(BigDecimal)
201
	 */
202
	public BigDecimalConstraints lessMessage(String message) {
203
		this.lessMessage = message;
204
		return this;
205
	}
206
207
	/**
208
	 * Adds a validator ensuring that the input BigDecimal is less than or equal
209
	 * to the given number. Uses the current {@link #lessEqualMessage(String)
210
	 * validation message} and {@link #bigDecimalFormat(NumberFormat) BigDecimal
211
	 * format}.
212
	 * 
213
	 * @param number
214
	 *            The number which the input BigDecimal must be less than or
215
	 *            equal to.
216
	 * @return This constraints instance for method chaining.
217
	 */
218
	public BigDecimalConstraints lessEqual(BigDecimal number) {
219
		addValidator(BigDecimalRangeValidator.greaterEqual(number,
220
				lessEqualMessage, bigDecimalFormat));
221
		return this;
222
	}
223
224
	/**
225
	 * Sets the validation message pattern for the
226
	 * {@link #lessEqual(BigDecimal)} constraint.
227
	 * 
228
	 * @param message
229
	 *            The validation message pattern for the
230
	 *            {@link #lessEqual(BigDecimal)} constraint. Can be
231
	 *            parameterized with the number ({0}) which the input BigDecimal
232
	 *            must be less than or equal to.
233
	 * @return This constraints instance for method chaining.
234
	 * 
235
	 * @see #lessEqual(BigDecimal)
236
	 */
237
	public BigDecimalConstraints lessEqualMessage(String message) {
238
		this.lessEqualMessage = message;
239
		return this;
240
	}
241
242
	/**
243
	 * Adds a validator ensuring that the input BigDecimal is within the given
244
	 * range. Uses the current {@link #rangeMessage(String) validation message}
245
	 * and {@link #bigDecimalFormat(NumberFormat) BigDecimal format}.
246
	 * 
247
	 * @param min
248
	 *            The lower bound of the range (inclusive).
249
	 * @param max
250
	 *            The upper bound of the range (inclusive).
251
	 * @return This constraints instance for method chaining.
252
	 */
253
	public BigDecimalConstraints range(BigDecimal min, BigDecimal max) {
254
		addValidator(BigDecimalRangeValidator.range(min, max, rangeMessage,
255
				bigDecimalFormat));
256
		return this;
257
	}
258
259
	/**
260
	 * Sets the validation message pattern for the
261
	 * {@link #range(BigDecimal, BigDecimal)} constraint.
262
	 * 
263
	 * @param message
264
	 *            The validation message pattern for the
265
	 *            {@link #range(BigDecimal, BigDecimal)} constraint. Can be
266
	 *            parameterized with the min ({0}) and max ({1}) values of the
267
	 *            range in which the input BigDecimal must lie.
268
	 * @return This constraints instance for method chaining.
269
	 * 
270
	 * @see #range(BigDecimal, BigDecimal)
271
	 */
272
	public BigDecimalConstraints rangeMessage(String message) {
273
		this.rangeMessage = message;
274
		return this;
275
	}
276
277
	/**
278
	 * Adds a validator ensuring that the input BigDecimal is positive. Uses the
279
	 * current {@link #positiveMessage(String) validation message}.
280
	 * 
281
	 * @return This constraints instance for method chaining.
282
	 */
283
	public BigDecimalConstraints positive() {
284
		addValidator(BigDecimalRangeValidator.positive(positiveMessage,
285
				bigDecimalFormat));
286
		return this;
287
	}
288
289
	/**
290
	 * Sets the validation message pattern for the {@link #positive()}
291
	 * constraint.
292
	 * 
293
	 * @param message
294
	 *            The validation message pattern for the {@link #positive()}
295
	 *            constraint.
296
	 * @return This constraints instance for method chaining.
297
	 * 
298
	 * @see #positive()
299
	 */
300
	public BigDecimalConstraints positiveMessage(String message) {
301
		this.positiveMessage = message;
302
		return this;
303
	}
304
305
	/**
306
	 * Adds a validator ensuring that the input BigDecimal is non-negative. Uses
307
	 * the current {@link #nonNegativeMessage(String) validation message}.
308
	 * 
309
	 * @return This constraints instance for method chaining.
310
	 */
311
	public BigDecimalConstraints nonNegative() {
312
		addValidator(BigDecimalRangeValidator.nonNegative(nonNegativeMessage,
313
				bigDecimalFormat));
314
		return this;
315
	}
316
317
	/**
318
	 * Sets the validation message pattern for the {@link #nonNegative()}
319
	 * constraint.
320
	 * 
321
	 * @param message
322
	 *            The validation message pattern for the {@link #nonNegative()}
323
	 *            constraint.
324
	 * @return This constraints instance for method chaining.
325
	 * 
326
	 * @see #nonNegative()
327
	 */
328
	public BigDecimalConstraints nonNegativeMessage(String message) {
329
		this.nonNegativeMessage = message;
330
		return this;
331
	}
332
333
	/**
334
	 * Sets the format to use when formatting the scale in any of the validation
335
	 * messages stemming from a scale constraint.
336
	 * 
337
	 * @param format
338
	 *            The format to use for displaying the scale in validation
339
	 *            messages stemming from a scale constraint.
340
	 * @return This constraints instance for method chaining.
341
	 * 
342
	 * @see #maxScale(int)
343
	 */
344
	public BigDecimalConstraints scaleFormat(NumberFormat format) {
345
		this.scaleFormat = format;
346
		return this;
347
	}
348
349
	/**
350
	 * Adds a validator ensuring that the input BigDecimal's scale is not
351
	 * greater than the given one. Uses the current
352
	 * {@link #maxScaleMessage(String) validation message} and
353
	 * {@link #scaleFormat(NumberFormat) scale format}.
354
	 * 
355
	 * @param scale
356
	 *            The maximum scale to enforce on the input BigDecimal.
357
	 * @return This constraints instance for method chaining.
358
	 */
359
	public BigDecimalConstraints maxScale(int scale) {
360
		addValidator(DecimalScaleValidator.max(scale, maxScaleMessage,
361
				scaleFormat));
362
		return this;
363
	}
364
365
	/**
366
	 * Sets the validation message pattern for the {@link #maxScale(int)}
367
	 * constraint.
368
	 * 
369
	 * @param message
370
	 *            The validation message pattern for the {@link #maxScale(int)}
371
	 *            constraint. Can be parameterized with the maximum scale ({0})
372
	 *            of the BigDecimal.
373
	 * @return This constraints instance for method chaining.
374
	 * 
375
	 * @see #maxScale(int)
376
	 */
377
	public BigDecimalConstraints maxScaleMessage(String message) {
378
		this.maxScaleMessage = message;
379
		return this;
380
	}
381
382
	/**
383
	 * Sets the format to use when formatting the precision in any of the
384
	 * validation messages stemming from a precision constraint.
385
	 * 
386
	 * @param format
387
	 *            The format to use for displaying the precision in validation
388
	 *            messages stemming from a precision constraint.
389
	 * @return This constraints instance for method chaining.
390
	 * 
391
	 * @see #maxPrecision(int)
392
	 */
393
	public BigDecimalConstraints precisionFormat(NumberFormat format) {
394
		this.precisionFormat = format;
395
		return this;
396
	}
397
398
	/**
399
	 * Adds a validator ensuring that the input decimal's precision is not
400
	 * greater than the given one. Uses the current
401
	 * {@link #maxPrecisionMessage(String) validation message} and
402
	 * {@link #precisionFormat(NumberFormat) precision format}.
403
	 * 
404
	 * @param precision
405
	 *            The maximum precision to enforce on the input decimal.
406
	 * @return This constraints instance for method chaining.
407
	 */
408
	public BigDecimalConstraints maxPrecision(int precision) {
409
		addValidator(DecimalPrecisionValidator.max(precision,
410
				maxPrecisionMessage, precisionFormat));
411
		return this;
412
	}
413
414
	/**
415
	 * Sets the validation message pattern for the {@link #maxPrecision(int)}
416
	 * constraint.
417
	 * 
418
	 * @param message
419
	 *            The validation message pattern for the
420
	 *            {@link #maxPrecision(int)} constraint. Can be parameterized
421
	 *            with the maximum precision ({0}) of the BigDecimal.
422
	 * @return This constraints instance for method chaining.
423
	 * 
424
	 * @see #maxPrecision(int)
425
	 */
426
	public BigDecimalConstraints maxPrecisionMessage(String message) {
427
		this.maxPrecisionMessage = message;
428
		return this;
429
	}
430
}
(-)src/org/eclipse/core/databinding/validation/constraint/BooleanConstraints.java (+56 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
15
16
/**
17
 * Provides a set of constraints to apply to <code>Boolean</code>s.
18
 * 
19
 * <p>
20
 * Instances of this class can be used to define a set of constraints to apply
21
 * to booleans. In addition, the validation messages to be issued for the
22
 * individual constraints can be configured.
23
 * </p>
24
 * 
25
 * @noextend This class is not intended to be subclassed by clients.
26
 * @since 1.3
27
 */
28
public class BooleanConstraints extends Constraints {
29
30
	private String requiredMessage = null;
31
32
	/**
33
	 * Adds a validator ensuring that the boolean value is not <code>null</code>
34
	 * . Uses the current {@link #requiredMessage(String) validation message}.
35
	 * 
36
	 * @return This constraints instance for method chaining.
37
	 */
38
	public BooleanConstraints required() {
39
		addValidator(new NonNullValidator(requiredMessage));
40
		return this;
41
	}
42
43
	/**
44
	 * Sets the validation message for the {@link #required()} constraint.
45
	 * 
46
	 * @param message
47
	 *            The validation message for the {@link #required()} constraint.
48
	 * @return This constraints instance for method chaining.
49
	 * 
50
	 * @see #required()
51
	 */
52
	public BooleanConstraints requiredMessage(String message) {
53
		this.requiredMessage = message;
54
		return this;
55
	}
56
}
(-)src/org/eclipse/core/internal/databinding/validation/BigIntegerRangeValidator.java (+206 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.math.BigInteger;
15
16
import com.ibm.icu.text.NumberFormat;
17
18
/**
19
 * Provides validations for BigIntegers which must lie within an open/closed
20
 * range.
21
 * 
22
 * @since 1.3
23
 */
24
public class BigIntegerRangeValidator extends NumberRangeValidator {
25
26
	private static final BigInteger ZERO = new BigInteger("0"); //$NON-NLS-1$
27
	private static final BigInteger ONE = new BigInteger("1"); //$NON-NLS-1$
28
29
	/**
30
	 * Single constructor which supports the individual integer range types.
31
	 * 
32
	 * @param min
33
	 *            The min BigInteger of the range or <code>null</code> in case
34
	 *            no lower bound is defined.
35
	 * @param max
36
	 *            The max BigInteger of the range or <code>null</code> in case
37
	 *            no upper bound is defined.
38
	 * @param minConstraint
39
	 *            The type of constraint imposed by the lower bound of the
40
	 *            range.
41
	 * @param maxConstraint
42
	 *            The type of constraint imposed by the upper bound of the
43
	 *            range.
44
	 * @param validationMessage
45
	 *            The validation message pattern to use. Can be parameterized by
46
	 *            the lower and upper bound of the range, if defined.
47
	 * @param format
48
	 *            The BigInteger format to use for formatting integers in the
49
	 *            validation message.
50
	 */
51
	private BigIntegerRangeValidator(BigInteger min, BigInteger max,
52
			int minConstraint, int maxConstraint, String validationMessage,
53
			NumberFormat format) {
54
		super(min, max, minConstraint, maxConstraint, validationMessage, format);
55
	}
56
57
	/**
58
	 * Creates a validator which checks that an input BigInteger is greater than
59
	 * the given number.
60
	 * 
61
	 * @param number
62
	 *            The reference number of the greater constraint.
63
	 * @param validationMessage
64
	 *            The validation message pattern to use. Can be parameterized
65
	 *            with the given reference number.
66
	 * @param format
67
	 *            The display format to use for formatting BigIntegers in the
68
	 *            validation message.
69
	 * @return The validator instance.
70
	 */
71
	public static BigIntegerRangeValidator greater(BigInteger number,
72
			String validationMessage, NumberFormat format) {
73
		return new BigIntegerRangeValidator(number, null, GREATER, UNDEFINED,
74
				defaultIfNull(validationMessage, GREATER_MESSAGE), format);
75
	}
76
77
	/**
78
	 * Creates a validator which checks that an input BigInteger is greater than
79
	 * or equal to the given number.
80
	 * 
81
	 * @param number
82
	 *            The reference number of the greater-equal constraint.
83
	 * @param validationMessage
84
	 *            The validation message pattern to use. Can be parameterized
85
	 *            with the given reference number.
86
	 * @param format
87
	 *            The display format to use for formatting BigIntegers in the
88
	 *            validation message.
89
	 * @return The validator instance.
90
	 */
91
	public static BigIntegerRangeValidator greaterEqual(BigInteger number,
92
			String validationMessage, NumberFormat format) {
93
		return new BigIntegerRangeValidator(number, null, GREATER_EQUAL,
94
				UNDEFINED, defaultIfNull(validationMessage,
95
						GREATER_EQUAL_MESSAGE), format);
96
	}
97
98
	/**
99
	 * Creates a validator which checks that an input BigInteger is less than
100
	 * the given number.
101
	 * 
102
	 * @param number
103
	 *            The reference number of the less constraint.
104
	 * @param validationMessage
105
	 *            The validation message pattern to use. Can be parameterized
106
	 *            with the given reference number.
107
	 * @param format
108
	 *            The display format to use for formatting BigIntegers in the
109
	 *            validation message.
110
	 * @return The validator instance.
111
	 */
112
	public static BigIntegerRangeValidator less(BigInteger number,
113
			String validationMessage, NumberFormat format) {
114
		return new BigIntegerRangeValidator(null, number, UNDEFINED, LESS,
115
				defaultIfNull(validationMessage, LESS_MESSAGE), format);
116
	}
117
118
	/**
119
	 * Creates a validator which checks that an input BigInteger is less than or
120
	 * equal to the given number.
121
	 * 
122
	 * @param number
123
	 *            The reference number of the less-equal constraint.
124
	 * @param validationMessage
125
	 *            The validation message pattern to use. Can be parameterized
126
	 *            with the given reference number.
127
	 * @param format
128
	 *            The display format to use for formatting BigIntegers in the
129
	 *            validation message.
130
	 * @return The validator instance.
131
	 */
132
	public static BigIntegerRangeValidator lessEqual(BigInteger number,
133
			String validationMessage, NumberFormat format) {
134
		return new BigIntegerRangeValidator(null, number, UNDEFINED,
135
				LESS_EQUAL,
136
				defaultIfNull(validationMessage, LESS_EQUAL_MESSAGE), format);
137
	}
138
139
	/**
140
	 * Creates a validator which checks that an input BigInteger is within the
141
	 * given range.
142
	 * 
143
	 * @param min
144
	 *            The lower bound of the range (inclusive).
145
	 * @param max
146
	 *            The upper bound of the range (inclusive).
147
	 * @param validationMessage
148
	 *            The validation message pattern to use. Can be parameterized
149
	 *            with the range's lower and upper bound.
150
	 * @param format
151
	 *            The display format to use for formatting BigIntegers in the
152
	 *            validation message.
153
	 * @return The validator instance.
154
	 */
155
	public static BigIntegerRangeValidator range(BigInteger min,
156
			BigInteger max, String validationMessage, NumberFormat format) {
157
		return new BigIntegerRangeValidator(min, max, GREATER_EQUAL,
158
				LESS_EQUAL, defaultIfNull(validationMessage,
159
						WITHIN_RANGE_MESSAGE), format);
160
	}
161
162
	/**
163
	 * Creates a validator which checks that an input BigInteger is positive.
164
	 * 
165
	 * @param validationMessage
166
	 *            The validation message to use.
167
	 * @param format
168
	 *            The display format to use for formatting BigIntegers in the
169
	 *            validation message.
170
	 * @return The validator instance.
171
	 */
172
	public static BigIntegerRangeValidator positive(String validationMessage,
173
			NumberFormat format) {
174
		return new BigIntegerRangeValidator(ONE, null, GREATER_EQUAL,
175
				UNDEFINED, defaultIfNull(validationMessage, POSITIVE_MESSAGE),
176
				format);
177
	}
178
179
	/**
180
	 * Creates a validator which checks that an input BigInteger is
181
	 * non-negative.
182
	 * 
183
	 * @param validationMessage
184
	 *            The validation message to use.
185
	 * @param format
186
	 *            The display format to use for formatting BigIntegers in the
187
	 *            validation message.
188
	 * @return The validator instance.
189
	 */
190
	public static BigIntegerRangeValidator nonNegative(
191
			String validationMessage, NumberFormat format) {
192
		return new BigIntegerRangeValidator(ZERO, null, GREATER_EQUAL,
193
				UNDEFINED, defaultIfNull(validationMessage,
194
						NON_NEGATIVE_MESSAGE), format);
195
	}
196
197
	protected int compare(Number number1, Number number2) {
198
		BigInteger bigInteger1 = (BigInteger) number1;
199
		BigInteger bigInteger2 = (BigInteger) number2;
200
		return bigInteger1.compareTo(bigInteger2);
201
	}
202
203
	private static String defaultIfNull(String string, String defaultString) {
204
		return (string != null) ? string : defaultString;
205
	}
206
}
(-)src/org/eclipse/core/internal/databinding/validation/DecimalPrecisionValidator.java (+108 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.text.MessageFormat;
15
16
import org.eclipse.core.databinding.validation.IValidator;
17
import org.eclipse.core.databinding.validation.ValidationStatus;
18
import org.eclipse.core.internal.databinding.BindingMessages;
19
import org.eclipse.core.runtime.IStatus;
20
21
import com.ibm.icu.math.BigDecimal;
22
import com.ibm.icu.text.NumberFormat;
23
24
/**
25
 * Provides validations for the precision of decimal numbers.
26
 * 
27
 * @since 1.3
28
 */
29
public class DecimalPrecisionValidator implements IValidator {
30
31
	private static final String MAX_PRECISION_VALIDATION_MESSAGE = BindingMessages
32
			.getString(BindingMessages.VALIDATE_DECIMAL_MAX_PRECISION);
33
34
	private final int maxPrecision;
35
36
	private final String validationMessage;
37
38
	private String formattedValidationMessage;
39
40
	private final NumberFormat precisionFormat;
41
42
	private DecimalPrecisionValidator(int maxPrecision,
43
			String validationMessage, NumberFormat precisionFormat) {
44
		this.maxPrecision = maxPrecision;
45
		this.validationMessage = validationMessage != null ? validationMessage
46
				: MAX_PRECISION_VALIDATION_MESSAGE;
47
		this.precisionFormat = precisionFormat;
48
	}
49
50
	/**
51
	 * Creates a validator which checks that an input decimal has a precision
52
	 * which is less or equal to the given precision.
53
	 * 
54
	 * @param maxPrecision
55
	 *            The maximum precision to enforce on the input decimal.
56
	 * @param validationMessage
57
	 *            The validation message pattern to use. Can be parameterized
58
	 *            with the maximum precision to be enforced.
59
	 * @param precisionFormat
60
	 *            The display format to use for formatting the precision in the
61
	 *            validation message.
62
	 * @return The validator instance.
63
	 */
64
	public static DecimalPrecisionValidator max(int maxPrecision,
65
			String validationMessage, NumberFormat precisionFormat) {
66
		return new DecimalPrecisionValidator(maxPrecision, validationMessage,
67
				precisionFormat);
68
	}
69
70
	public IStatus validate(Object value) {
71
		if (value != null) {
72
			Number number = (Number) value;
73
			final int precision;
74
			if (number instanceof BigDecimal) {
75
				precision = computePrecision(((BigDecimal) number));
76
			} else {
77
				precision = computePrecision(new BigDecimal(number
78
						.doubleValue()));
79
			}
80
			if (precision > maxPrecision) {
81
				return ValidationStatus.error(getFormattedValidationMessage());
82
			}
83
		}
84
		return ValidationStatus.ok();
85
	}
86
87
	private static int computePrecision(BigDecimal bigDecimal) {
88
		// In Java 1.4, there is no direct API for retrieving the precision of
89
		// a BigDecimal so we use the length of the string representation of the
90
		// unscaled BigInteger value of the BigDecimal to actually compute it.
91
		return bigDecimal.unscaledValue().abs().toString().length();
92
	}
93
94
	private synchronized String getFormattedValidationMessage() {
95
		if (formattedValidationMessage == null) {
96
			formattedValidationMessage = MessageFormat.format(
97
					validationMessage, getValidationMessageArguments());
98
		}
99
		return formattedValidationMessage;
100
	}
101
102
	private String[] getValidationMessageArguments() {
103
		synchronized (precisionFormat) {
104
			return new String[] { precisionFormat.format(new Integer(
105
					maxPrecision)) };
106
		}
107
	}
108
}
(-)src/org/eclipse/core/internal/databinding/validation/StringToBigDecimalValidator.java (+32 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
/**
15
 * Validates that a string is of the appropriate format for a BigDecimal.
16
 * 
17
 * @since 1.3
18
 */
19
public class StringToBigDecimalValidator extends
20
		AbstractStringToNumberValidator {
21
22
	/**
23
	 * @param converter
24
	 */
25
	public StringToBigDecimalValidator(NumberFormatConverter converter) {
26
		super(converter, null, null);
27
	}
28
29
	protected boolean isInRange(Number number) {
30
		return true;
31
	}
32
}
(-)src/org/eclipse/core/databinding/validation/constraint/Constraints.java (+224 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import java.util.ArrayList;
15
import java.util.Iterator;
16
import java.util.List;
17
18
import org.eclipse.core.databinding.util.Policy;
19
import org.eclipse.core.databinding.validation.IValidator;
20
import org.eclipse.core.internal.databinding.BindingMessages;
21
import org.eclipse.core.runtime.IStatus;
22
import org.eclipse.core.runtime.MultiStatus;
23
import org.eclipse.core.runtime.Status;
24
25
/**
26
 * This class allows to aggregate a set of {@link IValidator validators} and to
27
 * combine their individual validation statuses in different ways.
28
 * 
29
 * <p>
30
 * The set of validators to be applied can be {@link #addValidator(IValidator)
31
 * added} to a constraints object from which an aggregate validator can then be
32
 * {@link #createValidator() created} which combines the statuses of all the
33
 * accumulated validators as dictated by the specified
34
 * {@link #aggregationPolicy(int) aggregation policy}.
35
 * </p>
36
 * 
37
 * @see IValidator
38
 * 
39
 * @since 1.3
40
 */
41
public class Constraints {
42
43
	/**
44
	 * Constant denoting an aggregation strategy that merges multiple non-OK
45
	 * status objects in a {@link MultiStatus}. Returns an OK status result if
46
	 * all statuses from the set of validators to apply are an OK status.
47
	 * Returns a single status if there is only one non-OK status.
48
	 * 
49
	 * @see #aggregationPolicy(int)
50
	 */
51
	public static final int AGGREGATION_MERGED = 1;
52
53
	/**
54
	 * Constant denoting an aggregation strategy that always returns the
55
	 * <i>most</i> severe status from the set of validators to apply. If there
56
	 * is more than one status at the same severity level, it picks the first
57
	 * one it encounters.
58
	 * 
59
	 * @see #aggregationPolicy(int)
60
	 */
61
	public static final int AGGREGATION_MAX_SEVERITY = 2;
62
63
	/**
64
	 * Constant denoting an aggregation strategy that always returns the
65
	 * <i>least</i> severe status from the set of validators to apply. If there
66
	 * is more than one status at the same severity level, it picks the first
67
	 * one it encounters.
68
	 * 
69
	 * @see #aggregationPolicy(int)
70
	 */
71
	public static final int AGGREGATION_MIN_SEVERITY = 3;
72
73
	// Will be initialized lazily.
74
	private List validators = null;
75
76
	private IValidator cachedValidator = null;
77
78
	private int aggregationPolicy = AGGREGATION_MAX_SEVERITY;
79
80
	/**
81
	 * Adds a custom validator to the set of constraints to apply.
82
	 * 
83
	 * @param validator
84
	 *            The custom validator to add to the set of constraints.
85
	 * @return This constraints instance for method chaining.
86
	 */
87
	public final Constraints addValidator(IValidator validator) {
88
		if (validators == null) {
89
			validators = new ArrayList(2);
90
		}
91
		validators.add(validator);
92
		cachedValidator = null;
93
		return this;
94
	}
95
96
	/**
97
	 * Sets the aggregation policy to apply to the individual validations which
98
	 * constitute this set of constraints.
99
	 * 
100
	 * @param policy
101
	 *            The validation aggregation policy to set. Must be one of
102
	 *            {@link #AGGREGATION_MERGED}, {@link #AGGREGATION_MAX_SEVERITY}
103
	 *            or {@link #AGGREGATION_MIN_SEVERITY}.
104
	 * @return This constraints instance for method chaining.
105
	 * 
106
	 * @see #AGGREGATION_MERGED
107
	 * @see #AGGREGATION_MAX_SEVERITY
108
	 * @see #AGGREGATION_MIN_SEVERITY
109
	 */
110
	public final Constraints aggregationPolicy(int policy) {
111
		this.aggregationPolicy = policy;
112
		cachedValidator = null;
113
		return this;
114
	}
115
116
	/**
117
	 * Creates a validator which enforces the current set of constraints.
118
	 * 
119
	 * <p>
120
	 * Note that this method will return <code>null</code> in case the set of
121
	 * constraints to apply is empty.
122
	 * </p>
123
	 * 
124
	 * @return A validator which enforces the current set of constraints. May be
125
	 *         <code>null</code>.
126
	 */
127
	public final IValidator createValidator() {
128
		if (validators != null && !validators.isEmpty()) {
129
			if (cachedValidator == null) {
130
				if (validators.size() == 1) {
131
					cachedValidator = (IValidator) validators.get(0);
132
				} else {
133
					IValidator[] currentValidators = (IValidator[]) validators
134
							.toArray(new IValidator[validators.size()]);
135
					cachedValidator = new ConstraintsValidator(
136
							currentValidators, aggregationPolicy);
137
				}
138
			}
139
			return cachedValidator;
140
		}
141
		return null;
142
	}
143
144
	private static final class ConstraintsValidator implements IValidator {
145
146
		private final IValidator[] validators;
147
148
		private final int aggregationPolicy;
149
150
		public ConstraintsValidator(IValidator[] validators,
151
				int aggregationPolicy) {
152
			this.validators = validators;
153
			this.aggregationPolicy = aggregationPolicy;
154
		}
155
156
		public IStatus validate(Object value) {
157
			switch (aggregationPolicy) {
158
			case AGGREGATION_MERGED:
159
				return validateMerged(value);
160
			case AGGREGATION_MAX_SEVERITY:
161
				return validateMaxSeverity(value);
162
			case AGGREGATION_MIN_SEVERITY:
163
				return validateMinSeverity(value);
164
			default:
165
				throw new IllegalArgumentException(
166
						"Unsupported aggregationPolicy: " + aggregationPolicy); //$NON-NLS-1$
167
			}
168
		}
169
170
		private IStatus validateMerged(Object value) {
171
			List statuses = new ArrayList();
172
			for (int i = 0; i < validators.length; i++) {
173
				IValidator validator = validators[i];
174
				IStatus status = validator.validate(value);
175
				if (!status.isOK()) {
176
					statuses.add(status);
177
				}
178
			}
179
180
			if (statuses.size() == 1) {
181
				return (IStatus) statuses.get(0);
182
			}
183
184
			if (!statuses.isEmpty()) {
185
				MultiStatus result = new MultiStatus(Policy.JFACE_DATABINDING,
186
						0, BindingMessages
187
								.getString(BindingMessages.MULTIPLE_PROBLEMS),
188
						null);
189
				for (Iterator it = statuses.iterator(); it.hasNext();) {
190
					IStatus status = (IStatus) it.next();
191
					result.merge(status);
192
				}
193
				return result;
194
			}
195
196
			return Status.OK_STATUS;
197
		}
198
199
		private IStatus validateMaxSeverity(Object value) {
200
			IStatus maxStatus = Status.OK_STATUS;
201
			for (int i = 0; i < validators.length; i++) {
202
				IValidator validator = validators[i];
203
				IStatus status = validator.validate(value);
204
				if (status.getSeverity() > maxStatus.getSeverity()) {
205
					maxStatus = status;
206
				}
207
			}
208
			return maxStatus;
209
		}
210
211
		private IStatus validateMinSeverity(Object value) {
212
			IStatus minStatus = null;
213
			for (int i = 0; i < validators.length; i++) {
214
				IValidator validator = validators[i];
215
				IStatus status = validator.validate(value);
216
				if (minStatus == null
217
						|| status.getSeverity() < minStatus.getSeverity()) {
218
					minStatus = status;
219
				}
220
			}
221
			return minStatus != null ? minStatus : Status.OK_STATUS;
222
		}
223
	}
224
}
(-)src/org/eclipse/core/internal/databinding/validation/StringToBooleanValidator.java (+117 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.util.Arrays;
15
import java.util.LinkedList;
16
import java.util.List;
17
import java.util.StringTokenizer;
18
19
import org.eclipse.core.databinding.validation.IValidator;
20
import org.eclipse.core.databinding.validation.ValidationStatus;
21
import org.eclipse.core.internal.databinding.BindingMessages;
22
import org.eclipse.core.runtime.IStatus;
23
24
/**
25
 * @since 1.3
26
 */
27
public class StringToBooleanValidator implements IValidator {
28
29
	// TODO: Some of this code is duplicated from StringToBooleanPrimitiveConverter!
30
	private static final String[] DEFAULT_TRUE_VALUES;
31
	private static final String[] DEFAULT_FALSE_VALUES;
32
33
	static {
34
		String delimiter = BindingMessages.getString(BindingMessages.VALUE_DELIMITER);
35
		String values = BindingMessages.getString(BindingMessages.TRUE_STRING_VALUES);
36
		DEFAULT_TRUE_VALUES = valuesToSortedArray(delimiter, values);
37
38
		values = BindingMessages.getString(BindingMessages.FALSE_STRING_VALUES);
39
		DEFAULT_FALSE_VALUES = valuesToSortedArray(delimiter, values);
40
	}
41
42
	private String[] trueValues = DEFAULT_TRUE_VALUES;
43
	private String[] falseValues = DEFAULT_FALSE_VALUES;
44
45
	private String parseErrorMessage = BindingMessages.getString(BindingMessages.VALIDATE_INVALID_BOOLEAN_STRING);
46
47
	/**
48
	 * Returns a sorted array with all values converted to upper case.
49
	 *
50
	 * @param delimiter
51
	 * @param values
52
	 * @return sorted array of values
53
	 */
54
	private static String[] valuesToSortedArray(String delimiter, String values) {
55
		List list = new LinkedList();
56
		StringTokenizer tokenizer = new StringTokenizer(values, delimiter);
57
		while (tokenizer.hasMoreTokens()) {
58
			list.add(tokenizer.nextToken().toUpperCase());
59
		}
60
61
		String[] array = (String[]) list.toArray(new String[list.size()]);
62
		Arrays.sort(array);
63
64
		return array;
65
	}
66
67
	/**
68
	 * Sets the validation message to be used in case the source string does not
69
	 * represent a valid boolean value.
70
	 * 
71
	 * @param message
72
	 *            The validation message to be used in case the source string
73
	 *            does not represent a valid boolean value.
74
	 */
75
	public final void setParseErrorMessage(String message) {
76
		this.parseErrorMessage = message;
77
	}
78
79
	/**
80
	 * Sets the string values which are considered to represent a
81
	 * <code>true</code> and <code>false</code> value, respectively.
82
	 * 
83
	 * <p>
84
	 * Note that the capitalization of the provided strings is ignored.
85
	 * </p>
86
	 * 
87
	 * @param trueValues
88
	 *            The set of strings representing a <code>true</code> value.
89
	 * @param falseValues
90
	 *            The set of strings representing a <code>false</code> value.
91
	 */
92
	public final void setSourceStrings(String[] trueValues, String[] falseValues) {
93
		this.trueValues = new String[trueValues.length];
94
		for (int i = 0; i < trueValues.length; i++) {
95
			this.trueValues[i] = trueValues[i].toUpperCase();
96
		}
97
		Arrays.sort(this.trueValues); // for binary search
98
99
		this.falseValues = new String[falseValues.length];
100
		for (int i = 0; i < falseValues.length; i++) {
101
			this.falseValues[i] = falseValues[i].toUpperCase();
102
		}
103
		Arrays.sort(this.falseValues); // for binary search
104
	}
105
106
	public IStatus validate(Object value) {
107
		String source = (String) value;
108
		if (source != null && source.length() != 0) {
109
			source = source.toUpperCase();
110
			if (Arrays.binarySearch(trueValues, source) < 0
111
					&& Arrays.binarySearch(falseValues, source) < 0) {
112
				return ValidationStatus.error(parseErrorMessage);
113
			}
114
		}
115
		return ValidationStatus.ok();
116
	}
117
}
(-)src/org/eclipse/core/databinding/editing/Editing.java (+960 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.Binding;
15
import org.eclipse.core.databinding.DataBindingContext;
16
import org.eclipse.core.databinding.UpdateListStrategy;
17
import org.eclipse.core.databinding.UpdateSetStrategy;
18
import org.eclipse.core.databinding.UpdateValueStrategy;
19
import org.eclipse.core.databinding.conversion.IConverter;
20
import org.eclipse.core.databinding.observable.list.IObservableList;
21
import org.eclipse.core.databinding.observable.set.IObservableSet;
22
import org.eclipse.core.databinding.observable.value.IObservableValue;
23
import org.eclipse.core.databinding.validation.IValidator;
24
import org.eclipse.core.databinding.validation.constraint.Constraints;
25
import org.eclipse.core.runtime.IStatus;
26
import org.eclipse.core.runtime.MultiStatus;
27
28
/**
29
 * @since 1.3
30
 */
31
public class Editing {
32
33
	private Constraints targetConstraints;
34
35
	private Constraints modelConstraints;
36
37
	private Constraints beforeSetModelConstraints;
38
39
	private IConverter targetConverter;
40
41
	private IConverter modelConverter;
42
43
	/**
44
	 * Default constructor which creates an unconfigured editing instance.
45
	 */
46
	protected Editing() {
47
		// empty editing instance
48
	}
49
50
	/**
51
	 * Creates an unconfigured editing instance.
52
	 * 
53
	 * @return A new, unconfigured editing instance.
54
	 */
55
	public static Editing create() {
56
		return new Editing();
57
	}
58
59
	/**
60
	 * Creates an editing instance with the given target-to-model and
61
	 * model-to-target converters.
62
	 * 
63
	 * @param t2mConverter
64
	 *            The target-to-model converter to set. May be <code>null</code>
65
	 *            .
66
	 * @param m2tConverter
67
	 *            The model-to-target converter to set. May be <code>null</code>
68
	 *            .
69
	 * @return A new editing instance with the given target-to-model and
70
	 *         model-to-target converters.
71
	 */
72
	public static Editing withConverters(IConverter t2mConverter,
73
			IConverter m2tConverter) {
74
		Editing editing = new Editing();
75
		editing.setTargetConverter(t2mConverter);
76
		editing.setModelConverter(m2tConverter);
77
		return editing;
78
	}
79
80
	/**
81
	 * Returns the target constraints to apply.
82
	 * 
83
	 * @return The target constraints to apply.
84
	 * 
85
	 * @see #createTargetConstraints()
86
	 */
87
	public final Constraints targetConstraints() {
88
		if (targetConstraints == null) {
89
			targetConstraints = createTargetConstraints();
90
		}
91
		return targetConstraints;
92
	}
93
94
	/**
95
	 * Returns the model constraints to apply.
96
	 * 
97
	 * @return The model constraints to apply.
98
	 * 
99
	 * @see #createModelConstraints()
100
	 */
101
	public final Constraints modelConstraints() {
102
		if (modelConstraints == null) {
103
			modelConstraints = createModelConstraints();
104
		}
105
		return modelConstraints;
106
	}
107
108
	/**
109
	 * Returns the before-set model constraints to apply.
110
	 * 
111
	 * @return The before-set model constraints to apply.
112
	 * 
113
	 * @see #createBeforeSetModelConstraints()
114
	 */
115
	public final Constraints beforeSetModelConstraints() {
116
		if (beforeSetModelConstraints == null) {
117
			beforeSetModelConstraints = createBeforeSetModelConstraints();
118
		}
119
		return beforeSetModelConstraints;
120
	}
121
122
	/**
123
	 * Creates the target constraints to apply.
124
	 * 
125
	 * <p>
126
	 * The constraints object created by this method will be exposed as the
127
	 * {@link #targetConstraints()} of this editing object. By default, this
128
	 * method returns a plain {@link Constraints} object.
129
	 * </p>
130
	 * 
131
	 * <p>
132
	 * This method will be called lazily the first time the target constraints
133
	 * are accessed. Subclasses may overwrite this method in order to create a
134
	 * custom constraints object which will then be typically exposed in the
135
	 * subclass as API in order to allow for a typesafe access.
136
	 * </p>
137
	 * 
138
	 * @return The target constraints to apply.
139
	 * 
140
	 * @see #targetConstraints()
141
	 */
142
	protected Constraints createTargetConstraints() {
143
		return new Constraints();
144
	}
145
146
	/**
147
	 * Creates the model constraints to apply.
148
	 * 
149
	 * <p>
150
	 * The constraints object created by this method will be exposed as the
151
	 * {@link #modelConstraints()} of this editing object. By default, this
152
	 * method returns a plain {@link Constraints} object.
153
	 * </p>
154
	 * 
155
	 * <p>
156
	 * This method will be called lazily the first time the model constraints
157
	 * are accessed. Subclasses may overwrite this method in order to create a
158
	 * custom constraints object which will then be typically exposed in the
159
	 * subclass as API in order to allow for a typesafe access.
160
	 * </p>
161
	 * 
162
	 * @return The model constraints to apply.
163
	 * 
164
	 * @see #modelConstraints()
165
	 */
166
	protected Constraints createModelConstraints() {
167
		return new Constraints();
168
	}
169
170
	/**
171
	 * Creates the before-set model constraints to apply.
172
	 * 
173
	 * <p>
174
	 * The constraints object created by this method will be exposed as the
175
	 * {@link #beforeSetModelConstraints()} of this editing object. By default,
176
	 * this method returns a plain {@link Constraints} object.
177
	 * </p>
178
	 * 
179
	 * <p>
180
	 * This method will be called lazily the first time the before-set model
181
	 * constraints are accessed. Subclasses may overwrite this method in order
182
	 * to create a custom constraints object which will then be typically
183
	 * exposed in the subclass as API in order to allow for a typesafe access.
184
	 * </p>
185
	 * 
186
	 * @return The before-set model constraints to apply.
187
	 * 
188
	 * @see #beforeSetModelConstraints()
189
	 */
190
	protected Constraints createBeforeSetModelConstraints() {
191
		return new Constraints();
192
	}
193
194
	/**
195
	 * Sets the target-to-model converter for this editing instance.
196
	 * 
197
	 * @param converter
198
	 *            The target-to-model converter to set.
199
	 */
200
	protected final void setTargetConverter(IConverter converter) {
201
		this.targetConverter = converter;
202
	}
203
204
	/**
205
	 * Sets the model-to-target converter for this editing instance.
206
	 * 
207
	 * @param converter
208
	 *            The model-to-target converter to set.
209
	 */
210
	protected final void setModelConverter(IConverter converter) {
211
		this.modelConverter = converter;
212
	}
213
214
	/**
215
	 * Creates a new target-to-model {@link UpdateValueStrategy} with a default
216
	 * update policy configured by the current state of this editing object.
217
	 * 
218
	 * @return A new target-to-model {@link UpdateValueStrategy} configured by
219
	 *         the current state of this editing object.
220
	 * 
221
	 * @see UpdateValueStrategy#UpdateValueStrategy()
222
	 * @see #adaptT2MValueStrategy(UpdateValueStrategy)
223
	 */
224
	public final UpdateValueStrategy createT2MValueStrategy() {
225
		return adaptT2MValueStrategy(new UpdateValueStrategy());
226
	}
227
228
	/**
229
	 * Creates a new target-to-model {@link UpdateValueStrategy} with the given
230
	 * update policy configured by the current state of this editing object.
231
	 * 
232
	 * @param updatePolicy
233
	 *            The update policy to use.
234
	 * @return A new target-to-model {@link UpdateValueStrategy} configured by
235
	 *         the current state of this editing object.
236
	 * 
237
	 * @see UpdateValueStrategy#UpdateValueStrategy(int)
238
	 * @see #adaptT2MValueStrategy(UpdateValueStrategy)
239
	 */
240
	public final UpdateValueStrategy createT2MValueStrategy(int updatePolicy) {
241
		return adaptT2MValueStrategy(new UpdateValueStrategy(updatePolicy));
242
	}
243
244
	/**
245
	 * Creates a new model-to-target {@link UpdateValueStrategy} with a default
246
	 * update policy configured by the current state of this editing object.
247
	 * 
248
	 * @return A new model-to-target {@link UpdateValueStrategy} configured by
249
	 *         the current state of this editing object.
250
	 * 
251
	 * @see UpdateValueStrategy#UpdateValueStrategy()
252
	 * @see #adaptM2TValueStrategy(UpdateValueStrategy)
253
	 */
254
	public final UpdateValueStrategy createM2TValueStrategy() {
255
		return adaptM2TValueStrategy(new UpdateValueStrategy());
256
	}
257
258
	/**
259
	 * Creates a new model-to-target {@link UpdateValueStrategy} with the given
260
	 * update policy configured by the current state of this editing object.
261
	 * 
262
	 * @param updatePolicy
263
	 *            The update policy to use.
264
	 * @return A new model-to-target {@link UpdateValueStrategy} configured by
265
	 *         the current state of this editing object.
266
	 * 
267
	 * @see UpdateValueStrategy#UpdateValueStrategy(int)
268
	 * @see #adaptM2TValueStrategy(UpdateValueStrategy)
269
	 */
270
	public final UpdateValueStrategy createM2TValueStrategy(int updatePolicy) {
271
		return adaptM2TValueStrategy(new UpdateValueStrategy(updatePolicy));
272
	}
273
274
	/**
275
	 * Creates a new target-to-model {@link UpdateListStrategy} with a default
276
	 * update policy configured by the current state of this editing object.
277
	 * 
278
	 * @return A new target-to-model {@link UpdateListStrategy} configured by
279
	 *         the current state of this editing object.
280
	 * 
281
	 * @see UpdateListStrategy#UpdateListStrategy()
282
	 * @see #adaptT2MListStrategy(UpdateListStrategy)
283
	 */
284
	public final UpdateListStrategy createT2MListStrategy() {
285
		return adaptT2MListStrategy(new UpdateListStrategy());
286
	}
287
288
	/**
289
	 * Creates a new target-to-model {@link UpdateListStrategy} with the given
290
	 * update policy configured by the current state of this editing object.
291
	 * 
292
	 * @param updatePolicy
293
	 *            The update policy to use.
294
	 * @return A new target-to-model {@link UpdateListStrategy} configured by
295
	 *         the current state of this editing object.
296
	 * 
297
	 * @see UpdateListStrategy#UpdateListStrategy(int)
298
	 * @see #adaptT2MListStrategy(UpdateListStrategy)
299
	 */
300
	public final UpdateListStrategy createT2MListStrategy(int updatePolicy) {
301
		return adaptT2MListStrategy(new UpdateListStrategy(updatePolicy));
302
	}
303
304
	/**
305
	 * Creates a new model-to-target {@link UpdateListStrategy} with a default
306
	 * update policy configured by the current state of this editing object.
307
	 * 
308
	 * @return A new model-to-target {@link UpdateListStrategy} configured by
309
	 *         the current state of this editing object.
310
	 * 
311
	 * @see UpdateListStrategy#UpdateListStrategy()
312
	 * @see #adaptM2TListStrategy(UpdateListStrategy)
313
	 */
314
	public final UpdateListStrategy createM2TListStrategy() {
315
		return adaptM2TListStrategy(new UpdateListStrategy());
316
	}
317
318
	/**
319
	 * Creates a new model-to-target {@link UpdateListStrategy} with the given
320
	 * update policy configured by the current state of this editing object.
321
	 * 
322
	 * @param updatePolicy
323
	 *            The update policy to use.
324
	 * @return A new model-to-target {@link UpdateListStrategy} configured by
325
	 *         the current state of this editing object.
326
	 * 
327
	 * @see UpdateListStrategy#UpdateListStrategy(int)
328
	 * @see #adaptM2TListStrategy(UpdateListStrategy)
329
	 */
330
	public final UpdateListStrategy createM2TListStrategy(int updatePolicy) {
331
		return adaptM2TListStrategy(new UpdateListStrategy(updatePolicy));
332
	}
333
334
	/**
335
	 * Creates a new target-to-model {@link UpdateSetStrategy} with a default
336
	 * update policy configured by the current state of this editing object.
337
	 * 
338
	 * @return A new target-to-model {@link UpdateSetStrategy} configured by the
339
	 *         current state of this editing object.
340
	 * 
341
	 * @see UpdateListStrategy#UpdateListStrategy()
342
	 * @see #adaptT2MSetStrategy(UpdateSetStrategy)
343
	 */
344
	public final UpdateSetStrategy createT2MSetStrategy() {
345
		return adaptT2MSetStrategy(new UpdateSetStrategy());
346
	}
347
348
	/**
349
	 * Creates a new target-to-model {@link UpdateListStrategy} with the given
350
	 * update policy configured by the current state of this editing object.
351
	 * 
352
	 * @param updatePolicy
353
	 *            The update policy to use.
354
	 * @return A new target-to-model {@link UpdateListStrategy} configured by
355
	 *         the current state of this editing object.
356
	 * 
357
	 * @see UpdateSetStrategy#UpdateSetStrategy(int)
358
	 * @see #adaptT2MSetStrategy(UpdateSetStrategy)
359
	 */
360
	public final UpdateSetStrategy createT2MSetStrategy(int updatePolicy) {
361
		return adaptT2MSetStrategy(new UpdateSetStrategy(updatePolicy));
362
	}
363
364
	/**
365
	 * Creates a new model-to-target {@link UpdateSetStrategy} with a default
366
	 * update policy configured by the current state of this editing object.
367
	 * 
368
	 * @return A new model-to-target {@link UpdateSetStrategy} configured by the
369
	 *         current state of this editing object.
370
	 * 
371
	 * @see UpdateSetStrategy#UpdateSetStrategy()
372
	 * @see #adaptM2TSetStrategy(UpdateSetStrategy)
373
	 */
374
	public final UpdateSetStrategy createM2TSetStrategy() {
375
		return adaptM2TSetStrategy(new UpdateSetStrategy());
376
	}
377
378
	/**
379
	 * Creates a new model-to-target {@link UpdateSetStrategy} with the given
380
	 * update policy configured by the current state of this editing object.
381
	 * 
382
	 * @param updatePolicy
383
	 *            The update policy to use.
384
	 * @return A new model-to-target {@link UpdateSetStrategy} configured by the
385
	 *         current state of this editing object.
386
	 * 
387
	 * @see UpdateSetStrategy#UpdateSetStrategy(int)
388
	 * @see #adaptM2TSetStrategy(UpdateSetStrategy)
389
	 */
390
	public final UpdateSetStrategy createM2TSetStrategy(int updatePolicy) {
391
		return adaptM2TSetStrategy(new UpdateSetStrategy(updatePolicy));
392
	}
393
394
	/**
395
	 * Configures an existing target-to-model {@link UpdateValueStrategy} with
396
	 * the current state of this editing object.
397
	 * 
398
	 * <p>
399
	 * The configuration is done as follows:
400
	 * <ul>
401
	 * <li>
402
	 * The {@link Constraints#createValidator() validator} of the
403
	 * {@link #targetConstraints() target constraints} is set as the
404
	 * {@link UpdateValueStrategy#setAfterGetValidator(IValidator) after-get
405
	 * validator} of the update strategy.</li>
406
	 * <li>The {@link #setTargetConverter(IConverter) target converter} is set
407
	 * as the {@link UpdateValueStrategy#setConverter(IConverter) converter} of
408
	 * the update strategy.</li>
409
	 * <li>
410
	 * The {@link Constraints#createValidator() validator} of the
411
	 * {@link #modelConstraints() model constraints} is set as the
412
	 * {@link UpdateValueStrategy#setAfterConvertValidator(IValidator)
413
	 * after-convert validator} of the update strategy.</li>
414
	 * <li>The {@link Constraints#createValidator() validator} of the
415
	 * {@link #beforeSetModelConstraints() before-set model constraints} is set
416
	 * as the {@link UpdateValueStrategy#setBeforeSetValidator(IValidator)
417
	 * before-set validator} of the update strategy.</li>
418
	 * </ul>
419
	 * </p>
420
	 * 
421
	 * @param updateStrategy
422
	 *            The {@link UpdateValueStrategy} to configure.
423
	 * @return The passed-in, configured target-to-model
424
	 *         {@link UpdateValueStrategy}.
425
	 * 
426
	 * @see UpdateValueStrategy#setAfterGetValidator(IValidator)
427
	 * @see UpdateValueStrategy#setConverter(IConverter)
428
	 * @see UpdateValueStrategy#setAfterConvertValidator(IValidator)
429
	 * @see UpdateValueStrategy#setBeforeSetValidator(IValidator)
430
	 */
431
	public final UpdateValueStrategy adaptT2MValueStrategy(
432
			UpdateValueStrategy updateStrategy) {
433
		updateStrategy.setAfterGetValidator(createValidator(targetConstraints));
434
		updateStrategy.setConverter(targetConverter);
435
		updateStrategy
436
				.setAfterConvertValidator(createValidator(modelConstraints));
437
		updateStrategy
438
				.setBeforeSetValidator(createValidator(beforeSetModelConstraints));
439
		return updateStrategy;
440
	}
441
442
	/**
443
	 * Configures an existing model-to-target {@link UpdateValueStrategy} with
444
	 * the current state of this editing object by setting the
445
	 * {@link #setModelConverter(IConverter) model converter} as the
446
	 * {@link UpdateValueStrategy#setConverter(IConverter) converter} of the
447
	 * update strategy.
448
	 * 
449
	 * @param updateStrategy
450
	 *            The {@link UpdateValueStrategy} to configure.
451
	 * @return The passed-in, configured model-to-target
452
	 *         {@link UpdateValueStrategy}.
453
	 * 
454
	 * @see UpdateValueStrategy#setConverter(IConverter)
455
	 */
456
	public final UpdateValueStrategy adaptM2TValueStrategy(
457
			UpdateValueStrategy updateStrategy) {
458
		updateStrategy.setConverter(modelConverter);
459
		return updateStrategy;
460
	}
461
462
	/**
463
	 * Configures an existing target-to-model {@link UpdateListStrategy} with
464
	 * the current state of this editing object by setting the
465
	 * {@link #setTargetConverter(IConverter) target converter} as the
466
	 * {@link UpdateListStrategy#setConverter(IConverter) converter} of the
467
	 * update strategy.
468
	 * 
469
	 * @param updateStrategy
470
	 *            The {@link UpdateListStrategy} to configure.
471
	 * @return The passed-in, configured target-to-model
472
	 *         {@link UpdateListStrategy}.
473
	 * 
474
	 * @see UpdateListStrategy#setConverter(IConverter)
475
	 */
476
	public final UpdateListStrategy adaptT2MListStrategy(
477
			UpdateListStrategy updateStrategy) {
478
		updateStrategy.setConverter(targetConverter);
479
		return updateStrategy;
480
	}
481
482
	/**
483
	 * Configures an existing model-to-target {@link UpdateListStrategy} with
484
	 * the current state of this editing object by setting the
485
	 * {@link #setModelConverter(IConverter) model converter} as the
486
	 * {@link UpdateListStrategy#setConverter(IConverter) converter} of the
487
	 * update strategy.
488
	 * 
489
	 * @param updateStrategy
490
	 *            The {@link UpdateListStrategy} to configure.
491
	 * @return The passed-in, configured model-to-target
492
	 *         {@link UpdateListStrategy}.
493
	 * 
494
	 * @see UpdateListStrategy#setConverter(IConverter)
495
	 */
496
	public final UpdateListStrategy adaptM2TListStrategy(
497
			UpdateListStrategy updateStrategy) {
498
		updateStrategy.setConverter(modelConverter);
499
		return updateStrategy;
500
	}
501
502
	/**
503
	 * Configures an existing target-to-model {@link UpdateListStrategy} with
504
	 * the current state of this editing object by setting the
505
	 * {@link #setTargetConverter(IConverter) target converter} as the
506
	 * {@link UpdateSetStrategy#setConverter(IConverter) converter} of the
507
	 * update strategy.
508
	 * 
509
	 * @param updateStrategy
510
	 *            The {@link UpdateSetStrategy} to configure.
511
	 * @return The passed-in, configured target-to-model
512
	 *         {@link UpdateSetStrategy}.
513
	 * 
514
	 * @see UpdateSetStrategy#setConverter(IConverter)
515
	 */
516
	public final UpdateSetStrategy adaptT2MSetStrategy(
517
			UpdateSetStrategy updateStrategy) {
518
		updateStrategy.setConverter(targetConverter);
519
		return updateStrategy;
520
	}
521
522
	/**
523
	 * Configures an existing model-to-target {@link UpdateSetStrategy} with the
524
	 * current state of this editing object by setting the
525
	 * {@link #setModelConverter(IConverter) model converter} as the
526
	 * {@link UpdateSetStrategy#setConverter(IConverter) converter} of the
527
	 * update strategy.
528
	 * 
529
	 * @param updateStrategy
530
	 *            The {@link UpdateSetStrategy} to configure.
531
	 * @return The passed-in, configured model-to-target
532
	 *         {@link UpdateSetStrategy}.
533
	 * 
534
	 * @see UpdateSetStrategy#setConverter(IConverter)
535
	 */
536
	public final UpdateSetStrategy adaptM2TSetStrategy(
537
			UpdateSetStrategy updateStrategy) {
538
		updateStrategy.setConverter(modelConverter);
539
		return updateStrategy;
540
	}
541
542
	/**
543
	 * Converts a target value to a model value by performing the following
544
	 * steps:
545
	 * <ul>
546
	 * <li>
547
	 * Applying all the {@link #targetConstraints() target constraints} to the
548
	 * given target value.</li>
549
	 * <li>
550
	 * {@link #setTargetConverter(IConverter) Converting} the target value to
551
	 * the model value.</li>
552
	 * <li>
553
	 * Applying all the {@link #modelConstraints() model constraints} to the
554
	 * converted model value.</li>
555
	 * <li>
556
	 * Applying all the {@link #beforeSetModelConstraints() before-set model
557
	 * constraints} to the converted model value.</li>
558
	 * </ul>
559
	 * 
560
	 * <p>
561
	 * The conversion process will be aborted by returning <code>null</code>
562
	 * whenever any of the applied validators produces a {@link IStatus
563
	 * validation status} having {@link IStatus#getSeverity() severity}
564
	 * <code>IStatus.ERROR</code> or <code>IStatus.CANCEL</code>. During the
565
	 * conversion process, any validation status whose severity is different
566
	 * from <code>IStatus.OK</code> will be {@link MultiStatus#merge(IStatus)
567
	 * aggregated} on the given <code>validationStatus</code>.
568
	 * </p>
569
	 * 
570
	 * @param targetValue
571
	 *            The target value to be converted to a model value.
572
	 * @param validationStatus
573
	 *            Aggregate validation status to which to add the validations
574
	 *            produced during the conversion process. May be
575
	 *            <code>null</code>.
576
	 * @return The converted model value or <code>null</code> in case the
577
	 *         conversion has been aborted due to a validation error.
578
	 */
579
	public final Object convertToModel(Object targetValue,
580
			MultiStatus validationStatus) {
581
		if (!applyConstraints(targetConstraints, targetValue, validationStatus)) {
582
			return null;
583
		}
584
585
		Object modelValue = (targetConverter != null) ? targetConverter
586
				.convert(targetValue) : targetValue;
587
588
		if (!applyConstraints(modelConstraints, modelValue, validationStatus)) {
589
			return null;
590
		}
591
592
		if (!applyConstraints(beforeSetModelConstraints, modelValue,
593
				validationStatus)) {
594
			return null;
595
		}
596
597
		return modelValue;
598
	}
599
600
	/**
601
	 * {@link #setModelConverter(IConverter) Converts} a model value to a target
602
	 * value.
603
	 * 
604
	 * @param modelValue
605
	 *            The model value to be converted to a target value.
606
	 * @return The converted target value.
607
	 */
608
	public final Object convertToTarget(Object modelValue) {
609
		return (modelConverter != null) ? modelConverter.convert(modelValue)
610
				: modelValue;
611
	}
612
613
	/**
614
	 * Creates a binding between a target and model observable value on the
615
	 * given binding context by creating new update strategies which will be
616
	 * both configured with the state of this editing object before passing them
617
	 * to the binding.
618
	 * 
619
	 * <p>
620
	 * The target-to-model and model-to-target update strategies for the binding
621
	 * will be created by the methods {@link #createT2MValueStrategy()} and
622
	 * {@link #createM2TValueStrategy()}, respectively.
623
	 * </p>
624
	 * 
625
	 * @param dbc
626
	 *            The binding context on which to create the value binding.
627
	 * @param targetObservableValue
628
	 *            The target observable value of the binding.
629
	 * @param modelObservableValue
630
	 *            The model observable value of the binding.
631
	 * @return The new value binding.
632
	 * 
633
	 * @see #createT2MValueStrategy()
634
	 * @see #createM2TValueStrategy()
635
	 * @see DataBindingContext#bindValue(IObservableValue, IObservableValue,
636
	 *      UpdateValueStrategy, UpdateValueStrategy)
637
	 */
638
	public final Binding bindValue(DataBindingContext dbc,
639
			IObservableValue targetObservableValue,
640
			IObservableValue modelObservableValue) {
641
		return dbc.bindValue(targetObservableValue, modelObservableValue,
642
				createT2MValueStrategy(), createM2TValueStrategy());
643
	}
644
645
	/**
646
	 * Creates a binding between a target and model observable value on the
647
	 * given binding context by creating new update strategies with the provided
648
	 * update policies which will be both configured with the state of this
649
	 * editing object before passing them to the binding.
650
	 * 
651
	 * @param dbc
652
	 *            The binding context on which to create the value binding.
653
	 * @param targetObservableValue
654
	 *            The target observable value of the binding.
655
	 * @param modelObservableValue
656
	 *            The model observable value of the binding.
657
	 * @param t2mUpdatePolicy
658
	 *            The update policy for the target-to-model
659
	 *            {@link UpdateValueStrategy} which is
660
	 *            {@link #createT2MValueStrategy(int) created} and passed to the
661
	 *            new binding.
662
	 * @param m2tUpdatePolicy
663
	 *            The update policy for the model-to-target
664
	 *            {@link UpdateValueStrategy} which is
665
	 *            {@link #createM2TValueStrategy(int) created} and passed to the
666
	 *            new binding.
667
	 * @return The new value binding.
668
	 * 
669
	 * @see #createT2MValueStrategy(int)
670
	 * @see #createM2TValueStrategy(int)
671
	 * @see DataBindingContext#bindValue(IObservableValue, IObservableValue,
672
	 *      UpdateValueStrategy, UpdateValueStrategy)
673
	 */
674
	public final Binding bindValue(DataBindingContext dbc,
675
			IObservableValue targetObservableValue,
676
			IObservableValue modelObservableValue, int t2mUpdatePolicy,
677
			int m2tUpdatePolicy) {
678
		return dbc.bindValue(targetObservableValue, modelObservableValue,
679
				createT2MValueStrategy(t2mUpdatePolicy),
680
				createM2TValueStrategy(m2tUpdatePolicy));
681
	}
682
683
	/**
684
	 * Creates a binding between a target and model observable value on the
685
	 * given binding context by using the provided update strategies which will
686
	 * be both configured with the state of this editing object before passing
687
	 * them to the binding.
688
	 * 
689
	 * @param dbc
690
	 *            The binding context on which to create the value binding.
691
	 * @param targetObservableValue
692
	 *            The target observable value of the binding.
693
	 * @param modelObservableValue
694
	 *            The model observable value of the binding.
695
	 * @param t2mUpdateStrategy
696
	 *            The target-to-model {@link UpdateValueStrategy} of the binding
697
	 *            to be {@link #adaptT2MValueStrategy(UpdateValueStrategy)
698
	 *            configured} with the state of this editing object before
699
	 *            passing it to the binding.
700
	 * @param m2tUpdateStrategy
701
	 *            The model-to-target {@link UpdateValueStrategy} of the binding
702
	 *            to be {@link #adaptM2TValueStrategy(UpdateValueStrategy)
703
	 *            configured} with the state of this editing object before
704
	 *            passing it to the binding.
705
	 * @return The new value binding.
706
	 * 
707
	 * @see #adaptT2MValueStrategy(UpdateValueStrategy)
708
	 * @see #adaptM2TValueStrategy(UpdateValueStrategy)
709
	 * @see DataBindingContext#bindValue(IObservableValue, IObservableValue,
710
	 *      UpdateValueStrategy, UpdateValueStrategy)
711
	 */
712
	public final Binding bindValue(DataBindingContext dbc,
713
			IObservableValue targetObservableValue,
714
			IObservableValue modelObservableValue,
715
			UpdateValueStrategy t2mUpdateStrategy,
716
			UpdateValueStrategy m2tUpdateStrategy) {
717
		return dbc.bindValue(targetObservableValue, modelObservableValue,
718
				adaptT2MValueStrategy(t2mUpdateStrategy),
719
				adaptM2TValueStrategy(m2tUpdateStrategy));
720
	}
721
722
	/**
723
	 * Creates a binding between a target and model observable list on the given
724
	 * binding context by creating new update strategies which will be both
725
	 * configured with the state of this editing object before passing them to
726
	 * the binding.
727
	 * 
728
	 * <p>
729
	 * The target-to-model and model-to-target update strategies for the binding
730
	 * will be created by the methods {@link #createT2MListStrategy()} and
731
	 * {@link #createM2TListStrategy()}, respectively.
732
	 * </p>
733
	 * 
734
	 * @param dbc
735
	 *            The binding context on which to create the list binding.
736
	 * @param targetObservableList
737
	 *            The target observable list of the binding.
738
	 * @param modelObservableList
739
	 *            The model observable list of the binding.
740
	 * @return The new list binding.
741
	 * 
742
	 * @see #createT2MListStrategy()
743
	 * @see #createM2TListStrategy()
744
	 * @see DataBindingContext#bindList(IObservableList, IObservableList,
745
	 *      UpdateListStrategy, UpdateListStrategy)
746
	 */
747
	public final Binding bindList(DataBindingContext dbc,
748
			IObservableList targetObservableList,
749
			IObservableList modelObservableList) {
750
		return dbc.bindList(targetObservableList, modelObservableList,
751
				createT2MListStrategy(), createM2TListStrategy());
752
	}
753
754
	/**
755
	 * Creates a binding between a target and model observable list on the given
756
	 * binding context by creating new update strategies with the provided
757
	 * update policies which will be both configured with the state of this
758
	 * editing object before passing them to the binding.
759
	 * 
760
	 * @param dbc
761
	 *            The binding context on which to create the list binding.
762
	 * @param targetObservableList
763
	 *            The target observable list of the binding.
764
	 * @param modelObservableList
765
	 *            The model observable list of the binding.
766
	 * @param t2mUpdatePolicy
767
	 *            The update policy for the target-to-model
768
	 *            {@link UpdateListStrategy} which is
769
	 *            {@link #createT2MListStrategy(int) created} and passed to the
770
	 *            new binding.
771
	 * @param m2tUpdatePolicy
772
	 *            The update policy for the model-to-target
773
	 *            {@link UpdateListStrategy} which is
774
	 *            {@link #createM2TListStrategy(int) created} and passed to the
775
	 *            new binding.
776
	 * @return The new list binding.
777
	 * 
778
	 * @see #createT2MListStrategy(int)
779
	 * @see #createM2TListStrategy(int)
780
	 * @see DataBindingContext#bindList(IObservableList, IObservableList,
781
	 *      UpdateListStrategy, UpdateListStrategy)
782
	 */
783
	public final Binding bindList(DataBindingContext dbc,
784
			IObservableList targetObservableList,
785
			IObservableList modelObservableList, int t2mUpdatePolicy,
786
			int m2tUpdatePolicy) {
787
		return dbc.bindList(targetObservableList, modelObservableList,
788
				createT2MListStrategy(t2mUpdatePolicy),
789
				createM2TListStrategy(m2tUpdatePolicy));
790
	}
791
792
	/**
793
	 * Creates a binding between a target and model observable list on the given
794
	 * binding context by using the provided update strategies which will be
795
	 * both configured with the state of this editing object before passing them
796
	 * to the binding.
797
	 * 
798
	 * @param dbc
799
	 *            The binding context on which to create the list binding.
800
	 * @param targetObservableList
801
	 *            The target observable list of the binding.
802
	 * @param modelObservableList
803
	 *            The model observable list of the binding.
804
	 * @param t2mUpdateStrategy
805
	 *            The target-to-model {@link UpdateListStrategy} of the binding
806
	 *            to be {@link #adaptT2MListStrategy(UpdateListStrategy)
807
	 *            configured} with the state of this editing object before
808
	 *            passing it to the binding.
809
	 * @param m2tUpdateStrategy
810
	 *            The model-to-target {@link UpdateListStrategy} of the binding
811
	 *            to be {@link #adaptM2TListStrategy(UpdateListStrategy)
812
	 *            configured} with the state of this editing object before
813
	 *            passing it to the binding.
814
	 * @return The new list binding.
815
	 * 
816
	 * @see #adaptT2MListStrategy(UpdateListStrategy)
817
	 * @see #adaptM2TListStrategy(UpdateListStrategy)
818
	 * @see DataBindingContext#bindList(IObservableList, IObservableList,
819
	 *      UpdateListStrategy, UpdateListStrategy)
820
	 */
821
	public final Binding bindList(DataBindingContext dbc,
822
			IObservableList targetObservableList,
823
			IObservableList modelObservableList,
824
			UpdateListStrategy t2mUpdateStrategy,
825
			UpdateListStrategy m2tUpdateStrategy) {
826
		return dbc.bindList(targetObservableList, modelObservableList,
827
				adaptT2MListStrategy(t2mUpdateStrategy),
828
				adaptM2TListStrategy(m2tUpdateStrategy));
829
	}
830
831
	/**
832
	 * Creates a binding between a target and model observable set on the given
833
	 * binding context by creating new update strategies which will be both
834
	 * configured with the state of this editing object before passing them to
835
	 * the binding.
836
	 * 
837
	 * <p>
838
	 * The target-to-model and model-to-target update strategies for the binding
839
	 * will be created by the methods {@link #createT2MSetStrategy()} and
840
	 * {@link #createM2TSetStrategy()}, respectively.
841
	 * </p>
842
	 * 
843
	 * @param dbc
844
	 *            The binding context on which to create the set binding.
845
	 * @param targetObservableSet
846
	 *            The target observable set of the binding.
847
	 * @param modelObservableSet
848
	 *            The model observable set of the binding.
849
	 * @return The new set binding.
850
	 * 
851
	 * @see #createT2MSetStrategy()
852
	 * @see #createM2TSetStrategy()
853
	 * @see DataBindingContext#bindSet(IObservableSet, IObservableSet,
854
	 *      UpdateSetStrategy, UpdateSetStrategy)
855
	 */
856
	public final Binding bindSet(DataBindingContext dbc,
857
			IObservableSet targetObservableSet,
858
			IObservableSet modelObservableSet) {
859
		return dbc.bindSet(targetObservableSet, modelObservableSet,
860
				createT2MSetStrategy(), createM2TSetStrategy());
861
	}
862
863
	/**
864
	 * Creates a binding between a target and model observable set on the given
865
	 * binding context by creating new update strategies with the provided
866
	 * update policies which will be both configured with the state of this
867
	 * editing object before passing them to the binding.
868
	 * 
869
	 * @param dbc
870
	 *            The binding context on which to create the set binding.
871
	 * @param targetObservableSet
872
	 *            The target observable set of the binding.
873
	 * @param modelObservableSet
874
	 *            The model observable set of the binding.
875
	 * @param t2mUpdatePolicy
876
	 *            The update policy for the target-to-model
877
	 *            {@link UpdateSetStrategy} which is
878
	 *            {@link #createT2MSetStrategy(int) created} and passed to the
879
	 *            new binding.
880
	 * @param m2tUpdatePolicy
881
	 *            The update policy for the model-to-target
882
	 *            {@link UpdateSetStrategy} which is
883
	 *            {@link #createM2TSetStrategy(int) created} and passed to the
884
	 *            new binding.
885
	 * @return The new set binding.
886
	 * 
887
	 * @see #createT2MSetStrategy(int)
888
	 * @see #createM2TSetStrategy(int)
889
	 * @see DataBindingContext#bindSet(IObservableSet, IObservableSet,
890
	 *      UpdateSetStrategy, UpdateSetStrategy)
891
	 */
892
	public final Binding bindSet(DataBindingContext dbc,
893
			IObservableSet targetObservableSet,
894
			IObservableSet modelObservableSet, int t2mUpdatePolicy,
895
			int m2tUpdatePolicy) {
896
		return dbc.bindSet(targetObservableSet, modelObservableSet,
897
				createT2MSetStrategy(t2mUpdatePolicy),
898
				createM2TSetStrategy(m2tUpdatePolicy));
899
	}
900
901
	/**
902
	 * Creates a binding between a target and model observable set on the given
903
	 * binding context by using the provided update strategies which will be
904
	 * both configured with the state of this editing object before passing them
905
	 * to the binding.
906
	 * 
907
	 * @param dbc
908
	 *            The binding context on which to create the set binding.
909
	 * @param targetObservableSet
910
	 *            The target observable set of the binding.
911
	 * @param modelObservableSet
912
	 *            The model observable set of the binding.
913
	 * @param t2mUpdateStrategy
914
	 *            The target-to-model {@link UpdateSetStrategy} of the binding
915
	 *            to be {@link #adaptT2MSetStrategy(UpdateSetStrategy)
916
	 *            configured} with the state of this editing object before
917
	 *            passing it to the binding.
918
	 * @param m2tUpdateStrategy
919
	 *            The model-to-target {@link UpdateSetStrategy} of the binding
920
	 *            to be {@link #adaptM2TSetStrategy(UpdateSetStrategy)
921
	 *            configured} with the state of this editing object before
922
	 *            passing it to the binding.
923
	 * @return The new set binding.
924
	 * 
925
	 * @see #adaptT2MSetStrategy(UpdateSetStrategy)
926
	 * @see #adaptM2TSetStrategy(UpdateSetStrategy)
927
	 * @see DataBindingContext#bindSet(IObservableSet, IObservableSet,
928
	 *      UpdateSetStrategy, UpdateSetStrategy)
929
	 */
930
	public final Binding bindSet(DataBindingContext dbc,
931
			IObservableSet targetObservableSet,
932
			IObservableSet modelObservableSet,
933
			UpdateSetStrategy t2mUpdateStrategy,
934
			UpdateSetStrategy m2tUpdateStrategy) {
935
		return dbc.bindSet(targetObservableSet, modelObservableSet,
936
				adaptT2MSetStrategy(t2mUpdateStrategy),
937
				adaptM2TSetStrategy(m2tUpdateStrategy));
938
	}
939
940
	private static IValidator createValidator(Constraints constraints) {
941
		return constraints != null ? constraints.createValidator() : null;
942
	}
943
944
	private static boolean applyConstraints(Constraints constraints,
945
			Object value, MultiStatus aggregateStatus) {
946
		IValidator validator = createValidator(constraints);
947
		if (validator != null) {
948
			IStatus validationStatus = validator.validate(value);
949
			if (aggregateStatus != null && !validationStatus.isOK()) {
950
				aggregateStatus.merge(validationStatus);
951
			}
952
			return isValid(validationStatus);
953
		}
954
		return true;
955
	}
956
957
	private static boolean isValid(IStatus status) {
958
		return status.isOK() || status.matches(IStatus.INFO | IStatus.WARNING);
959
	}
960
}
(-)src/org/eclipse/core/databinding/validation/constraint/StringConstraints.java (+272 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import java.util.regex.Pattern;
15
16
import org.eclipse.core.internal.databinding.validation.NonEmptyStringValidator;
17
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
18
import org.eclipse.core.internal.databinding.validation.StringLengthValidator;
19
import org.eclipse.core.internal.databinding.validation.StringRegexValidator;
20
21
import com.ibm.icu.text.NumberFormat;
22
23
/**
24
 * Provides a set of constraints to apply to <code>String</code>s.
25
 * 
26
 * <p>
27
 * Instances of this class can be used to define a set of constraints to apply
28
 * to strings. In addition, the validation messages to be issued for the
29
 * individual constraints as well as the way in which model objects are
30
 * formatted in the validation messages can be configured.
31
 * </p>
32
 * 
33
 * @noextend This class is not intended to be subclassed by clients.
34
 * @since 1.3
35
 */
36
public class StringConstraints extends Constraints {
37
38
	private NumberFormat lengthFormat = NumberFormat.getIntegerInstance();
39
40
	private String requiredMessage = null;
41
42
	private String nonEmptyMessage = null;
43
44
	private String minLengthMessage = null;
45
46
	private String maxLengthMessage = null;
47
48
	private String lengthRangeMessage = null;
49
50
	private String matchesMessage = null;
51
52
	/**
53
	 * Adds a validator ensuring that the input integer is not <code>null</code>
54
	 * . Uses the current {@link #requiredMessage(String) validation message}.
55
	 * 
56
	 * @return This constraints instance for method chaining.
57
	 */
58
	public StringConstraints required() {
59
		addValidator(new NonNullValidator(requiredMessage));
60
		return this;
61
	}
62
63
	/**
64
	 * Sets the validation message for the {@link #required()} constraint.
65
	 * 
66
	 * @param message
67
	 *            The validation message for the {@link #required()} constraint.
68
	 * @return This constraints instance for method chaining.
69
	 * 
70
	 * @see #required()
71
	 */
72
	public StringConstraints requiredMessage(String message) {
73
		this.requiredMessage = message;
74
		return this;
75
	}
76
77
	/**
78
	 * Adds a validator ensuring that the input integer is not empty. Uses the
79
	 * current {@link #nonEmptyMessage(String) validation message}.
80
	 * 
81
	 * @return This constraints instance for method chaining.
82
	 */
83
	public StringConstraints nonEmpty() {
84
		addValidator(new NonEmptyStringValidator(nonEmptyMessage));
85
		return this;
86
	}
87
88
	/**
89
	 * Sets the validation message for the {@link #nonEmpty()} constraint.
90
	 * 
91
	 * @param message
92
	 *            The validation message for the {@link #nonEmpty()} constraint.
93
	 * @return This constraints instance for method chaining.
94
	 * 
95
	 * @see #nonEmpty()
96
	 */
97
	public StringConstraints nonEmptyMessage(String message) {
98
		this.nonEmptyMessage = message;
99
		return this;
100
	}
101
102
	/**
103
	 * Sets the format to use when formatting the string length in any of the
104
	 * validation messages stemming from a length constraint.
105
	 * 
106
	 * @param format
107
	 *            The format to use for displaying the string length in
108
	 *            validation messages stemming from a length constraint.
109
	 *            messages.
110
	 * @return This constraints instance for method chaining.
111
	 * 
112
	 * @see #minLength(int)
113
	 * @see #maxLength(int)
114
	 * @see #lengthRange(int, int)
115
	 */
116
	public StringConstraints lengthFormat(NumberFormat format) {
117
		this.lengthFormat = format;
118
		return this;
119
	}
120
121
	/**
122
	 * Adds a validator ensuring that the input string has at least the
123
	 * specified amount of characters. Uses the current
124
	 * {@link #minLengthMessage(String) validation message} and
125
	 * {@link #lengthFormat(NumberFormat) length format}.
126
	 * 
127
	 * @param minLength
128
	 *            The minimal length to be enforced on the input string.
129
	 * @return This constraints instance for method chaining.
130
	 */
131
	public StringConstraints minLength(int minLength) {
132
		addValidator(StringLengthValidator.min(minLength, minLengthMessage,
133
				lengthFormat));
134
		return this;
135
	}
136
137
	/**
138
	 * Sets the validation message pattern for the {@link #minLength(int)}
139
	 * constraint.
140
	 * 
141
	 * @param message
142
	 *            The validation message pattern for the {@link #minLength(int)}
143
	 *            constraint. Can be parameterized with the minimum string
144
	 *            length ({0}).
145
	 * @return This constraints instance for method chaining.
146
	 * 
147
	 * @see #minLength(int)
148
	 */
149
	public StringConstraints minLengthMessage(String message) {
150
		this.minLengthMessage = message;
151
		return this;
152
	}
153
154
	/**
155
	 * Adds a validator ensuring that the input string has not more than the
156
	 * specified amount of characters. Uses the current
157
	 * {@link #maxLengthMessage(String) validation message} and
158
	 * {@link #lengthFormat(NumberFormat) length format}.
159
	 * 
160
	 * @param maxLength
161
	 *            The maximum length to be enforced on the input string.
162
	 * @return This constraints instance for method chaining.
163
	 */
164
	public StringConstraints maxLength(int maxLength) {
165
		addValidator(StringLengthValidator.max(maxLength, maxLengthMessage,
166
				lengthFormat));
167
		return this;
168
	}
169
170
	/**
171
	 * Sets the validation message pattern for the {@link #maxLength(int)}
172
	 * constraint.
173
	 * 
174
	 * @param message
175
	 *            The validation message pattern for the {@link #maxLength(int)}
176
	 *            constraint. Can be parameterized with the maximum string
177
	 *            length ({0}).
178
	 * @return This constraints instance for method chaining.
179
	 * 
180
	 * @see #maxLength(int)
181
	 */
182
	public StringConstraints maxLengthMessage(String message) {
183
		this.maxLengthMessage = message;
184
		return this;
185
	}
186
187
	/**
188
	 * Adds a validator ensuring that the length of the input string is between
189
	 * the given bounds. Uses the current {@link #lengthRangeMessage(String)
190
	 * validation message} and {@link #lengthFormat(NumberFormat) length format}
191
	 * .
192
	 * 
193
	 * @param minLength
194
	 *            The minimal length to be enforced on the input string.
195
	 * @param maxLength
196
	 *            The maximum length to be enforced on the input string.
197
	 * @return This constraints instance for method chaining.
198
	 */
199
	public StringConstraints lengthRange(int minLength, int maxLength) {
200
		addValidator(StringLengthValidator.range(minLength, maxLength,
201
				lengthRangeMessage, lengthFormat));
202
		return this;
203
	}
204
205
	/**
206
	 * Sets the validation message pattern for the
207
	 * {@link #lengthRange(int, int)} constraint.
208
	 * 
209
	 * @param message
210
	 *            The validation message pattern for the
211
	 *            {@link #lengthRange(int, int)} constraint. Can be
212
	 *            parameterized with the minimum ({0}) and maximum ({1}) string
213
	 *            lengths.
214
	 * @return This constraints instance for method chaining.
215
	 * 
216
	 * @see #lengthRange(int, int)
217
	 */
218
	public StringConstraints lengthRangeMessage(String message) {
219
		this.lengthRangeMessage = message;
220
		return this;
221
	}
222
223
	/**
224
	 * Adds a validator ensuring that the input string
225
	 * {@link Pattern#matches(String, CharSequence) matches} the given regular
226
	 * expression. Uses the current {@link #matchesMessage(String) validation
227
	 * message}.
228
	 * 
229
	 * @param regex
230
	 *            The regular expression which the input string must match.
231
	 * @return This constraints instance for method chaining.
232
	 * 
233
	 * @see Pattern#matches(String, CharSequence)
234
	 */
235
	public StringConstraints matches(String regex) {
236
		addValidator(new StringRegexValidator(regex, matchesMessage));
237
		return this;
238
	}
239
240
	/**
241
	 * Adds a validator ensuring that the input string
242
	 * {@link Pattern#matches(String, CharSequence) matches} the given pattern.
243
	 * Uses the current {@link #matchesMessage(String) validation message}.
244
	 * 
245
	 * @param pattern
246
	 *            The pattern which the input string must match.
247
	 * @return This constraints instance for method chaining.
248
	 * 
249
	 * @see Pattern#matches(String, CharSequence)
250
	 */
251
	public StringConstraints matches(Pattern pattern) {
252
		addValidator(new StringRegexValidator(pattern, matchesMessage));
253
		return this;
254
	}
255
256
	/**
257
	 * Sets the validation message pattern for the {@link #matches(String)}
258
	 * constraint.
259
	 * 
260
	 * @param message
261
	 *            The validation message pattern for the
262
	 *            {@link #matches(String)} constraint. Can be parameterized with
263
	 *            the pattern string ({0}) which the input integer must match.
264
	 * @return This constraints instance for method chaining.
265
	 * 
266
	 * @see #matches(String)
267
	 */
268
	public StringConstraints matchesMessage(String message) {
269
		this.matchesMessage = message;
270
		return this;
271
	}
272
}
(-)src/org/eclipse/core/internal/databinding/validation/DecimalScaleValidator.java (+99 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.text.MessageFormat;
15
16
import org.eclipse.core.databinding.validation.IValidator;
17
import org.eclipse.core.databinding.validation.ValidationStatus;
18
import org.eclipse.core.internal.databinding.BindingMessages;
19
import org.eclipse.core.runtime.IStatus;
20
21
import com.ibm.icu.math.BigDecimal;
22
import com.ibm.icu.text.NumberFormat;
23
24
/**
25
 * Provides validations for the scale of decimal numbers.
26
 * 
27
 * @since 1.3
28
 */
29
public class DecimalScaleValidator implements IValidator {
30
31
	private static final String MAX_SCALE_VALIDATION_MESSAGE = BindingMessages
32
			.getString(BindingMessages.VALIDATE_DECIMAL_MAX_SCALE);
33
34
	private final int maxScale;
35
36
	private final String validationMessage;
37
38
	private String formattedValidationMessage;
39
40
	private final NumberFormat scaleFormat;
41
42
	private DecimalScaleValidator(int maxScale, String validationMessage,
43
			NumberFormat scaleFormat) {
44
		this.maxScale = maxScale;
45
		this.validationMessage = validationMessage != null ? validationMessage
46
				: MAX_SCALE_VALIDATION_MESSAGE;
47
		this.scaleFormat = scaleFormat;
48
	}
49
50
	/**
51
	 * Creates a validator which checks that an input decimal has a scale which
52
	 * is less or equal to the given scale.
53
	 * 
54
	 * @param maxScale
55
	 *            The maximum scale to enforce on the input decimal.
56
	 * @param validationMessage
57
	 *            The validation message pattern to use. Can be parameterized
58
	 *            with the maximum scale to be enforced.
59
	 * @param scaleFormat
60
	 *            The display format to use for formatting the scale in the
61
	 *            validation message.
62
	 * @return The validator instance.
63
	 */
64
	public static DecimalScaleValidator max(int maxScale,
65
			String validationMessage, NumberFormat scaleFormat) {
66
		return new DecimalScaleValidator(maxScale, validationMessage,
67
				scaleFormat);
68
	}
69
70
	public IStatus validate(Object value) {
71
		if (value != null) {
72
			Number number = (Number) value;
73
			final int scale;
74
			if (number instanceof BigDecimal) {
75
				scale = ((BigDecimal) number).scale();
76
			} else {
77
				scale = new BigDecimal(number.doubleValue()).scale();
78
			}
79
			if (scale > maxScale) {
80
				return ValidationStatus.error(getFormattedValidationMessage());
81
			}
82
		}
83
		return ValidationStatus.ok();
84
	}
85
86
	private synchronized String getFormattedValidationMessage() {
87
		if (formattedValidationMessage == null) {
88
			formattedValidationMessage = MessageFormat.format(
89
					validationMessage, getValidationMessageArguments());
90
		}
91
		return formattedValidationMessage;
92
	}
93
94
	private String[] getValidationMessageArguments() {
95
		synchronized (scaleFormat) {
96
			return new String[] { scaleFormat.format(new Integer(maxScale)) };
97
		}
98
	}
99
}
(-)src/org/eclipse/core/databinding/editing/IntegerEditing.java (+463 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.conversion.NumberToStringConverter;
15
import org.eclipse.core.databinding.conversion.StringToNumberConverter;
16
import org.eclipse.core.databinding.validation.constraint.Constraints;
17
import org.eclipse.core.databinding.validation.constraint.IntegerConstraints;
18
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
19
import org.eclipse.core.internal.databinding.validation.AbstractStringToNumberValidator;
20
import org.eclipse.core.internal.databinding.validation.StringToByteValidator;
21
import org.eclipse.core.internal.databinding.validation.StringToIntegerValidator;
22
import org.eclipse.core.internal.databinding.validation.StringToLongValidator;
23
import org.eclipse.core.internal.databinding.validation.StringToShortValidator;
24
25
import com.ibm.icu.text.NumberFormat;
26
27
/**
28
 * @noextend This class is not intended to be subclassed by clients.
29
 * @since 1.3
30
 */
31
public class IntegerEditing extends Editing {
32
33
	private final NumberFormat displayFormat;
34
35
	/**
36
	 * Creates a new editing object for integer numbers.
37
	 * 
38
	 * @param format
39
	 *            The integer format defining the validations and conversions
40
	 *            used for editing.
41
	 * @param parseErrorMessage
42
	 *            The validation message issued in case the input string cannot
43
	 *            be parsed to an integer.
44
	 * @param outOfRangeMessage
45
	 *            The validation message issued in case the input string
46
	 *            represents an integer whose value is out of range.
47
	 * @param integerType
48
	 *            The specific integer type for which to set up an editing
49
	 *            instance.
50
	 * 
51
	 * @noreference This constructor is not intended to be referenced by
52
	 *              clients.
53
	 */
54
	protected IntegerEditing(NumberFormat format, String parseErrorMessage,
55
			String outOfRangeMessage, Class integerType) {
56
		this.displayFormat = format;
57
58
		final StringToNumberConverter targetConverter;
59
		final NumberToStringConverter modelConverter;
60
		final AbstractStringToNumberValidator targetValidator;
61
		if (Long.class.equals(integerType)) {
62
			targetConverter = StringToNumberConverter.toLong(format, false);
63
			modelConverter = NumberToStringConverter.fromLong(format, false);
64
			targetValidator = new StringToLongValidator(targetConverter);
65
		} else if (Integer.class.equals(integerType)) {
66
			targetConverter = StringToNumberConverter.toInteger(format, false);
67
			modelConverter = NumberToStringConverter.fromInteger(format, false);
68
			targetValidator = new StringToIntegerValidator(targetConverter);
69
		} else if (Short.class.equals(integerType)) {
70
			targetConverter = StringToNumberConverter.toShort(format, false);
71
			modelConverter = NumberToStringConverter.fromShort(format, false);
72
			targetValidator = new StringToShortValidator(targetConverter);
73
		} else if (Byte.class.equals(integerType)) {
74
			targetConverter = StringToNumberConverter.toByte(format, false);
75
			modelConverter = NumberToStringConverter.fromByte(format, false);
76
			targetValidator = new StringToByteValidator(targetConverter);
77
		} else {
78
			throw new IllegalArgumentException(
79
					"Unsupported integer type: " + integerType); //$NON-NLS-1$
80
		}
81
82
		if (parseErrorMessage != null) {
83
			targetValidator.setParseErrorMessage(parseErrorMessage);
84
		}
85
		if (outOfRangeMessage != null) {
86
			targetValidator.setOutOfRangeMessage(outOfRangeMessage);
87
		}
88
89
		setTargetConverter(targetConverter);
90
		setModelConverter(modelConverter);
91
		targetConstraints().addValidator(targetValidator);
92
	}
93
94
	/**
95
	 * Creates a new editing object for {@link Long}s which defaults the
96
	 * validations and conversions used for editing based on the platform's
97
	 * locale. Uses the default validation messages.
98
	 * 
99
	 * @return The new editing object using the default validations and
100
	 *         conversions for editing.
101
	 * 
102
	 * @see NumberFormat#getIntegerInstance()
103
	 */
104
	public static IntegerEditing withLongDefaults() {
105
		return withLongDefaults(null, null);
106
	}
107
108
	/**
109
	 * Creates a new editing object for {@link Long}s which defaults the
110
	 * validations and conversions used for editing based on the platform's
111
	 * locale. Uses the specified custom validation messages.
112
	 * 
113
	 * @param parseErrorMessage
114
	 *            The validation message issued in case the input string cannot
115
	 *            be parsed to an integer.
116
	 * @param outOfRangeMessage
117
	 *            The validation message issued in case the input string
118
	 *            represents an integer whose value is out of range. Can be
119
	 *            parameterized by the <code>Long.MIN_VALUE</code> ({0}) and
120
	 *            <code>Long.MAX_VALUE</code> ({1}) values.
121
	 * @return The new editing object using the default validations and
122
	 *         conversions for editing.
123
	 * 
124
	 * @see NumberFormat#getIntegerInstance()
125
	 */
126
	public static IntegerEditing withLongDefaults(String parseErrorMessage,
127
			String outOfRangeMessage) {
128
		return new IntegerEditing(NumberFormat.getIntegerInstance(),
129
				parseErrorMessage, outOfRangeMessage, Long.class);
130
	}
131
132
	/**
133
	 * Creates a new editing object for {@link Long}s whose validations and
134
	 * conversions used for editing are based on the given integer format. Uses
135
	 * the default validation messages.
136
	 * 
137
	 * @param format
138
	 *            The integer format defining the validations and conversions
139
	 *            used for editing.
140
	 * @return The new editing object configured by the given integer format.
141
	 */
142
	public static IntegerEditing forLongFormat(NumberFormat format) {
143
		return forLongFormat(format, null, null);
144
	}
145
146
	/**
147
	 * Creates a new editing object for {@link Long}s whose validations and
148
	 * conversions used for editing are based on the given integer format. Uses
149
	 * the specified custom validation messages.
150
	 * 
151
	 * @param format
152
	 *            The integer format defining the validations and conversions
153
	 *            used for editing.
154
	 * @param parseErrorMessage
155
	 *            The validation message issued in case the input string cannot
156
	 *            be parsed to an integer.
157
	 * @param outOfRangeMessage
158
	 *            The validation message issued in case the input string
159
	 *            represents an integer whose value is out of range. Can be
160
	 *            parameterized by the <code>Long.MIN_VALUE</code> ({0}) and
161
	 *            <code>Long.MAX_VALUE</code> ({1}) values.
162
	 * @return The new editing object configured by the given integer format.
163
	 */
164
	public static IntegerEditing forLongFormat(NumberFormat format,
165
			String parseErrorMessage, String outOfRangeMessage) {
166
		return new IntegerEditing(format, parseErrorMessage, outOfRangeMessage,
167
				Long.class);
168
	}
169
170
	/**
171
	 * Creates a new editing object for {@link Integer}s which defaults the
172
	 * validations and conversions used for editing based on the platform's
173
	 * locale. Uses the default validation messages.
174
	 * 
175
	 * @return The new editing object using the default validations and
176
	 *         conversions for editing.
177
	 * 
178
	 * @see NumberFormat#getIntegerInstance()
179
	 */
180
	public static IntegerEditing withIntegerDefaults() {
181
		return withIntegerDefaults(null, null);
182
	}
183
184
	/**
185
	 * Creates a new editing object for {@link Integer}s which defaults the
186
	 * validations and conversions used for editing based on the platform's
187
	 * locale. Uses the specified custom validation messages.
188
	 * 
189
	 * @param parseErrorMessage
190
	 *            The validation message issued in case the input string cannot
191
	 *            be parsed to an integer.
192
	 * @param outOfRangeMessage
193
	 *            The validation message issued in case the input string
194
	 *            represents an integer whose value is out of range. Can be
195
	 *            parameterized by the <code>Integer.MIN_VALUE</code> ({0}) and
196
	 *            <code>Integer.MAX_VALUE</code> ({1}) values.
197
	 * @return The new editing object using the default validations and
198
	 *         conversions for editing.
199
	 * 
200
	 * @see NumberFormat#getIntegerInstance()
201
	 */
202
	public static IntegerEditing withIntegerDefaults(String parseErrorMessage,
203
			String outOfRangeMessage) {
204
		return new IntegerEditing(NumberFormat.getIntegerInstance(),
205
				parseErrorMessage, outOfRangeMessage, Integer.class);
206
	}
207
208
	/**
209
	 * Creates a new editing object for {@link Integer}s whose validations and
210
	 * conversions used for editing are based on the given integer format. Uses
211
	 * the default validation messages.
212
	 * 
213
	 * @param format
214
	 *            The integer format defining the validations and conversions
215
	 *            used for editing.
216
	 * @return The new editing object configured by the given integer format.
217
	 */
218
	public static IntegerEditing forIntegerFormat(NumberFormat format) {
219
		return forIntegerFormat(format, null, null);
220
	}
221
222
	/**
223
	 * Creates a new editing object for {@link Integer}s whose validations and
224
	 * conversions used for editing are based on the given integer format. Uses
225
	 * the specified custom validation messages.
226
	 * 
227
	 * @param format
228
	 *            The integer format defining the validations and conversions
229
	 *            used for editing.
230
	 * @param parseErrorMessage
231
	 *            The validation message issued in case the input string cannot
232
	 *            be parsed to an integer.
233
	 * @param outOfRangeMessage
234
	 *            The validation message issued in case the input string
235
	 *            represents an integer whose value is out of range. Can be
236
	 *            parameterized by the <code>Integer.MIN_VALUE</code> ({0}) and
237
	 *            <code>Integer.MAX_VALUE</code> ({1}) values.
238
	 * @return The new editing object configured by the given integer format.
239
	 */
240
	public static IntegerEditing forIntegerFormat(NumberFormat format,
241
			String parseErrorMessage, String outOfRangeMessage) {
242
		return new IntegerEditing(format, parseErrorMessage, outOfRangeMessage,
243
				Integer.class);
244
	}
245
246
	/**
247
	 * Creates a new editing object for {@link Short}s which defaults the
248
	 * validations and conversions used for editing based on the platform's
249
	 * locale. Uses the default validation messages.
250
	 * 
251
	 * @return The new editing object using the default validations and
252
	 *         conversions for editing.
253
	 * 
254
	 * @see NumberFormat#getIntegerInstance()
255
	 */
256
	public static IntegerEditing withShortDefaults() {
257
		return withShortDefaults(null, null);
258
	}
259
260
	/**
261
	 * Creates a new editing object for {@link Short}s which defaults the
262
	 * validations and conversions used for editing based on the platform's
263
	 * locale. Uses the specified custom validation messages.
264
	 * 
265
	 * @param parseErrorMessage
266
	 *            The validation message issued in case the input string cannot
267
	 *            be parsed to an integer.
268
	 * @param outOfRangeMessage
269
	 *            The validation message issued in case the input string
270
	 *            represents an integer whose value is out of range. Can be
271
	 *            parameterized by the <code>Short.MIN_VALUE</code> ({0}) and
272
	 *            <code>Short.MAX_VALUE</code> ({1}) values.
273
	 * @return The new editing object using the default validations and
274
	 *         conversions for editing.
275
	 * 
276
	 * @see NumberFormat#getIntegerInstance()
277
	 */
278
	public static IntegerEditing withShortDefaults(String parseErrorMessage,
279
			String outOfRangeMessage) {
280
		return new IntegerEditing(NumberFormat.getIntegerInstance(),
281
				parseErrorMessage, outOfRangeMessage, Short.class);
282
	}
283
284
	/**
285
	 * Creates a new editing object for {@link Short}s whose validations and
286
	 * conversions used for editing are based on the given integer format. Uses
287
	 * the default validation messages.
288
	 * 
289
	 * @param format
290
	 *            The integer format defining the validations and conversions
291
	 *            used for editing.
292
	 * @return The new editing object configured by the given integer format.
293
	 */
294
	public static IntegerEditing forShortFormat(NumberFormat format) {
295
		return forShortFormat(format, null, null);
296
	}
297
298
	/**
299
	 * Creates a new editing object for {@link Short}s whose validations and
300
	 * conversions used for editing are based on the given integer format. Uses
301
	 * the specified custom validation messages.
302
	 * 
303
	 * @param format
304
	 *            The integer format defining the validations and conversions
305
	 *            used for editing.
306
	 * @param parseErrorMessage
307
	 *            The validation message issued in case the input string cannot
308
	 *            be parsed to an integer.
309
	 * @param outOfRangeMessage
310
	 *            The validation message issued in case the input string
311
	 *            represents an integer whose value is out of range. Can be
312
	 *            parameterized by the <code>Short.MIN_VALUE</code> ({0}) and
313
	 *            <code>Short.MAX_VALUE</code> ({1}) values.
314
	 * @return The new editing object configured by the given integer format.
315
	 */
316
	public static IntegerEditing forShortFormat(NumberFormat format,
317
			String parseErrorMessage, String outOfRangeMessage) {
318
		return new IntegerEditing(format, parseErrorMessage, outOfRangeMessage,
319
				Short.class);
320
	}
321
322
	/**
323
	 * Creates a new editing object for {@link Byte}s which defaults the
324
	 * validations and conversions used for editing based on the platform's
325
	 * locale. Uses the default validation messages.
326
	 * 
327
	 * @return The new editing object using the default validations and
328
	 *         conversions for editing.
329
	 * 
330
	 * @see NumberFormat#getIntegerInstance()
331
	 */
332
	public static IntegerEditing withByteDefaults() {
333
		return withByteDefaults(null, null);
334
	}
335
336
	/**
337
	 * Creates a new editing object for {@link Byte}s which defaults the
338
	 * validations and conversions used for editing based on the platform's
339
	 * locale. Uses the specified custom validation messages.
340
	 * 
341
	 * @param parseErrorMessage
342
	 *            The validation message issued in case the input string cannot
343
	 *            be parsed to an integer.
344
	 * @param outOfRangeMessage
345
	 *            The validation message issued in case the input string
346
	 *            represents an integer whose value is out of range. Can be
347
	 *            parameterized by the <code>Byte.MIN_VALUE</code> ({0}) and
348
	 *            <code>Byte.MAX_VALUE</code> ({1}) values.
349
	 * @return The new editing object using the default validations and
350
	 *         conversions for editing.
351
	 * 
352
	 * @see NumberFormat#getIntegerInstance()
353
	 */
354
	public static IntegerEditing withByteDefaults(String parseErrorMessage,
355
			String outOfRangeMessage) {
356
		return new IntegerEditing(NumberFormat.getIntegerInstance(),
357
				parseErrorMessage, outOfRangeMessage, Byte.class);
358
	}
359
360
	/**
361
	 * Creates a new editing object for {@link Byte}s whose validations and
362
	 * conversions used for editing are based on the given integer format. Uses
363
	 * the default validation messages.
364
	 * 
365
	 * @param format
366
	 *            The integer format defining the validations and conversions
367
	 *            used for editing.
368
	 * @return The new editing object configured by the given integer format.
369
	 */
370
	public static IntegerEditing forByteFormat(NumberFormat format) {
371
		return forByteFormat(format, null, null);
372
	}
373
374
	/**
375
	 * Creates a new editing object for {@link Byte}s whose validations and
376
	 * conversions used for editing are based on the given integer format. Uses
377
	 * the specified custom validation messages.
378
	 * 
379
	 * @param format
380
	 *            The integer format defining the validations and conversions
381
	 *            used for editing.
382
	 * @param parseErrorMessage
383
	 *            The validation message issued in case the input string cannot
384
	 *            be parsed to an integer.
385
	 * @param outOfRangeMessage
386
	 *            The validation message issued in case the input string
387
	 *            represents an integer whose value is out of range. Can be
388
	 *            parameterized by the <code>Byte.MIN_VALUE</code> ({0}) and
389
	 *            <code>Byte.MAX_VALUE</code> ({1}) values.
390
	 * @return The new editing object configured by the given integer format.
391
	 */
392
	public static IntegerEditing forByteFormat(NumberFormat format,
393
			String parseErrorMessage, String outOfRangeMessage) {
394
		return new IntegerEditing(format, parseErrorMessage, outOfRangeMessage,
395
				Byte.class);
396
	}
397
398
	/**
399
	 * Returns the target constraints to apply.
400
	 * 
401
	 * <p>
402
	 * This method provides a typesafe access to the {@link StringConstraints
403
	 * string target constraints} of this editing object and is equivalent to
404
	 * {@code (StringConstraints) targetConstraints()}.
405
	 * </p>
406
	 * 
407
	 * @return The target constraints to apply.
408
	 * 
409
	 * @see #targetConstraints()
410
	 * @see StringConstraints
411
	 */
412
	public StringConstraints targetStringConstraints() {
413
		return (StringConstraints) targetConstraints();
414
	}
415
416
	/**
417
	 * Returns the model constraints to apply.
418
	 * 
419
	 * <p>
420
	 * This method provides a typesafe access to the {@link IntegerConstraints
421
	 * integer model constraints} of this editing object and is equivalent to
422
	 * {@code (IntegerConstraints) modelConstraints()}.
423
	 * </p>
424
	 * 
425
	 * @return The model constraints to apply.
426
	 * 
427
	 * @see #modelConstraints()
428
	 * @see IntegerConstraints
429
	 */
430
	public IntegerConstraints modelIntegerConstraints() {
431
		return (IntegerConstraints) modelConstraints();
432
	}
433
434
	/**
435
	 * Returns the before-set model constraints to apply.
436
	 * 
437
	 * <p>
438
	 * This method provides a typesafe access to the {@link IntegerConstraints
439
	 * integer before-set model constraints} of this editing object and is
440
	 * equivalent to {@code (IntegerConstraints) beforeSetModelConstraints()}.
441
	 * </p>
442
	 * 
443
	 * @return The before-set model constraints to apply.
444
	 * 
445
	 * @see #beforeSetModelConstraints()
446
	 * @see IntegerConstraints
447
	 */
448
	public IntegerConstraints beforeSetModelIntegerConstraints() {
449
		return (IntegerConstraints) beforeSetModelConstraints();
450
	}
451
452
	protected Constraints createTargetConstraints() {
453
		return new StringConstraints();
454
	}
455
456
	protected Constraints createModelConstraints() {
457
		return new IntegerConstraints().integerFormat(displayFormat);
458
	}
459
460
	protected Constraints createBeforeSetModelConstraints() {
461
		return new IntegerConstraints().integerFormat(displayFormat);
462
	}
463
}
(-)src/org/eclipse/core/databinding/editing/DateEditing.java (+196 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.validation.constraint.Constraints;
15
import org.eclipse.core.databinding.validation.constraint.DateConstraints;
16
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
17
import org.eclipse.core.internal.databinding.conversion.DateToStringConverter;
18
import org.eclipse.core.internal.databinding.conversion.StringToDateConverter;
19
import org.eclipse.core.internal.databinding.validation.StringToDateValidator;
20
21
import com.ibm.icu.text.DateFormat;
22
23
/**
24
 * @noextend This class is not intended to be subclassed by clients.
25
 * @since 1.3
26
 */
27
public class DateEditing extends Editing {
28
29
	private final DateFormat displayFormat;
30
31
	/**
32
	 * Creates a new editing object for <code>Date</code>s.
33
	 * 
34
	 * @param inputFormats
35
	 *            The date formats supported for reading in dates.
36
	 * @param parseErrorMessage
37
	 *            The validation message issued in case the input string cannot
38
	 *            be parsed to a date.
39
	 * @param displayFormat
40
	 *            The date format for displaying dates.
41
	 * 
42
	 * @noreference This constructor is not intended to be referenced by
43
	 *              clients.
44
	 */
45
	protected DateEditing(DateFormat[] inputFormats, String parseErrorMessage,
46
			DateFormat displayFormat) {
47
		this.displayFormat = displayFormat;
48
49
		StringToDateConverter targetConverter = new StringToDateConverter();
50
		if (inputFormats != null) {
51
			targetConverter.setFormatters(inputFormats);
52
		}
53
54
		DateToStringConverter modelConverter = new DateToStringConverter();
55
		if (displayFormat != null) {
56
			modelConverter.setFormatters(new DateFormat[] { displayFormat });
57
		}
58
59
		StringToDateValidator targetValidator = new StringToDateValidator(
60
				targetConverter);
61
		if (parseErrorMessage != null) {
62
			targetValidator.setParseErrorMessage(parseErrorMessage);
63
		}
64
65
		setTargetConverter(targetConverter);
66
		setModelConverter(modelConverter);
67
		targetConstraints().addValidator(targetValidator);
68
	}
69
70
	/**
71
	 * Creates a new editing object which defaults the validations and
72
	 * conversions used for editing. Uses the default validation message.
73
	 * 
74
	 * @return The new editing object using the default validations and
75
	 *         conversions for editing.
76
	 */
77
	public static DateEditing withDefaults() {
78
		return withDefaults(null);
79
	}
80
81
	/**
82
	 * Creates a new editing object which defaults the validations and
83
	 * conversions used for editing. Uses the specified custom validation
84
	 * message.
85
	 * 
86
	 * @param parseErrorMessage
87
	 *            The validation message issued in case the input string cannot
88
	 *            be parsed to a date.
89
	 * @return The new editing object using the default validations and
90
	 *         conversions for editing.
91
	 */
92
	public static DateEditing withDefaults(String parseErrorMessage) {
93
		return new DateEditing(null, parseErrorMessage, null);
94
	}
95
96
	/**
97
	 * Creates a new editing object which supports all the given date input
98
	 * formats and which uses the specified format for displaying a date. Uses
99
	 * the default validation message.
100
	 * 
101
	 * @param inputFormats
102
	 *            The date formats supported for reading in dates.
103
	 * @param displayFormat
104
	 *            The date format for displaying dates.
105
	 * @return The new editing object configured by the given date formats.
106
	 */
107
	public static DateEditing forFormats(DateFormat[] inputFormats,
108
			DateFormat displayFormat) {
109
		return new DateEditing(inputFormats, null, displayFormat);
110
	}
111
112
	/**
113
	 * Creates a new editing object which supports all the given date input
114
	 * formats and which uses the specified format for displaying a date. Uses
115
	 * the specified custom validation message.
116
	 * 
117
	 * @param inputFormats
118
	 *            The date formats supported for reading in dates.
119
	 * @param parseErrorMessage
120
	 *            The validation message issued in case the input string cannot
121
	 *            be parsed to a date.
122
	 * @param displayFormat
123
	 *            The date format for displaying dates.
124
	 * @return The new editing object configured by the given date formats.
125
	 */
126
	public static DateEditing forFormats(DateFormat[] inputFormats,
127
			String parseErrorMessage, DateFormat displayFormat) {
128
		return new DateEditing(inputFormats, parseErrorMessage, displayFormat);
129
	}
130
131
	/**
132
	 * Returns the target constraints to apply.
133
	 * 
134
	 * <p>
135
	 * This method provides a typesafe access to the {@link StringConstraints
136
	 * string target constraints} of this editing object and is equivalent to
137
	 * {@code (StringConstraints) targetConstraints()}.
138
	 * </p>
139
	 * 
140
	 * @return The target constraints to apply.
141
	 * 
142
	 * @see #targetConstraints()
143
	 * @see StringConstraints
144
	 */
145
	public StringConstraints targetStringConstraints() {
146
		return (StringConstraints) targetConstraints();
147
	}
148
149
	/**
150
	 * Returns the model constraints to apply.
151
	 * 
152
	 * <p>
153
	 * This method provides a typesafe access to the {@link DateConstraints date
154
	 * model constraints} of this editing object and is equivalent to {@code
155
	 * (DateConstraints) modelConstraints()}.
156
	 * </p>
157
	 * 
158
	 * @return The model constraints to apply.
159
	 * 
160
	 * @see #modelConstraints()
161
	 * @see DateConstraints
162
	 */
163
	public DateConstraints modelDateConstraints() {
164
		return (DateConstraints) modelConstraints();
165
	}
166
167
	/**
168
	 * Returns the before-set model constraints to apply.
169
	 * 
170
	 * <p>
171
	 * This method provides a typesafe access to the {@link DateConstraints date
172
	 * before-set model constraints} of this editing object and is equivalent to
173
	 * {@code (DateConstraints) beforeSetModelConstraints()}.
174
	 * </p>
175
	 * 
176
	 * @return The before-set model constraints to apply.
177
	 * 
178
	 * @see #beforeSetModelConstraints()
179
	 * @see DateConstraints
180
	 */
181
	public DateConstraints beforeSetModelDateConstraints() {
182
		return (DateConstraints) beforeSetModelConstraints();
183
	}
184
185
	protected Constraints createTargetConstraints() {
186
		return new StringConstraints();
187
	}
188
189
	protected Constraints createModelConstraints() {
190
		return new DateConstraints().dateFormat(displayFormat);
191
	}
192
193
	protected Constraints createBeforeSetModelConstraints() {
194
		return new DateConstraints().dateFormat(displayFormat);
195
	}
196
}
(-)src/org/eclipse/core/internal/databinding/validation/StringRegexValidator.java (+83 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.text.MessageFormat;
15
import java.util.regex.Matcher;
16
import java.util.regex.Pattern;
17
18
import org.eclipse.core.databinding.validation.IValidator;
19
import org.eclipse.core.databinding.validation.ValidationStatus;
20
import org.eclipse.core.internal.databinding.BindingMessages;
21
import org.eclipse.core.runtime.IStatus;
22
23
/**
24
 * Provides validations for strings which must match a given regular expression.
25
 * 
26
 * @since 1.3
27
 */
28
public class StringRegexValidator implements IValidator {
29
30
	private static final String REGEX_VALIDATION_MESSAGE = BindingMessages
31
			.getString(BindingMessages.VALIDATE_STRING_REGEX);
32
33
	private final Pattern pattern;
34
	private final String validationMessage;
35
	private String formattedValidationMessage;
36
37
	/**
38
	 * Creates a new regex validator.
39
	 * 
40
	 * @param regex
41
	 *            The regular expression which the input string must match.
42
	 * @param validationMessage
43
	 *            The validation message pattern to use. Can be parameterized
44
	 *            with the given regular expression string.
45
	 */
46
	public StringRegexValidator(String regex, String validationMessage) {
47
		this(Pattern.compile(regex), validationMessage);
48
	}
49
50
	/**
51
	 * Creates a new regex validator.
52
	 * 
53
	 * @param pattern
54
	 *            The pattern which the input string must match.
55
	 * @param validationMessage
56
	 *            The validation message pattern to use. Can be parameterized
57
	 *            with the given regular expression string.
58
	 */
59
	public StringRegexValidator(Pattern pattern, String validationMessage) {
60
		this.pattern = pattern;
61
		this.validationMessage = validationMessage != null ? validationMessage
62
				: REGEX_VALIDATION_MESSAGE;
63
	}
64
65
	public IStatus validate(Object value) {
66
		String input = (String) value;
67
		if (input != null) {
68
			Matcher matcher = pattern.matcher(input);
69
			if (!matcher.matches()) {
70
				return ValidationStatus.error(getFormattedValidationMessage());
71
			}
72
		}
73
		return ValidationStatus.ok();
74
	}
75
76
	private synchronized String getFormattedValidationMessage() {
77
		if (formattedValidationMessage == null) {
78
			formattedValidationMessage = MessageFormat.format(
79
					validationMessage, new String[] { pattern.pattern() });
80
		}
81
		return formattedValidationMessage;
82
	}
83
}
(-)src/org/eclipse/core/databinding/editing/DecimalEditing.java (+301 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.conversion.NumberToStringConverter;
15
import org.eclipse.core.databinding.conversion.StringToNumberConverter;
16
import org.eclipse.core.databinding.validation.constraint.Constraints;
17
import org.eclipse.core.databinding.validation.constraint.DecimalConstraints;
18
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
19
import org.eclipse.core.internal.databinding.validation.AbstractStringToNumberValidator;
20
import org.eclipse.core.internal.databinding.validation.StringToDoubleValidator;
21
import org.eclipse.core.internal.databinding.validation.StringToFloatValidator;
22
23
import com.ibm.icu.text.NumberFormat;
24
25
/**
26
 * @noextend This class is not intended to be subclassed by clients.
27
 * @since 1.3
28
 */
29
public class DecimalEditing extends Editing {
30
31
	private final NumberFormat displayFormat;
32
33
	/**
34
	 * Creates a new editing object for decimal numbers.
35
	 * 
36
	 * @param format
37
	 *            The number format defining the validations and conversions
38
	 *            used for editing.
39
	 * @param parseErrorMessage
40
	 *            The validation message issued in case the input string cannot
41
	 *            be parsed to a double.
42
	 * @param outOfRangeMessage
43
	 *            The validation message issued in case the input string
44
	 *            represents a double whose value is out of range.
45
	 * @param decimalType
46
	 *            The specific decimal type for which to set up an editing
47
	 *            instance.
48
	 * 
49
	 * @noreference This constructor is not intended to be referenced by
50
	 *              clients.
51
	 */
52
	protected DecimalEditing(NumberFormat format, String parseErrorMessage,
53
			String outOfRangeMessage, Class decimalType) {
54
		this.displayFormat = format;
55
56
		final StringToNumberConverter targetConverter;
57
		final NumberToStringConverter modelConverter;
58
		final AbstractStringToNumberValidator targetValidator;
59
		if (Double.class.equals(decimalType)) {
60
			targetConverter = StringToNumberConverter.toDouble(format, false);
61
			modelConverter = NumberToStringConverter.fromDouble(format, false);
62
			targetValidator = new StringToDoubleValidator(targetConverter);
63
		} else if (Float.class.equals(decimalType)) {
64
			targetConverter = StringToNumberConverter.toFloat(format, false);
65
			modelConverter = NumberToStringConverter.fromFloat(format, false);
66
			targetValidator = new StringToFloatValidator(targetConverter);
67
		} else {
68
			throw new IllegalArgumentException(
69
					"Unsupported decimal type: " + decimalType); //$NON-NLS-1$
70
		}
71
72
		if (parseErrorMessage != null) {
73
			targetValidator.setParseErrorMessage(parseErrorMessage);
74
		}
75
		if (outOfRangeMessage != null) {
76
			targetValidator.setOutOfRangeMessage(outOfRangeMessage);
77
		}
78
79
		setTargetConverter(targetConverter);
80
		setModelConverter(modelConverter);
81
		targetConstraints().addValidator(targetValidator);
82
	}
83
84
	/**
85
	 * Creates a new editing object for {@link Double}s which defaults the
86
	 * validations and conversions used for editing based on the platform's
87
	 * locale. Uses the default validation messages.
88
	 * 
89
	 * @return The new editing object using the default validations and
90
	 *         conversions for editing.
91
	 * 
92
	 * @see NumberFormat#getNumberInstance()
93
	 */
94
	public static DecimalEditing withDoubleDefaults() {
95
		return withDoubleDefaults(null, null);
96
	}
97
98
	/**
99
	 * Creates a new editing object for {@link Double}s which defaults the
100
	 * validations and conversions used for editing based on the platform's
101
	 * locale. Uses the specified custom validation messages.
102
	 * 
103
	 * @param parseErrorMessage
104
	 *            The validation message issued in case the input string cannot
105
	 *            be parsed to a double.
106
	 * @param outOfRangeMessage
107
	 *            The validation message issued in case the input string
108
	 *            represents a double whose value is out of range. Can be
109
	 *            parameterized by the <code>-Double.MAX_VALUE</code> ({0}) and
110
	 *            <code>+Double.MAX_VALUE</code> ({1}) values.
111
	 * @return The new editing object using the default validations and
112
	 *         conversions for editing.
113
	 * 
114
	 * @see NumberFormat#getNumberInstance()
115
	 */
116
	public static DecimalEditing withDoubleDefaults(String parseErrorMessage,
117
			String outOfRangeMessage) {
118
		return new DecimalEditing(NumberFormat.getNumberInstance(),
119
				parseErrorMessage, outOfRangeMessage, Double.class);
120
	}
121
122
	/**
123
	 * Creates a new editing object for {@link Double}s whose validations and
124
	 * conversions used for editing are based on the given number format. Uses
125
	 * the default validation messages.
126
	 * 
127
	 * @param format
128
	 *            The number format defining the validations and conversions
129
	 *            used for editing.
130
	 * @return The new editing object configured by the given number format.
131
	 */
132
	public static DecimalEditing forDoubleFormat(NumberFormat format) {
133
		return forDoubleFormat(format, null, null);
134
	}
135
136
	/**
137
	 * Creates a new editing object for {@link Double}s whose validations and
138
	 * conversions used for editing are based on the given number format. Uses
139
	 * the specified custom validation messages.
140
	 * 
141
	 * @param format
142
	 *            The number format defining the validations and conversions
143
	 *            used for editing.
144
	 * @param parseErrorMessage
145
	 *            The validation message issued in case the input string cannot
146
	 *            be parsed to a double.
147
	 * @param outOfRangeMessage
148
	 *            The validation message issued in case the input string
149
	 *            represents a double whose value is out of range. Can be
150
	 *            parameterized by the <code>-Double.MAX_VALUE</code> ({0}) and
151
	 *            <code>+Double.MAX_VALUE</code> ({1}) values.
152
	 * @return The new editing object configured by the given number format.
153
	 */
154
	public static DecimalEditing forDoubleFormat(NumberFormat format,
155
			String parseErrorMessage, String outOfRangeMessage) {
156
		return new DecimalEditing(format, parseErrorMessage, outOfRangeMessage,
157
				Double.class);
158
	}
159
160
	/**
161
	 * Creates a new editing object for {@link Float}s which defaults the
162
	 * validations and conversions used for editing based on the platform's
163
	 * locale. Uses the default validation messages.
164
	 * 
165
	 * @return The new editing object using the default validations and
166
	 *         conversions for editing.
167
	 * 
168
	 * @see NumberFormat#getNumberInstance()
169
	 */
170
	public static DecimalEditing withFloatDefaults() {
171
		return withFloatDefaults(null, null);
172
	}
173
174
	/**
175
	 * Creates a new editing object for {@link Float}s which defaults the
176
	 * validations and conversions used for editing based on the platform's
177
	 * locale. Uses the specified custom validation messages.
178
	 * 
179
	 * @param parseErrorMessage
180
	 *            The validation message issued in case the input string cannot
181
	 *            be parsed to a double.
182
	 * @param outOfRangeMessage
183
	 *            The validation message issued in case the input string
184
	 *            represents a float whose value is out of range. Can be
185
	 *            parameterized by the <code>-Float.MAX_VALUE</code> ({0}) and
186
	 *            <code>+Float.MAX_VALUE</code> ({1}) values.
187
	 * @return The new editing object using the default validations and
188
	 *         conversions for editing.
189
	 * 
190
	 * @see NumberFormat#getNumberInstance()
191
	 */
192
	public static DecimalEditing withFloatDefaults(String parseErrorMessage,
193
			String outOfRangeMessage) {
194
		return new DecimalEditing(NumberFormat.getNumberInstance(),
195
				parseErrorMessage, outOfRangeMessage, Float.class);
196
	}
197
198
	/**
199
	 * Creates a new editing object for {@link Float}s whose validations and
200
	 * conversions used for editing are based on the given number format. Uses
201
	 * the default validation messages.
202
	 * 
203
	 * @param format
204
	 *            The number format defining the validations and conversions
205
	 *            used for editing.
206
	 * @return The new editing object configured by the given number format.
207
	 */
208
	public static DecimalEditing forFloatFormat(NumberFormat format) {
209
		return forFloatFormat(format, null, null);
210
	}
211
212
	/**
213
	 * Creates a new editing object for {@link Float}s whose validations and
214
	 * conversions used for editing are based on the given number format. Uses
215
	 * the specified custom validation messages.
216
	 * 
217
	 * @param format
218
	 *            The number format defining the validations and conversions
219
	 *            used for editing.
220
	 * @param parseErrorMessage
221
	 *            The validation message issued in case the input string cannot
222
	 *            be parsed to a float.
223
	 * @param outOfRangeMessage
224
	 *            The validation message issued in case the input string
225
	 *            represents a float whose value is out of range. Can be
226
	 *            parameterized by the <code>-Float.MAX_VALUE</code> ({0}) and
227
	 *            <code>+Float.MAX_VALUE</code> ({1}) values.
228
	 * @return The new editing object configured by the given number format.
229
	 */
230
	public static DecimalEditing forFloatFormat(NumberFormat format,
231
			String parseErrorMessage, String outOfRangeMessage) {
232
		return new DecimalEditing(format, parseErrorMessage, outOfRangeMessage,
233
				Float.class);
234
	}
235
236
	/**
237
	 * Returns the target constraints to apply.
238
	 * 
239
	 * <p>
240
	 * This method provides a typesafe access to the {@link StringConstraints
241
	 * string target constraints} of this editing object and is equivalent to
242
	 * {@code (StringConstraints) targetConstraints()}.
243
	 * </p>
244
	 * 
245
	 * @return The target constraints to apply.
246
	 * 
247
	 * @see #targetConstraints()
248
	 * @see StringConstraints
249
	 */
250
	public StringConstraints targetStringConstraints() {
251
		return (StringConstraints) targetConstraints();
252
	}
253
254
	/**
255
	 * Returns the model constraints to apply.
256
	 * 
257
	 * <p>
258
	 * This method provides a typesafe access to the {@link DecimalConstraints
259
	 * decimal model constraints} of this editing object and is equivalent to
260
	 * {@code (DecimalConstraints) modelConstraints()}.
261
	 * </p>
262
	 * 
263
	 * @return The model constraints to apply.
264
	 * 
265
	 * @see #modelConstraints()
266
	 * @see DecimalConstraints
267
	 */
268
	public DecimalConstraints modelDecimalConstraints() {
269
		return (DecimalConstraints) modelConstraints();
270
	}
271
272
	/**
273
	 * Returns the before-set model constraints to apply.
274
	 * 
275
	 * <p>
276
	 * This method provides a typesafe access to the {@link DecimalConstraints
277
	 * decimal before-set model constraints} of this editing object and is
278
	 * equivalent to {@code (DecimalConstraints) beforeSetModelConstraints()}.
279
	 * </p>
280
	 * 
281
	 * @return The before-set model constraints to apply.
282
	 * 
283
	 * @see #beforeSetModelConstraints()
284
	 * @see DecimalConstraints
285
	 */
286
	public DecimalConstraints beforeSetModelDecimalConstraints() {
287
		return (DecimalConstraints) beforeSetModelConstraints();
288
	}
289
290
	protected Constraints createTargetConstraints() {
291
		return new StringConstraints();
292
	}
293
294
	protected Constraints createModelConstraints() {
295
		return new DecimalConstraints().decimalFormat(displayFormat);
296
	}
297
298
	protected Constraints createBeforeSetModelConstraints() {
299
		return new DecimalConstraints().decimalFormat(displayFormat);
300
	}
301
}
(-)src/org/eclipse/core/databinding/editing/BigDecimalEditing.java (+197 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import java.math.BigDecimal;
15
16
import org.eclipse.core.databinding.conversion.NumberToStringConverter;
17
import org.eclipse.core.databinding.conversion.StringToNumberConverter;
18
import org.eclipse.core.databinding.validation.constraint.BigDecimalConstraints;
19
import org.eclipse.core.databinding.validation.constraint.Constraints;
20
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
21
import org.eclipse.core.internal.databinding.validation.AbstractStringToNumberValidator;
22
import org.eclipse.core.internal.databinding.validation.StringToBigDecimalValidator;
23
24
import com.ibm.icu.text.NumberFormat;
25
26
/**
27
 * @noextend This class is not intended to be subclassed by clients.
28
 * @since 1.3
29
 */
30
public class BigDecimalEditing extends Editing {
31
32
	private final NumberFormat displayFormat;
33
34
	/**
35
	 * Creates a new editing object for <code>BigDecimal</code>s.
36
	 * 
37
	 * @param format
38
	 *            The BigDecimal format defining the validations and conversions
39
	 *            used for editing.
40
	 * @param parseErrorMessage
41
	 *            The validation message issued in case the input string cannot
42
	 *            be parsed to a BigDecimal.
43
	 * 
44
	 * @noreference This constructor is not intended to be referenced by
45
	 *              clients.
46
	 */
47
	protected BigDecimalEditing(NumberFormat format, String parseErrorMessage) {
48
		this.displayFormat = format;
49
50
		final StringToNumberConverter targetConverter = StringToNumberConverter
51
				.toBigDecimal(format);
52
		final NumberToStringConverter modelConverter = NumberToStringConverter
53
				.fromBigDecimal(format);
54
55
		final AbstractStringToNumberValidator targetValidator = new StringToBigDecimalValidator(
56
				targetConverter);
57
		if (parseErrorMessage != null) {
58
			targetValidator.setParseErrorMessage(parseErrorMessage);
59
		}
60
61
		setTargetConverter(targetConverter);
62
		setModelConverter(modelConverter);
63
		targetConstraints().addValidator(targetValidator);
64
	}
65
66
	/**
67
	 * Creates a new editing object for {@link BigDecimal}s which defaults the
68
	 * validations and conversions used for editing based on the platform's
69
	 * locale. Uses the default validation messages.
70
	 * 
71
	 * @return The new editing object using the default validations and
72
	 *         conversions for editing.
73
	 * 
74
	 * @see NumberFormat#getNumberInstance()
75
	 */
76
	public static BigDecimalEditing withDefaults() {
77
		return withDefaults(null);
78
	}
79
80
	/**
81
	 * Creates a new editing object for {@link BigDecimal}s which defaults the
82
	 * validations and conversions used for editing based on the platform's
83
	 * locale. Uses the specified custom validation message.
84
	 * 
85
	 * @param parseErrorMessage
86
	 *            The validation message issued in case the input string cannot
87
	 *            be parsed to a BigDecimal.
88
	 * @return The new editing object using the default validations and
89
	 *         conversions for editing.
90
	 * 
91
	 * @see NumberFormat#getNumberInstance()
92
	 */
93
	public static BigDecimalEditing withDefaults(String parseErrorMessage) {
94
		return new BigDecimalEditing(NumberFormat.getNumberInstance(),
95
				parseErrorMessage);
96
	}
97
98
	/**
99
	 * Creates a new editing object for {@link BigDecimal}s whose validations
100
	 * and conversions used for editing are based on the given BigDecimal
101
	 * format. Uses the default validation messages.
102
	 * 
103
	 * @param format
104
	 *            The BigDecimal format defining the validations and conversions
105
	 *            used for editing.
106
	 * @return The new editing object configured by the given BigDecimal format.
107
	 */
108
	public static BigDecimalEditing forFormat(NumberFormat format) {
109
		return forFormat(format, null);
110
	}
111
112
	/**
113
	 * Creates a new editing object for {@link BigDecimal}s whose validations
114
	 * and conversions used for editing are based on the given BigDecimal
115
	 * format. Uses the specified custom validation message.
116
	 * 
117
	 * @param format
118
	 *            The BigDecimal format defining the validations and conversions
119
	 *            used for editing.
120
	 * @param parseErrorMessage
121
	 *            The validation message issued in case the input string cannot
122
	 *            be parsed to a BigDecimal.
123
	 * @return The new editing object configured by the given BigDecimal format.
124
	 */
125
	public static BigDecimalEditing forFormat(NumberFormat format,
126
			String parseErrorMessage) {
127
		return new BigDecimalEditing(format, parseErrorMessage);
128
	}
129
130
	/**
131
	 * Returns the target constraints to apply.
132
	 * 
133
	 * <p>
134
	 * This method provides a typesafe access to the {@link StringConstraints
135
	 * string target constraints} of this editing object and is equivalent to
136
	 * {@code (StringConstraints) targetConstraints()}.
137
	 * </p>
138
	 * 
139
	 * @return The target constraints to apply.
140
	 * 
141
	 * @see #targetConstraints()
142
	 * @see StringConstraints
143
	 */
144
	public StringConstraints targetStringConstraints() {
145
		return (StringConstraints) targetConstraints();
146
	}
147
148
	/**
149
	 * Returns the model constraints to apply.
150
	 * 
151
	 * <p>
152
	 * This method provides a typesafe access to the
153
	 * {@link BigDecimalConstraints BigDecimal model constraints} of this
154
	 * editing object and is equivalent to {@code (BigDecimalConstraints)
155
	 * modelConstraints()}.
156
	 * </p>
157
	 * 
158
	 * @return The model constraints to apply.
159
	 * 
160
	 * @see #modelConstraints()
161
	 * @see BigDecimalConstraints
162
	 */
163
	public BigDecimalConstraints modelBigDecimalConstraints() {
164
		return (BigDecimalConstraints) modelConstraints();
165
	}
166
167
	/**
168
	 * Returns the before-set model constraints to apply.
169
	 * 
170
	 * <p>
171
	 * This method provides a typesafe access to the
172
	 * {@link BigDecimalConstraints BigDecimal before-set model constraints} of
173
	 * this editing object and is equivalent to {@code (BigDecimalConstraints)
174
	 * beforeSetModelConstraints()}.
175
	 * </p>
176
	 * 
177
	 * @return The before-set model constraints to apply.
178
	 * 
179
	 * @see #beforeSetModelConstraints()
180
	 * @see BigDecimalConstraints
181
	 */
182
	public BigDecimalConstraints beforeSetModelBigDecimalConstraints() {
183
		return (BigDecimalConstraints) beforeSetModelConstraints();
184
	}
185
186
	protected Constraints createTargetConstraints() {
187
		return new StringConstraints();
188
	}
189
190
	protected Constraints createModelConstraints() {
191
		return new BigDecimalConstraints().bigDecimalFormat(displayFormat);
192
	}
193
194
	protected Constraints createBeforeSetModelConstraints() {
195
		return new BigDecimalConstraints().bigDecimalFormat(displayFormat);
196
	}
197
}
(-)src/org/eclipse/core/internal/databinding/validation/IntegerRangeValidator.java (+201 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import com.ibm.icu.text.NumberFormat;
15
16
/**
17
 * Provides validations for integer numbers which must lie within an open/closed
18
 * range.
19
 * 
20
 * @since 1.3
21
 */
22
public class IntegerRangeValidator extends NumberRangeValidator {
23
24
	private static final Long ZERO = new Long(0);
25
	private static final Long ONE = new Long(1);
26
27
	/**
28
	 * Single constructor which supports the individual integer range types.
29
	 * 
30
	 * @param min
31
	 *            The min integer of the range or <code>null</code> in case no
32
	 *            lower bound is defined.
33
	 * @param max
34
	 *            The max integer of the range or <code>null</code> in case no
35
	 *            upper bound is defined.
36
	 * @param minConstraint
37
	 *            The type of constraint imposed by the lower bound of the
38
	 *            range.
39
	 * @param maxConstraint
40
	 *            The type of constraint imposed by the upper bound of the
41
	 *            range.
42
	 * @param validationMessage
43
	 *            The validation message pattern to use. Can be parameterized by
44
	 *            the lower and upper bound of the range, if defined.
45
	 * @param format
46
	 *            The integer format to use for formatting integers in the
47
	 *            validation message.
48
	 */
49
	private IntegerRangeValidator(Number min, Number max, int minConstraint,
50
			int maxConstraint, String validationMessage, NumberFormat format) {
51
		super(min, max, minConstraint, maxConstraint, validationMessage, format);
52
	}
53
54
	/**
55
	 * Creates a validator which checks that an input integer is greater than
56
	 * the given number.
57
	 * 
58
	 * @param number
59
	 *            The reference number of the greater constraint.
60
	 * @param validationMessage
61
	 *            The validation message pattern to use. Can be parameterized
62
	 *            with the given reference number.
63
	 * @param format
64
	 *            The display format to use for formatting integers in the
65
	 *            validation message.
66
	 * @return The validator instance.
67
	 */
68
	public static IntegerRangeValidator greater(long number,
69
			String validationMessage, NumberFormat format) {
70
		return new IntegerRangeValidator(new Long(number), null, GREATER,
71
				UNDEFINED, defaultIfNull(validationMessage, GREATER_MESSAGE),
72
				format);
73
	}
74
75
	/**
76
	 * Creates a validator which checks that an input integer is greater than or
77
	 * equal to the given number.
78
	 * 
79
	 * @param number
80
	 *            The reference number of the greater-equal constraint.
81
	 * @param validationMessage
82
	 *            The validation message pattern to use. Can be parameterized
83
	 *            with the given reference number.
84
	 * @param format
85
	 *            The display format to use for formatting integers in the
86
	 *            validation message.
87
	 * @return The validator instance.
88
	 */
89
	public static IntegerRangeValidator greaterEqual(long number,
90
			String validationMessage, NumberFormat format) {
91
		return new IntegerRangeValidator(new Long(number), null, GREATER_EQUAL,
92
				UNDEFINED, defaultIfNull(validationMessage,
93
						GREATER_EQUAL_MESSAGE), format);
94
	}
95
96
	/**
97
	 * Creates a validator which checks that an input integer is less than the
98
	 * given number.
99
	 * 
100
	 * @param number
101
	 *            The reference number of the less constraint.
102
	 * @param validationMessage
103
	 *            The validation message pattern to use. Can be parameterized
104
	 *            with the given reference number.
105
	 * @param format
106
	 *            The display format to use for formatting integers in the
107
	 *            validation message.
108
	 * @return The validator instance.
109
	 */
110
	public static IntegerRangeValidator less(long number,
111
			String validationMessage, NumberFormat format) {
112
		return new IntegerRangeValidator(null, new Long(number), UNDEFINED,
113
				LESS, defaultIfNull(validationMessage, LESS_MESSAGE), format);
114
	}
115
116
	/**
117
	 * Creates a validator which checks that an input integer is less than or
118
	 * equal to the given number.
119
	 * 
120
	 * @param number
121
	 *            The reference number of the less-equal constraint.
122
	 * @param validationMessage
123
	 *            The validation message pattern to use. Can be parameterized
124
	 *            with the given reference number.
125
	 * @param format
126
	 *            The display format to use for formatting integers in the
127
	 *            validation message.
128
	 * @return The validator instance.
129
	 */
130
	public static IntegerRangeValidator lessEqual(long number,
131
			String validationMessage, NumberFormat format) {
132
		return new IntegerRangeValidator(null, new Long(number), UNDEFINED,
133
				LESS_EQUAL,
134
				defaultIfNull(validationMessage, LESS_EQUAL_MESSAGE), format);
135
	}
136
137
	/**
138
	 * Creates a validator which checks that an input integer is within the
139
	 * given range.
140
	 * 
141
	 * @param min
142
	 *            The lower bound of the range (inclusive).
143
	 * @param max
144
	 *            The upper bound of the range (inclusive).
145
	 * @param validationMessage
146
	 *            The validation message pattern to use. Can be parameterized
147
	 *            with the range's lower and upper bound.
148
	 * @param format
149
	 *            The display format to use for formatting integers in the
150
	 *            validation message.
151
	 * @return The validator instance.
152
	 */
153
	public static IntegerRangeValidator range(long min, long max,
154
			String validationMessage, NumberFormat format) {
155
		return new IntegerRangeValidator(new Long(min), new Long(max),
156
				GREATER_EQUAL, LESS_EQUAL, defaultIfNull(validationMessage,
157
						WITHIN_RANGE_MESSAGE), format);
158
	}
159
160
	/**
161
	 * Creates a validator which checks that an input integer is positive.
162
	 * 
163
	 * @param validationMessage
164
	 *            The validation message to use.
165
	 * @param format
166
	 *            The display format to use for formatting integers in the
167
	 *            validation message.
168
	 * @return The validator instance.
169
	 */
170
	public static IntegerRangeValidator positive(String validationMessage,
171
			NumberFormat format) {
172
		return new IntegerRangeValidator(ONE, null, GREATER_EQUAL, UNDEFINED,
173
				defaultIfNull(validationMessage, POSITIVE_MESSAGE), format);
174
	}
175
176
	/**
177
	 * Creates a validator which checks that an input integer is non-negative.
178
	 * 
179
	 * @param validationMessage
180
	 *            The validation message to use.
181
	 * @param format
182
	 *            The display format to use for formatting integers in the
183
	 *            validation message.
184
	 * @return The validator instance.
185
	 */
186
	public static IntegerRangeValidator nonNegative(String validationMessage,
187
			NumberFormat format) {
188
		return new IntegerRangeValidator(ZERO, null, GREATER_EQUAL, UNDEFINED,
189
				defaultIfNull(validationMessage, NON_NEGATIVE_MESSAGE), format);
190
	}
191
192
	protected int compare(Number number1, Number number2) {
193
		long val1 = number1.longValue();
194
		long val2 = number2.longValue();
195
		return (val1 < val2) ? -1 : ((val1 > val2) ? + 1 : 0);
196
	}
197
198
	private static String defaultIfNull(String string, String defaultString) {
199
		return (string != null) ? string : defaultString;
200
	}
201
}
(-)src/org/eclipse/core/databinding/validation/constraint/BigIntegerConstraints.java (+322 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import java.math.BigInteger;
15
16
import org.eclipse.core.internal.databinding.validation.BigIntegerRangeValidator;
17
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
18
19
import com.ibm.icu.text.NumberFormat;
20
21
/**
22
 * Provides a set of constraints to apply to <code>BigInteger</code>s.
23
 * 
24
 * <p>
25
 * Instances of this class can be used to define a set of constraints to apply
26
 * to BigInteger numbers. In addition, the validation messages to be issued for
27
 * the individual constraints as well as the way in which model objects are
28
 * formatted in the validation messages can be configured.
29
 * </p>
30
 * 
31
 * @see BigInteger
32
 * 
33
 * @noextend This class is not intended to be subclassed by clients.
34
 * @since 1.3
35
 */
36
public class BigIntegerConstraints extends Constraints {
37
38
	private NumberFormat bigIntegerFormat = NumberFormat.getIntegerInstance();
39
40
	private String requiredMessage = null;
41
42
	private String greaterMessage = null;
43
44
	private String greaterEqualMessage = null;
45
46
	private String lessMessage = null;
47
48
	private String lessEqualMessage = null;
49
50
	private String rangeMessage = null;
51
52
	private String positiveMessage = null;
53
54
	private String nonNegativeMessage = null;
55
56
	/**
57
	 * Sets the format to use when formatting a BigInteger to be included in any
58
	 * of the validation messages.
59
	 * 
60
	 * @param format
61
	 *            The format to use for displaying BigIntegers in validation
62
	 *            messages.
63
	 * @return This constraints instance for method chaining.
64
	 */
65
	public BigIntegerConstraints bigIntegerFormat(NumberFormat format) {
66
		this.bigIntegerFormat = format;
67
		return this;
68
	}
69
70
	/**
71
	 * Adds a validator ensuring that the input BigInteger is not
72
	 * <code>null</code>. Uses the current {@link #requiredMessage(String)
73
	 * validation message}.
74
	 * 
75
	 * @return This constraints instance for method chaining.
76
	 */
77
	public BigIntegerConstraints required() {
78
		addValidator(new NonNullValidator(requiredMessage));
79
		return this;
80
	}
81
82
	/**
83
	 * Sets the validation message for the {@link #required()} constraint.
84
	 * 
85
	 * @param message
86
	 *            The validation message for the {@link #required()} constraint.
87
	 * @return This constraints instance for method chaining.
88
	 * 
89
	 * @see #required()
90
	 */
91
	public BigIntegerConstraints requiredMessage(String message) {
92
		this.requiredMessage = message;
93
		return this;
94
	}
95
96
	/**
97
	 * Adds a validator ensuring that the input BigInteger is greater than the
98
	 * given number. Uses the current {@link #greaterMessage(String) validation
99
	 * message} and {@link #bigIntegerFormat(NumberFormat) BigInteger format}.
100
	 * 
101
	 * @param number
102
	 *            The number which the input BigInteger must be greater than.
103
	 * @return This constraints instance for method chaining.
104
	 */
105
	public BigIntegerConstraints greater(BigInteger number) {
106
		addValidator(BigIntegerRangeValidator.greater(number, greaterMessage,
107
				bigIntegerFormat));
108
		return this;
109
	}
110
111
	/**
112
	 * Sets the validation message pattern for the {@link #greater(BigInteger)}
113
	 * constraint.
114
	 * 
115
	 * @param message
116
	 *            The validation message pattern for the
117
	 *            {@link #greater(BigInteger)} constraint. Can be parameterized
118
	 *            with the number ({0}) which the input BigInteger must be
119
	 *            greater than.
120
	 * @return This constraints instance for method chaining.
121
	 * 
122
	 * @see #greater(BigInteger)
123
	 */
124
	public BigIntegerConstraints greaterMessage(String message) {
125
		this.greaterMessage = message;
126
		return this;
127
	}
128
129
	/**
130
	 * Adds a validator ensuring that the input BigInteger is greater than or
131
	 * equal to the given number. Uses the current
132
	 * {@link #greaterEqualMessage(String) validation message} and
133
	 * {@link #bigIntegerFormat(NumberFormat) BigInteger format}.
134
	 * 
135
	 * @param number
136
	 *            The number which the input BigInteger must be greater than or
137
	 *            equal to.
138
	 * @return This constraints instance for method chaining.
139
	 */
140
	public BigIntegerConstraints greaterEqual(BigInteger number) {
141
		addValidator(BigIntegerRangeValidator.greaterEqual(number,
142
				greaterEqualMessage, bigIntegerFormat));
143
		return this;
144
	}
145
146
	/**
147
	 * Sets the validation message pattern for the
148
	 * {@link #greaterEqual(BigInteger)} constraint.
149
	 * 
150
	 * @param message
151
	 *            The validation message pattern for the
152
	 *            {@link #greaterEqual(BigInteger)} constraint. Can be
153
	 *            parameterized with the number ({0}) which the input BigInteger
154
	 *            must be greater than or equal to.
155
	 * @return This constraints instance for method chaining.
156
	 * 
157
	 * @see #greaterEqual(BigInteger)
158
	 */
159
	public BigIntegerConstraints greaterEqualMessage(String message) {
160
		this.greaterEqualMessage = message;
161
		return this;
162
	}
163
164
	/**
165
	 * Adds a validator ensuring that the input BigInteger is less than the
166
	 * given number. Uses the current {@link #lessMessage(String) validation
167
	 * message} and {@link #bigIntegerFormat(NumberFormat) BigInteger format}.
168
	 * 
169
	 * @param number
170
	 *            The number which the input BigInteger must be less than.
171
	 * @return This constraints instance for method chaining.
172
	 */
173
	public BigIntegerConstraints less(BigInteger number) {
174
		addValidator(BigIntegerRangeValidator.less(number, lessMessage,
175
				bigIntegerFormat));
176
		return this;
177
	}
178
179
	/**
180
	 * Sets the validation message pattern for the {@link #less(BigInteger)}
181
	 * constraint.
182
	 * 
183
	 * @param message
184
	 *            The validation message pattern for the
185
	 *            {@link #less(BigInteger)} constraint. Can be parameterized
186
	 *            with the number ({0}) which the input BigInteger must be less
187
	 *            than.
188
	 * @return This constraints instance for method chaining.
189
	 * 
190
	 * @see #less(BigInteger)
191
	 */
192
	public BigIntegerConstraints lessMessage(String message) {
193
		this.lessMessage = message;
194
		return this;
195
	}
196
197
	/**
198
	 * Adds a validator ensuring that the input BigInteger is less than or equal
199
	 * to the given number. Uses the current {@link #lessEqualMessage(String)
200
	 * validation message} and {@link #bigIntegerFormat(NumberFormat) BigInteger
201
	 * format}.
202
	 * 
203
	 * @param number
204
	 *            The number which the input BigInteger must be less than or
205
	 *            equal to.
206
	 * @return This constraints instance for method chaining.
207
	 */
208
	public BigIntegerConstraints lessEqual(BigInteger number) {
209
		addValidator(BigIntegerRangeValidator.greaterEqual(number,
210
				lessEqualMessage, bigIntegerFormat));
211
		return this;
212
	}
213
214
	/**
215
	 * Sets the validation message pattern for the
216
	 * {@link #lessEqual(BigInteger)} constraint.
217
	 * 
218
	 * @param message
219
	 *            The validation message pattern for the
220
	 *            {@link #lessEqual(BigInteger)} constraint. Can be
221
	 *            parameterized with the number ({0}) which the input BigInteger
222
	 *            must be less than or equal to.
223
	 * @return This constraints instance for method chaining.
224
	 * 
225
	 * @see #lessEqual(BigInteger)
226
	 */
227
	public BigIntegerConstraints lessEqualMessage(String message) {
228
		this.lessEqualMessage = message;
229
		return this;
230
	}
231
232
	/**
233
	 * Adds a validator ensuring that the input BigInteger is within the given
234
	 * range. Uses the current {@link #rangeMessage(String) validation message}
235
	 * and {@link #bigIntegerFormat(NumberFormat) BigInteger format}.
236
	 * 
237
	 * @param min
238
	 *            The lower bound of the range (inclusive).
239
	 * @param max
240
	 *            The upper bound of the range (inclusive).
241
	 * @return This constraints instance for method chaining.
242
	 */
243
	public BigIntegerConstraints range(BigInteger min, BigInteger max) {
244
		addValidator(BigIntegerRangeValidator.range(min, max, rangeMessage,
245
				bigIntegerFormat));
246
		return this;
247
	}
248
249
	/**
250
	 * Sets the validation message pattern for the
251
	 * {@link #range(BigInteger, BigInteger)} constraint.
252
	 * 
253
	 * @param message
254
	 *            The validation message pattern for the
255
	 *            {@link #range(BigInteger, BigInteger)} constraint. Can be
256
	 *            parameterized with the min ({0}) and max ({1}) values of the
257
	 *            range in which the input BigInteger must lie.
258
	 * @return This constraints instance for method chaining.
259
	 * 
260
	 * @see #range(BigInteger, BigInteger)
261
	 */
262
	public BigIntegerConstraints rangeMessage(String message) {
263
		this.rangeMessage = message;
264
		return this;
265
	}
266
267
	/**
268
	 * Adds a validator ensuring that the input BigInteger is positive. Uses the
269
	 * current {@link #positiveMessage(String) validation message}.
270
	 * 
271
	 * @return This constraints instance for method chaining.
272
	 */
273
	public BigIntegerConstraints positive() {
274
		addValidator(BigIntegerRangeValidator.positive(positiveMessage,
275
				bigIntegerFormat));
276
		return this;
277
	}
278
279
	/**
280
	 * Sets the validation message pattern for the {@link #positive()}
281
	 * constraint.
282
	 * 
283
	 * @param message
284
	 *            The validation message pattern for the {@link #positive()}
285
	 *            constraint.
286
	 * @return This constraints instance for method chaining.
287
	 * 
288
	 * @see #positive()
289
	 */
290
	public BigIntegerConstraints positiveMessage(String message) {
291
		this.positiveMessage = message;
292
		return this;
293
	}
294
295
	/**
296
	 * Adds a validator ensuring that the input BigInteger is non-negative. Uses
297
	 * the current {@link #nonNegativeMessage(String) validation message}.
298
	 * 
299
	 * @return This constraints instance for method chaining.
300
	 */
301
	public BigIntegerConstraints nonNegative() {
302
		addValidator(BigIntegerRangeValidator.nonNegative(nonNegativeMessage,
303
				bigIntegerFormat));
304
		return this;
305
	}
306
307
	/**
308
	 * Sets the validation message pattern for the {@link #nonNegative()}
309
	 * constraint.
310
	 * 
311
	 * @param message
312
	 *            The validation message pattern for the {@link #nonNegative()}
313
	 *            constraint.
314
	 * @return This constraints instance for method chaining.
315
	 * 
316
	 * @see #nonNegative()
317
	 */
318
	public BigIntegerConstraints nonNegativeMessage(String message) {
319
		this.nonNegativeMessage = message;
320
		return this;
321
	}
322
}
(-)src/org/eclipse/core/internal/databinding/validation/CharacterValidator.java (+145 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import org.eclipse.core.databinding.validation.IValidator;
15
import org.eclipse.core.databinding.validation.ValidationStatus;
16
import org.eclipse.core.internal.databinding.BindingMessages;
17
import org.eclipse.core.runtime.IStatus;
18
19
/**
20
 * @since 1.3
21
 */
22
public class CharacterValidator implements IValidator {
23
24
	private static final int VALIDATE_NO_WHITESPACE = 0;
25
	private static final int VALIDATE_NO_SPACE = 1;
26
	private static final int VALIDATE_LETTER = 2;
27
	private static final int VALIDATE_DIGIT = 3;
28
	private static final int VALIDATE_LETTER_OR_DIGIT = 4;
29
30
	private static final String NO_WHITESPACE_VALIDATION_MESSAGE = BindingMessages
31
			.getString(BindingMessages.VALIDATE_CHARACTER_NO_WHITESPACE);
32
	private static final String NO_SPACE_VALIDATION_MESSAGE = BindingMessages
33
			.getString(BindingMessages.VALIDATE_CHARACTER_NO_SPACE);
34
	private static final String LETTER_VALIDATION_MESSAGE = BindingMessages
35
			.getString(BindingMessages.VALIDATE_CHARACTER_LETTER);
36
	private static final String DIGIT_VALIDATION_MESSAGE = BindingMessages
37
			.getString(BindingMessages.VALIDATE_CHARACTER_DIGIT);
38
	private static final String LETTER_OR_DIGIT_VALIDATION_MESSAGE = BindingMessages
39
			.getString(BindingMessages.VALIDATE_CHARACTER_LETTER_OR_DIGIT);
40
41
	private final int validation;
42
	private final String validationMessage;
43
44
	private CharacterValidator(int validation, String validationMessage) {
45
		this.validation = validation;
46
		this.validationMessage = validationMessage;
47
	}
48
49
	/**
50
	 * Creates a validator which checks that an input character is no
51
	 * {@link Character#isWhitespace(char) whitespace}.
52
	 * 
53
	 * @param validationMessage
54
	 *            The validation message to use.
55
	 * @return The validator instance.
56
	 */
57
	public static CharacterValidator noWhitespace(String validationMessage) {
58
		return new CharacterValidator(VALIDATE_NO_WHITESPACE, defaultIfNull(
59
				NO_WHITESPACE_VALIDATION_MESSAGE, validationMessage));
60
	}
61
62
	/**
63
	 * Creates a validator which checks that an input character is no
64
	 * {@link Character#isSpaceChar(char) space}.
65
	 * 
66
	 * @param validationMessage
67
	 *            The validation message to use.
68
	 * @return The validator instance.
69
	 */
70
	public static CharacterValidator noSpace(String validationMessage) {
71
		return new CharacterValidator(VALIDATE_NO_SPACE, defaultIfNull(
72
				NO_SPACE_VALIDATION_MESSAGE, validationMessage));
73
	}
74
75
	/**
76
	 * Creates a validator which checks that an input character is a
77
	 * {@link Character#isLetter(char) letter}.
78
	 * 
79
	 * @param validationMessage
80
	 *            The validation message to use.
81
	 * @return The validator instance.
82
	 */
83
	public static CharacterValidator letter(String validationMessage) {
84
		return new CharacterValidator(VALIDATE_LETTER, defaultIfNull(
85
				LETTER_VALIDATION_MESSAGE, validationMessage));
86
	}
87
88
	/**
89
	 * Creates a validator which checks that an input character is a
90
	 * {@link Character#isDigit(char) digit}.
91
	 * 
92
	 * @param validationMessage
93
	 *            The validation message to use.
94
	 * @return The validator instance.
95
	 */
96
	public static CharacterValidator digit(String validationMessage) {
97
		return new CharacterValidator(VALIDATE_DIGIT, defaultIfNull(
98
				DIGIT_VALIDATION_MESSAGE, validationMessage));
99
	}
100
101
	/**
102
	 * Creates a validator which checks that an input character is a
103
	 * {@link Character#isLetterOrDigit(char) letter or ditig}.
104
	 * 
105
	 * @param validationMessage
106
	 *            The validation message to use.
107
	 * @return The validator instance.
108
	 */
109
	public static CharacterValidator letterOrDigit(String validationMessage) {
110
		return new CharacterValidator(VALIDATE_LETTER_OR_DIGIT, defaultIfNull(
111
				LETTER_OR_DIGIT_VALIDATION_MESSAGE, validationMessage));
112
	}
113
114
	public IStatus validate(Object value) {
115
		if (value != null) {
116
			char character = ((Character) value).charValue();
117
			if (!isValid(character)) {
118
				return ValidationStatus.error(validationMessage);
119
			}
120
		}
121
		return ValidationStatus.ok();
122
	}
123
124
	private boolean isValid(char character) {
125
		switch (validation) {
126
		case VALIDATE_NO_WHITESPACE:
127
			return !Character.isWhitespace(character);
128
		case VALIDATE_NO_SPACE:
129
			return !Character.isSpaceChar(character);
130
		case VALIDATE_LETTER:
131
			return Character.isLetter(character);
132
		case VALIDATE_DIGIT:
133
			return Character.isDigit(character);
134
		case VALIDATE_LETTER_OR_DIGIT:
135
			return Character.isLetterOrDigit(character);
136
		default:
137
			throw new IllegalArgumentException(
138
					"Unsupported validation: " + validation); //$NON-NLS-1$
139
		}
140
	}
141
142
	private static String defaultIfNull(String string, String defaultString) {
143
		return (string != null) ? string : defaultString;
144
	}
145
}
(-)src/org/eclipse/core/databinding/editing/CharacterEditing.java (+145 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import org.eclipse.core.databinding.validation.constraint.CharacterConstraints;
15
import org.eclipse.core.databinding.validation.constraint.Constraints;
16
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
17
import org.eclipse.core.internal.databinding.conversion.CharacterToStringConverter;
18
import org.eclipse.core.internal.databinding.conversion.StringToCharacterConverter;
19
import org.eclipse.core.internal.databinding.validation.StringToCharacterValidator;
20
21
/**
22
 * @noextend This class is not intended to be subclassed by clients.
23
 * @since 1.3
24
 */
25
public class CharacterEditing extends Editing {
26
27
	/**
28
	 * Creates a new editing object for booleans.
29
	 * 
30
	 * @param parseErrorMessage
31
	 *            The validation message issued in case the input string is not
32
	 *            a valid character.
33
	 * 
34
	 * @noreference This constructor is not intended to be referenced by
35
	 *              clients.
36
	 */
37
	protected CharacterEditing(String parseErrorMessage) {
38
		StringToCharacterConverter targetConverter = new StringToCharacterConverter(
39
				false);
40
		CharacterToStringConverter modelConverter = CharacterToStringConverter
41
				.fromCharacter(false);
42
43
		StringToCharacterValidator targetValidator = new StringToCharacterValidator(
44
				targetConverter);
45
		if (parseErrorMessage != null) {
46
			targetValidator.setParseErrorMessage(parseErrorMessage);
47
		}
48
49
		setTargetConverter(targetConverter);
50
		setModelConverter(modelConverter);
51
		targetConstraints().addValidator(targetValidator);
52
	}
53
54
	/**
55
	 * Creates a new editing object which uses the default validations and
56
	 * conversions for the editing of characters.
57
	 * 
58
	 * @return The new editing object for the default editing of characters.
59
	 */
60
	public static CharacterEditing withDefaults() {
61
		return withDefaults(null);
62
	}
63
64
	/**
65
	 * Creates a new editing object which uses the default validations and
66
	 * conversions for the editing of characters. Uses the specified custom
67
	 * validation message.
68
	 * 
69
	 * @param parseErrorMessage
70
	 *            The validation message issued in case the input string is not
71
	 *            a valid character.
72
	 * @return The new editing object for the default editing of characters.
73
	 */
74
	public static CharacterEditing withDefaults(String parseErrorMessage) {
75
		return new CharacterEditing(parseErrorMessage);
76
	}
77
78
	/**
79
	 * Returns the target constraints to apply.
80
	 * 
81
	 * <p>
82
	 * This method provides a typesafe access to the {@link StringConstraints
83
	 * string target constraints} of this editing object and is equivalent to
84
	 * {@code (StringConstraints) targetConstraints()}.
85
	 * </p>
86
	 * 
87
	 * @return The target constraints to apply.
88
	 * 
89
	 * @see #targetConstraints()
90
	 * @see StringConstraints
91
	 */
92
	public StringConstraints targetStringConstraints() {
93
		return (StringConstraints) targetConstraints();
94
	}
95
96
	/**
97
	 * Returns the model constraints to apply.
98
	 * 
99
	 * <p>
100
	 * This method provides a typesafe access to the
101
	 * {@link CharacterConstraints character model constraints} of this editing
102
	 * object and is equivalent to {@code (CharacterConstraints)
103
	 * modelConstraints()}.
104
	 * </p>
105
	 * 
106
	 * @return The model constraints to apply.
107
	 * 
108
	 * @see #modelConstraints()
109
	 * @see CharacterConstraints
110
	 */
111
	public CharacterConstraints modelCharacterConstraints() {
112
		return (CharacterConstraints) modelConstraints();
113
	}
114
115
	/**
116
	 * Returns the before-set model constraints to apply.
117
	 * 
118
	 * <p>
119
	 * This method provides a typesafe access to the
120
	 * {@link CharacterConstraints character before-set model constraints} of
121
	 * this editing object and is equivalent to {@code (CharacterConstraints)
122
	 * beforeSetModelConstraints()}.
123
	 * </p>
124
	 * 
125
	 * @return The before-set model constraints to apply.
126
	 * 
127
	 * @see #beforeSetModelConstraints()
128
	 * @see CharacterConstraints
129
	 */
130
	public CharacterConstraints beforeSetModelCharacterConstraints() {
131
		return (CharacterConstraints) beforeSetModelConstraints();
132
	}
133
134
	protected Constraints createTargetConstraints() {
135
		return new StringConstraints();
136
	}
137
138
	protected Constraints createModelConstraints() {
139
		return new CharacterConstraints();
140
	}
141
142
	protected Constraints createBeforeSetModelConstraints() {
143
		return new CharacterConstraints();
144
	}
145
}
(-)src/org/eclipse/core/internal/databinding/validation/StringToBigIntegerValidator.java (+32 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
/**
15
 * Validates that a string is of the appropriate format for a BigInteger.
16
 * 
17
 * @since 1.3
18
 */
19
public class StringToBigIntegerValidator extends
20
		AbstractStringToNumberValidator {
21
22
	/**
23
	 * @param converter
24
	 */
25
	public StringToBigIntegerValidator(NumberFormatConverter converter) {
26
		super(converter, null, null);
27
	}
28
29
	protected boolean isInRange(Number number) {
30
		return true;
31
	}
32
}
(-)src/org/eclipse/core/internal/databinding/validation/NonNullValidator.java (+43 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import org.eclipse.core.databinding.validation.IValidator;
15
import org.eclipse.core.databinding.validation.ValidationStatus;
16
import org.eclipse.core.internal.databinding.BindingMessages;
17
import org.eclipse.core.runtime.IStatus;
18
19
/**
20
 * @since 1.3
21
 */
22
public class NonNullValidator implements IValidator {
23
24
	private static final String NON_NULL_VALIDATION_MESSAGE = BindingMessages
25
			.getString(BindingMessages.VALIDATE_NON_NULL);
26
27
	private final String validationMessage;
28
29
	/**
30
	 * @param validationMessage
31
	 */
32
	public NonNullValidator(String validationMessage) {
33
		this.validationMessage = validationMessage != null ? validationMessage
34
				: NON_NULL_VALIDATION_MESSAGE;
35
	}
36
37
	public IStatus validate(Object value) {
38
		if (value == null) {
39
			return ValidationStatus.error(validationMessage);
40
		}
41
		return ValidationStatus.ok();
42
	}
43
}
(-)src/org/eclipse/core/internal/databinding/validation/DecimalRangeValidator.java (+201 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import com.ibm.icu.text.NumberFormat;
15
16
/**
17
 * Provides validations for decimal numbers which must lie within an open/closed
18
 * range.
19
 * 
20
 * @since 1.3
21
 */
22
public class DecimalRangeValidator extends NumberRangeValidator {
23
24
	private static final Double ZERO = new Double(0);
25
	private static final Double ONE = new Double(1);
26
27
	/**
28
	 * Single constructor which supports the individual decimal range types.
29
	 * 
30
	 * @param min
31
	 *            The min decimal of the range or <code>null</code> in case no
32
	 *            lower bound is defined.
33
	 * @param max
34
	 *            The max decimal of the range or <code>null</code> in case no
35
	 *            upper bound is defined.
36
	 * @param minConstraint
37
	 *            The type of constraint imposed by the lower bound of the
38
	 *            range.
39
	 * @param maxConstraint
40
	 *            The type of constraint imposed by the upper bound of the
41
	 *            range.
42
	 * @param validationMessage
43
	 *            The validation message pattern to use. Can be parameterized by
44
	 *            the lower and upper bound of the range, if defined.
45
	 * @param format
46
	 *            The decimal format to use for formatting integers in the
47
	 *            validation message.
48
	 */
49
	private DecimalRangeValidator(Number min, Number max, int minConstraint,
50
			int maxConstraint, String validationMessage, NumberFormat format) {
51
		super(min, max, minConstraint, maxConstraint, validationMessage, format);
52
	}
53
54
	/**
55
	 * Creates a validator which checks that an input decimal is greater than
56
	 * the given number.
57
	 * 
58
	 * @param number
59
	 *            The reference number of the greater constraint.
60
	 * @param validationMessage
61
	 *            The validation message pattern to use. Can be parameterized
62
	 *            with the given reference number.
63
	 * @param format
64
	 *            The display format to use for formatting integers in the
65
	 *            validation message.
66
	 * @return The validator instance.
67
	 */
68
	public static DecimalRangeValidator greater(double number,
69
			String validationMessage, NumberFormat format) {
70
		return new DecimalRangeValidator(new Double(number), null, GREATER,
71
				UNDEFINED, defaultIfNull(validationMessage, GREATER_MESSAGE),
72
				format);
73
	}
74
75
	/**
76
	 * Creates a validator which checks that an input decimal is greater than or
77
	 * equal to the given number.
78
	 * 
79
	 * @param number
80
	 *            The reference number of the greater-equal constraint.
81
	 * @param validationMessage
82
	 *            The validation message pattern to use. Can be parameterized
83
	 *            with the given reference number.
84
	 * @param format
85
	 *            The display format to use for formatting integers in the
86
	 *            validation message.
87
	 * @return The validator instance.
88
	 */
89
	public static DecimalRangeValidator greaterEqual(double number,
90
			String validationMessage, NumberFormat format) {
91
		return new DecimalRangeValidator(new Double(number), null,
92
				GREATER_EQUAL, UNDEFINED, defaultIfNull(validationMessage,
93
						GREATER_EQUAL_MESSAGE), format);
94
	}
95
96
	/**
97
	 * Creates a validator which checks that an input decimal is less than the
98
	 * given number.
99
	 * 
100
	 * @param number
101
	 *            The reference number of the less constraint.
102
	 * @param validationMessage
103
	 *            The validation message pattern to use. Can be parameterized
104
	 *            with the given reference number.
105
	 * @param format
106
	 *            The display format to use for formatting integers in the
107
	 *            validation message.
108
	 * @return The validator instance.
109
	 */
110
	public static DecimalRangeValidator less(double number,
111
			String validationMessage, NumberFormat format) {
112
		return new DecimalRangeValidator(null, new Double(number), UNDEFINED,
113
				LESS, defaultIfNull(validationMessage, LESS_MESSAGE), format);
114
	}
115
116
	/**
117
	 * Creates a validator which checks that an input decimal is less than or
118
	 * equal to the given number.
119
	 * 
120
	 * @param number
121
	 *            The reference number of the less-equal constraint.
122
	 * @param validationMessage
123
	 *            The validation message pattern to use. Can be parameterized
124
	 *            with the given reference number.
125
	 * @param format
126
	 *            The display format to use for formatting integers in the
127
	 *            validation message.
128
	 * @return The validator instance.
129
	 */
130
	public static DecimalRangeValidator lessEqual(double number,
131
			String validationMessage, NumberFormat format) {
132
		return new DecimalRangeValidator(null, new Double(number), UNDEFINED,
133
				LESS_EQUAL,
134
				defaultIfNull(validationMessage, LESS_EQUAL_MESSAGE), format);
135
	}
136
137
	/**
138
	 * Creates a validator which checks that an input decimal is within the
139
	 * given range.
140
	 * 
141
	 * @param min
142
	 *            The lower bound of the range (inclusive).
143
	 * @param max
144
	 *            The upper bound of the range (inclusive).
145
	 * @param validationMessage
146
	 *            The validation message pattern to use. Can be parameterized
147
	 *            with the range's lower and upper bound.
148
	 * @param format
149
	 *            The display format to use for formatting integers in the
150
	 *            validation message.
151
	 * @return The validator instance.
152
	 */
153
	public static DecimalRangeValidator range(double min, double max,
154
			String validationMessage, NumberFormat format) {
155
		return new DecimalRangeValidator(new Double(min), new Double(max),
156
				GREATER_EQUAL, LESS_EQUAL, defaultIfNull(validationMessage,
157
						WITHIN_RANGE_MESSAGE), format);
158
	}
159
160
	/**
161
	 * Creates a validator which checks that an input decimal is positive.
162
	 * 
163
	 * @param validationMessage
164
	 *            The validation message to use.
165
	 * @param format
166
	 *            The display format to use for formatting integers in the
167
	 *            validation message.
168
	 * @return The validator instance.
169
	 */
170
	public static DecimalRangeValidator positive(String validationMessage,
171
			NumberFormat format) {
172
		return new DecimalRangeValidator(ONE, null, GREATER_EQUAL, UNDEFINED,
173
				defaultIfNull(validationMessage, POSITIVE_MESSAGE), format);
174
	}
175
176
	/**
177
	 * Creates a validator which checks that an input decimal is non-negative.
178
	 * 
179
	 * @param validationMessage
180
	 *            The validation message to use.
181
	 * @param format
182
	 *            The display format to use for formatting integers in the
183
	 *            validation message.
184
	 * @return The validator instance.
185
	 */
186
	public static DecimalRangeValidator nonNegative(String validationMessage,
187
			NumberFormat format) {
188
		return new DecimalRangeValidator(ZERO, null, GREATER_EQUAL, UNDEFINED,
189
				defaultIfNull(validationMessage, NON_NEGATIVE_MESSAGE), format);
190
	}
191
192
	protected int compare(Number number1, Number number2) {
193
		double val1 = number1.doubleValue();
194
		double val2 = number2.doubleValue();
195
		return (val1 < val2) ? -1 : ((val1 > val2) ? + 1 : 0);
196
	}
197
198
	private static String defaultIfNull(String string, String defaultString) {
199
		return (string != null) ? string : defaultString;
200
	}
201
}
(-)src/org/eclipse/core/internal/databinding/validation/BigDecimalRangeValidator.java (+206 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import java.math.BigDecimal;
15
16
import com.ibm.icu.text.NumberFormat;
17
18
/**
19
 * Provides validations for BigDecimals which must lie within an open/closed
20
 * range.
21
 * 
22
 * @since 1.3
23
 */
24
public class BigDecimalRangeValidator extends NumberRangeValidator {
25
26
	private static final BigDecimal ZERO = new BigDecimal("0"); //$NON-NLS-1$
27
	private static final BigDecimal ONE = new BigDecimal("1"); //$NON-NLS-1$
28
29
	/**
30
	 * Single constructor which supports the individual integer range types.
31
	 * 
32
	 * @param min
33
	 *            The min BigDecimal of the range or <code>null</code> in case
34
	 *            no lower bound is defined.
35
	 * @param max
36
	 *            The max BigDecimal of the range or <code>null</code> in case
37
	 *            no upper bound is defined.
38
	 * @param minConstraint
39
	 *            The type of constraint imposed by the lower bound of the
40
	 *            range.
41
	 * @param maxConstraint
42
	 *            The type of constraint imposed by the upper bound of the
43
	 *            range.
44
	 * @param validationMessage
45
	 *            The validation message pattern to use. Can be parameterized by
46
	 *            the lower and upper bound of the range, if defined.
47
	 * @param format
48
	 *            The BigDecimal format to use for formatting integers in the
49
	 *            validation message.
50
	 */
51
	private BigDecimalRangeValidator(BigDecimal min, BigDecimal max,
52
			int minConstraint, int maxConstraint, String validationMessage,
53
			NumberFormat format) {
54
		super(min, max, minConstraint, maxConstraint, validationMessage, format);
55
	}
56
57
	/**
58
	 * Creates a validator which checks that an input BigDecimal is greater than
59
	 * the given number.
60
	 * 
61
	 * @param number
62
	 *            The reference number of the greater constraint.
63
	 * @param validationMessage
64
	 *            The validation message pattern to use. Can be parameterized
65
	 *            with the given reference number.
66
	 * @param format
67
	 *            The display format to use for formatting BigDecimals in the
68
	 *            validation message.
69
	 * @return The validator instance.
70
	 */
71
	public static BigDecimalRangeValidator greater(BigDecimal number,
72
			String validationMessage, NumberFormat format) {
73
		return new BigDecimalRangeValidator(number, null, GREATER, UNDEFINED,
74
				defaultIfNull(validationMessage, GREATER_MESSAGE), format);
75
	}
76
77
	/**
78
	 * Creates a validator which checks that an input BigDecimal is greater than
79
	 * or equal to the given number.
80
	 * 
81
	 * @param number
82
	 *            The reference number of the greater-equal constraint.
83
	 * @param validationMessage
84
	 *            The validation message pattern to use. Can be parameterized
85
	 *            with the given reference number.
86
	 * @param format
87
	 *            The display format to use for formatting BigDecimals in the
88
	 *            validation message.
89
	 * @return The validator instance.
90
	 */
91
	public static BigDecimalRangeValidator greaterEqual(BigDecimal number,
92
			String validationMessage, NumberFormat format) {
93
		return new BigDecimalRangeValidator(number, null, GREATER_EQUAL,
94
				UNDEFINED, defaultIfNull(validationMessage,
95
						GREATER_EQUAL_MESSAGE), format);
96
	}
97
98
	/**
99
	 * Creates a validator which checks that an input BigDecimal is less than
100
	 * the given number.
101
	 * 
102
	 * @param number
103
	 *            The reference number of the less constraint.
104
	 * @param validationMessage
105
	 *            The validation message pattern to use. Can be parameterized
106
	 *            with the given reference number.
107
	 * @param format
108
	 *            The display format to use for formatting BigDecimals in the
109
	 *            validation message.
110
	 * @return The validator instance.
111
	 */
112
	public static BigDecimalRangeValidator less(BigDecimal number,
113
			String validationMessage, NumberFormat format) {
114
		return new BigDecimalRangeValidator(null, number, UNDEFINED, LESS,
115
				defaultIfNull(validationMessage, LESS_MESSAGE), format);
116
	}
117
118
	/**
119
	 * Creates a validator which checks that an input BigDecimal is less than or
120
	 * equal to the given number.
121
	 * 
122
	 * @param number
123
	 *            The reference number of the less-equal constraint.
124
	 * @param validationMessage
125
	 *            The validation message pattern to use. Can be parameterized
126
	 *            with the given reference number.
127
	 * @param format
128
	 *            The display format to use for formatting BigDecimals in the
129
	 *            validation message.
130
	 * @return The validator instance.
131
	 */
132
	public static BigDecimalRangeValidator lessEqual(BigDecimal number,
133
			String validationMessage, NumberFormat format) {
134
		return new BigDecimalRangeValidator(null, number, UNDEFINED,
135
				LESS_EQUAL,
136
				defaultIfNull(validationMessage, LESS_EQUAL_MESSAGE), format);
137
	}
138
139
	/**
140
	 * Creates a validator which checks that an input BigDecimal is within the
141
	 * given range.
142
	 * 
143
	 * @param min
144
	 *            The lower bound of the range (inclusive).
145
	 * @param max
146
	 *            The upper bound of the range (inclusive).
147
	 * @param validationMessage
148
	 *            The validation message pattern to use. Can be parameterized
149
	 *            with the range's lower and upper bound.
150
	 * @param format
151
	 *            The display format to use for formatting BigDecimals in the
152
	 *            validation message.
153
	 * @return The validator instance.
154
	 */
155
	public static BigDecimalRangeValidator range(BigDecimal min,
156
			BigDecimal max, String validationMessage, NumberFormat format) {
157
		return new BigDecimalRangeValidator(min, max, GREATER_EQUAL,
158
				LESS_EQUAL, defaultIfNull(validationMessage,
159
						WITHIN_RANGE_MESSAGE), format);
160
	}
161
162
	/**
163
	 * Creates a validator which checks that an input BigDecimal is positive.
164
	 * 
165
	 * @param validationMessage
166
	 *            The validation message to use.
167
	 * @param format
168
	 *            The display format to use for formatting BigDecimals in the
169
	 *            validation message.
170
	 * @return The validator instance.
171
	 */
172
	public static BigDecimalRangeValidator positive(String validationMessage,
173
			NumberFormat format) {
174
		return new BigDecimalRangeValidator(ONE, null, GREATER_EQUAL,
175
				UNDEFINED, defaultIfNull(validationMessage, POSITIVE_MESSAGE),
176
				format);
177
	}
178
179
	/**
180
	 * Creates a validator which checks that an input BigDecimal is
181
	 * non-negative.
182
	 * 
183
	 * @param validationMessage
184
	 *            The validation message to use.
185
	 * @param format
186
	 *            The display format to use for formatting BigDecimals in the
187
	 *            validation message.
188
	 * @return The validator instance.
189
	 */
190
	public static BigDecimalRangeValidator nonNegative(
191
			String validationMessage, NumberFormat format) {
192
		return new BigDecimalRangeValidator(ZERO, null, GREATER_EQUAL,
193
				UNDEFINED, defaultIfNull(validationMessage,
194
						NON_NEGATIVE_MESSAGE), format);
195
	}
196
197
	protected int compare(Number number1, Number number2) {
198
		BigDecimal bigDecimal1 = (BigDecimal) number1;
199
		BigDecimal bigDecimal2 = (BigDecimal) number2;
200
		return bigDecimal1.compareTo(bigDecimal2);
201
	}
202
203
	private static String defaultIfNull(String string, String defaultString) {
204
		return (string != null) ? string : defaultString;
205
	}
206
}
(-)src/org/eclipse/core/internal/databinding/conversion/BooleanToStringConverter.java (+60 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.conversion;
13
14
import org.eclipse.core.databinding.conversion.Converter;
15
16
/**
17
 * @since 1.3
18
 */
19
public class BooleanToStringConverter extends Converter {
20
21
	// Those are the defaults used up to now in UpdateStrategy where a simple
22
	// ObjectToStringConverter was used for converting booleans to strings.
23
	// FIXME: Should/may we change this to convert to a localized string?
24
	private String trueValue = Boolean.TRUE.toString();
25
	private String falseValue = Boolean.FALSE.toString();
26
27
	/**
28
	 * Creates a new converter which converts a boolean to its default string
29
	 * representation.
30
	 * 
31
	 * @param booleanType
32
	 *            The boolean type. Must be one of {@code Boolean.TYPE} or
33
	 *            {@code Boolean.class}.
34
	 */
35
	public BooleanToStringConverter(Class booleanType) {
36
		super(booleanType, String.class);
37
	}
38
39
	/**
40
	 * Sets the string values to which a <code>true</code> and
41
	 * <code>false</code> value should be converted.
42
	 * 
43
	 * @param trueValue
44
	 *            The string to which to convert a <code>true</code> value.
45
	 * @param falseValue
46
	 *            The string to which to convert a <code>false</code> value.
47
	 */
48
	public final void setTargetStrings(String trueValue, String falseValue) {
49
		this.trueValue = trueValue;
50
		this.falseValue = falseValue;
51
	}
52
53
	public Object convert(Object source) {
54
		Boolean value = (Boolean) source;
55
		if (value != null) {
56
			return value.booleanValue() ? trueValue : falseValue;
57
		}
58
		return ""; //$NON-NLS-1$
59
	}
60
}
(-)src/org/eclipse/core/databinding/editing/BigIntegerEditing.java (+197 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.editing;
13
14
import java.math.BigInteger;
15
16
import org.eclipse.core.databinding.conversion.NumberToStringConverter;
17
import org.eclipse.core.databinding.conversion.StringToNumberConverter;
18
import org.eclipse.core.databinding.validation.constraint.BigIntegerConstraints;
19
import org.eclipse.core.databinding.validation.constraint.Constraints;
20
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
21
import org.eclipse.core.internal.databinding.validation.AbstractStringToNumberValidator;
22
import org.eclipse.core.internal.databinding.validation.StringToBigIntegerValidator;
23
24
import com.ibm.icu.text.NumberFormat;
25
26
/**
27
 * @noextend This class is not intended to be subclassed by clients.
28
 * @since 1.3
29
 */
30
public class BigIntegerEditing extends Editing {
31
32
	private final NumberFormat displayFormat;
33
34
	/**
35
	 * Creates a new editing object for <code>BigInteger</code>s.
36
	 * 
37
	 * @param format
38
	 *            The BigInteger format defining the validations and conversions
39
	 *            used for editing.
40
	 * @param parseErrorMessage
41
	 *            The validation message issued in case the input string cannot
42
	 *            be parsed to a BigInteger.
43
	 * 
44
	 * @noreference This constructor is not intended to be referenced by
45
	 *              clients.
46
	 */
47
	protected BigIntegerEditing(NumberFormat format, String parseErrorMessage) {
48
		this.displayFormat = format;
49
50
		final StringToNumberConverter targetConverter = StringToNumberConverter
51
				.toBigInteger(format);
52
		final NumberToStringConverter modelConverter = NumberToStringConverter
53
				.fromBigInteger(format);
54
55
		final AbstractStringToNumberValidator targetValidator = new StringToBigIntegerValidator(
56
				targetConverter);
57
		if (parseErrorMessage != null) {
58
			targetValidator.setParseErrorMessage(parseErrorMessage);
59
		}
60
61
		setTargetConverter(targetConverter);
62
		setModelConverter(modelConverter);
63
		targetConstraints().addValidator(targetValidator);
64
	}
65
66
	/**
67
	 * Creates a new editing object for {@link BigInteger}s which defaults the
68
	 * validations and conversions used for editing based on the platform's
69
	 * locale. Uses the default validation messages.
70
	 * 
71
	 * @return The new editing object using the default validations and
72
	 *         conversions for editing.
73
	 * 
74
	 * @see NumberFormat#getIntegerInstance()
75
	 */
76
	public static BigIntegerEditing withDefaults() {
77
		return withDefaults(null);
78
	}
79
80
	/**
81
	 * Creates a new editing object for {@link BigInteger}s which defaults the
82
	 * validations and conversions used for editing based on the platform's
83
	 * locale. Uses the specified custom validation message.
84
	 * 
85
	 * @param parseErrorMessage
86
	 *            The validation message issued in case the input string cannot
87
	 *            be parsed to a BigInteger.
88
	 * @return The new editing object using the default validations and
89
	 *         conversions for editing.
90
	 * 
91
	 * @see NumberFormat#getIntegerInstance()
92
	 */
93
	public static BigIntegerEditing withDefaults(String parseErrorMessage) {
94
		return new BigIntegerEditing(NumberFormat.getIntegerInstance(),
95
				parseErrorMessage);
96
	}
97
98
	/**
99
	 * Creates a new editing object for {@link BigInteger}s whose validations
100
	 * and conversions used for editing are based on the given BigInteger
101
	 * format. Uses the default validation messages.
102
	 * 
103
	 * @param format
104
	 *            The BigInteger format defining the validations and conversions
105
	 *            used for editing.
106
	 * @return The new editing object configured by the given BigInteger format.
107
	 */
108
	public static BigIntegerEditing forFormat(NumberFormat format) {
109
		return forFormat(format, null);
110
	}
111
112
	/**
113
	 * Creates a new editing object for {@link BigInteger}s whose validations
114
	 * and conversions used for editing are based on the given BigInteger
115
	 * format. Uses the specified custom validation message.
116
	 * 
117
	 * @param format
118
	 *            The BigInteger format defining the validations and conversions
119
	 *            used for editing.
120
	 * @param parseErrorMessage
121
	 *            The validation message issued in case the input string cannot
122
	 *            be parsed to a BigInteger.
123
	 * @return The new editing object configured by the given BigInteger format.
124
	 */
125
	public static BigIntegerEditing forFormat(NumberFormat format,
126
			String parseErrorMessage) {
127
		return new BigIntegerEditing(format, parseErrorMessage);
128
	}
129
130
	/**
131
	 * Returns the target constraints to apply.
132
	 * 
133
	 * <p>
134
	 * This method provides a typesafe access to the {@link StringConstraints
135
	 * string target constraints} of this editing object and is equivalent to
136
	 * {@code (StringConstraints) targetConstraints()}.
137
	 * </p>
138
	 * 
139
	 * @return The target constraints to apply.
140
	 * 
141
	 * @see #targetConstraints()
142
	 * @see StringConstraints
143
	 */
144
	public StringConstraints targetStringConstraints() {
145
		return (StringConstraints) targetConstraints();
146
	}
147
148
	/**
149
	 * Returns the model constraints to apply.
150
	 * 
151
	 * <p>
152
	 * This method provides a typesafe access to the
153
	 * {@link BigIntegerConstraints BigInteger model constraints} of this
154
	 * editing object and is equivalent to {@code (BigIntegerConstraints)
155
	 * modelConstraints()}.
156
	 * </p>
157
	 * 
158
	 * @return The model constraints to apply.
159
	 * 
160
	 * @see #modelConstraints()
161
	 * @see BigIntegerConstraints
162
	 */
163
	public BigIntegerConstraints modelBigIntegerConstraints() {
164
		return (BigIntegerConstraints) modelConstraints();
165
	}
166
167
	/**
168
	 * Returns the before-set model constraints to apply.
169
	 * 
170
	 * <p>
171
	 * This method provides a typesafe access to the
172
	 * {@link BigIntegerConstraints BigInteger before-set model constraints} of
173
	 * this editing object and is equivalent to {@code (BigIntegerConstraints)
174
	 * beforeSetModelConstraints()}.
175
	 * </p>
176
	 * 
177
	 * @return The before-set model constraints to apply.
178
	 * 
179
	 * @see #beforeSetModelConstraints()
180
	 * @see BigIntegerConstraints
181
	 */
182
	public BigIntegerConstraints beforeSetModelBigIntegerConstraints() {
183
		return (BigIntegerConstraints) beforeSetModelConstraints();
184
	}
185
186
	protected Constraints createTargetConstraints() {
187
		return new StringConstraints();
188
	}
189
190
	protected Constraints createModelConstraints() {
191
		return new BigIntegerConstraints().bigIntegerFormat(displayFormat);
192
	}
193
194
	protected Constraints createBeforeSetModelConstraints() {
195
		return new BigIntegerConstraints().bigIntegerFormat(displayFormat);
196
	}
197
}
(-)src/org/eclipse/core/databinding/validation/constraint/IntegerConstraints.java (+322 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.databinding.validation.constraint;
13
14
import org.eclipse.core.internal.databinding.validation.IntegerRangeValidator;
15
import org.eclipse.core.internal.databinding.validation.NonNullValidator;
16
17
import com.ibm.icu.text.NumberFormat;
18
19
/**
20
 * Provides a set of constraints to apply to integer numbers.
21
 * 
22
 * <p>
23
 * Instances of this class can be used to define a set of constraints to apply
24
 * to integer numbers. In addition, the validation messages to be issued for the
25
 * individual constraints as well as the way in which model objects are
26
 * formatted in the validation messages can be configured.
27
 * </p>
28
 * 
29
 * <p>
30
 * The integer types supported by this class are <code>long</code>,
31
 * <code>int</code>, <code>short</code>, and <code>byte</code>.
32
 * </p>
33
 * 
34
 * @noextend This class is not intended to be subclassed by clients.
35
 * @since 1.3
36
 */
37
public class IntegerConstraints extends Constraints {
38
39
	private NumberFormat integerFormat = NumberFormat.getIntegerInstance();
40
41
	private String requiredMessage = null;
42
43
	private String greaterMessage = null;
44
45
	private String greaterEqualMessage = null;
46
47
	private String lessMessage = null;
48
49
	private String lessEqualMessage = null;
50
51
	private String rangeMessage = null;
52
53
	private String positiveMessage = null;
54
55
	private String nonNegativeMessage = null;
56
57
	/**
58
	 * Sets the format to use when formatting an integer to be included in any
59
	 * of the validation messages.
60
	 * 
61
	 * @param format
62
	 *            The format to use for displaying integers in validation
63
	 *            messages.
64
	 * @return This constraints instance for method chaining.
65
	 */
66
	public IntegerConstraints integerFormat(NumberFormat format) {
67
		this.integerFormat = format;
68
		return this;
69
	}
70
71
	/**
72
	 * Adds a validator ensuring that the input integer is not <code>null</code>
73
	 * . Uses the current {@link #requiredMessage(String) validation message}.
74
	 * 
75
	 * @return This constraints instance for method chaining.
76
	 */
77
	public IntegerConstraints required() {
78
		addValidator(new NonNullValidator(requiredMessage));
79
		return this;
80
	}
81
82
	/**
83
	 * Sets the validation message for the {@link #required()} constraint.
84
	 * 
85
	 * @param message
86
	 *            The validation message for the {@link #required()} constraint.
87
	 * @return This constraints instance for method chaining.
88
	 * 
89
	 * @see #required()
90
	 */
91
	public IntegerConstraints requiredMessage(String message) {
92
		this.requiredMessage = message;
93
		return this;
94
	}
95
96
	/**
97
	 * Adds a validator ensuring that the input integer is greater than the
98
	 * given number. Uses the current {@link #greaterMessage(String) validation
99
	 * message} and {@link #integerFormat(NumberFormat) integer format}.
100
	 * 
101
	 * @param number
102
	 *            The number which the input integer must be greater than.
103
	 * @return This constraints instance for method chaining.
104
	 */
105
	public IntegerConstraints greater(long number) {
106
		addValidator(IntegerRangeValidator.greater(number, greaterMessage,
107
				integerFormat));
108
		return this;
109
	}
110
111
	/**
112
	 * Sets the validation message pattern for the {@link #greater(long)}
113
	 * constraint.
114
	 * 
115
	 * @param message
116
	 *            The validation message pattern for the {@link #greater(long)}
117
	 *            constraint. Can be parameterized with the number ({0}) which
118
	 *            the input integer must be greater than.
119
	 * @return This constraints instance for method chaining.
120
	 * 
121
	 * @see #greater(long)
122
	 */
123
	public IntegerConstraints greaterMessage(String message) {
124
		this.greaterMessage = message;
125
		return this;
126
	}
127
128
	/**
129
	 * Adds a validator ensuring that the input integer is greater than or equal
130
	 * to the given number. Uses the current
131
	 * {@link #greaterEqualMessage(String) validation message} and
132
	 * {@link #integerFormat(NumberFormat) integer format}.
133
	 * 
134
	 * @param number
135
	 *            The number which the input integer must be greater than or
136
	 *            equal to.
137
	 * @return This constraints instance for method chaining.
138
	 */
139
	public IntegerConstraints greaterEqual(long number) {
140
		addValidator(IntegerRangeValidator.greaterEqual(number,
141
				greaterEqualMessage, integerFormat));
142
		return this;
143
	}
144
145
	/**
146
	 * Sets the validation message pattern for the {@link #greaterEqual(long)}
147
	 * constraint.
148
	 * 
149
	 * @param message
150
	 *            The validation message pattern for the
151
	 *            {@link #greaterEqual(long)} constraint. Can be parameterized
152
	 *            with the number ({0}) which the input integer must be greater
153
	 *            than or equal to.
154
	 * @return This constraints instance for method chaining.
155
	 * 
156
	 * @see #greaterEqual(long)
157
	 */
158
	public IntegerConstraints greaterEqualMessage(String message) {
159
		this.greaterEqualMessage = message;
160
		return this;
161
	}
162
163
	/**
164
	 * Adds a validator ensuring that the input integer is less than the given
165
	 * number. Uses the current {@link #lessMessage(String) validation message}
166
	 * and {@link #integerFormat(NumberFormat) integer format}.
167
	 * 
168
	 * @param number
169
	 *            The number which the input integer must be less than.
170
	 * @return This constraints instance for method chaining.
171
	 */
172
	public IntegerConstraints less(long number) {
173
		addValidator(IntegerRangeValidator.less(number, lessMessage,
174
				integerFormat));
175
		return this;
176
	}
177
178
	/**
179
	 * Sets the validation message pattern for the {@link #less(long)}
180
	 * constraint.
181
	 * 
182
	 * @param message
183
	 *            The validation message pattern for the {@link #less(long)}
184
	 *            constraint. Can be parameterized with the number ({0}) which
185
	 *            the input integer must be less than.
186
	 * @return This constraints instance for method chaining.
187
	 * 
188
	 * @see #less(long)
189
	 */
190
	public IntegerConstraints lessMessage(String message) {
191
		this.lessMessage = message;
192
		return this;
193
	}
194
195
	/**
196
	 * Adds a validator ensuring that the input integer is less than or equal to
197
	 * the given number. Uses the current {@link #lessEqualMessage(String)
198
	 * validation message} and {@link #integerFormat(NumberFormat) integer
199
	 * format}.
200
	 * 
201
	 * @param number
202
	 *            The number which the input integer must be less than or equal
203
	 *            to.
204
	 * @return This constraints instance for method chaining.
205
	 */
206
	public IntegerConstraints lessEqual(long number) {
207
		addValidator(IntegerRangeValidator.greaterEqual(number,
208
				lessEqualMessage, integerFormat));
209
		return this;
210
	}
211
212
	/**
213
	 * Sets the validation message pattern for the {@link #lessEqual(long)}
214
	 * constraint.
215
	 * 
216
	 * @param message
217
	 *            The validation message pattern for the
218
	 *            {@link #lessEqual(long)} constraint. Can be parameterized with
219
	 *            the number ({0}) which the input integer must be less than or
220
	 *            equal to.
221
	 * @return This constraints instance for method chaining.
222
	 * 
223
	 * @see #lessEqual(long)
224
	 */
225
	public IntegerConstraints lessEqualMessage(String message) {
226
		this.lessEqualMessage = message;
227
		return this;
228
	}
229
230
	/**
231
	 * Adds a validator ensuring that the input integer is within the given
232
	 * range. Uses the current {@link #rangeMessage(String) validation message}
233
	 * and {@link #integerFormat(NumberFormat) integer format}.
234
	 * 
235
	 * @param min
236
	 *            The lower bound of the range (inclusive).
237
	 * @param max
238
	 *            The upper bound of the range (inclusive).
239
	 * @return This constraints instance for method chaining.
240
	 */
241
	public IntegerConstraints range(long min, long max) {
242
		addValidator(IntegerRangeValidator.range(min, max, rangeMessage,
243
				integerFormat));
244
		return this;
245
	}
246
247
	/**
248
	 * Sets the validation message pattern for the {@link #range(long, long)}
249
	 * constraint.
250
	 * 
251
	 * @param message
252
	 *            The validation message pattern for the
253
	 *            {@link #range(long, long)} constraint. Can be parameterized
254
	 *            with the min ({0}) and max ({1}) values of the range in which
255
	 *            the input integer must lie.
256
	 * @return This constraints instance for method chaining.
257
	 * 
258
	 * @see #range(long, long)
259
	 */
260
	public IntegerConstraints rangeMessage(String message) {
261
		this.rangeMessage = message;
262
		return this;
263
	}
264
265
	/**
266
	 * Adds a validator ensuring that the input integer is positive. Uses the
267
	 * current {@link #positiveMessage(String) validation message} and
268
	 * {@link #integerFormat(NumberFormat) integer format}.
269
	 * 
270
	 * @return This constraints instance for method chaining.
271
	 */
272
	public IntegerConstraints positive() {
273
		addValidator(IntegerRangeValidator.positive(positiveMessage,
274
				integerFormat));
275
		return this;
276
	}
277
278
	/**
279
	 * Sets the validation message pattern for the {@link #positive()}
280
	 * constraint.
281
	 * 
282
	 * @param message
283
	 *            The validation message pattern for the {@link #positive()}
284
	 *            constraint.
285
	 * @return This constraints instance for method chaining.
286
	 * 
287
	 * @see #positive()
288
	 */
289
	public IntegerConstraints positiveMessage(String message) {
290
		this.positiveMessage = message;
291
		return this;
292
	}
293
294
	/**
295
	 * Adds a validator ensuring that the input integer is non-negative. Uses
296
	 * the current {@link #nonNegativeMessage(String) validation message} and
297
	 * {@link #integerFormat(NumberFormat) integer format}.
298
	 * 
299
	 * @return This constraints instance for method chaining.
300
	 */
301
	public IntegerConstraints nonNegative() {
302
		addValidator(IntegerRangeValidator.nonNegative(nonNegativeMessage,
303
				integerFormat));
304
		return this;
305
	}
306
307
	/**
308
	 * Sets the validation message pattern for the {@link #nonNegative()}
309
	 * constraint.
310
	 * 
311
	 * @param message
312
	 *            The validation message pattern for the {@link #nonNegative()}
313
	 *            constraint.
314
	 * @return This constraints instance for method chaining.
315
	 * 
316
	 * @see #nonNegative()
317
	 */
318
	public IntegerConstraints nonNegativeMessage(String message) {
319
		this.nonNegativeMessage = message;
320
		return this;
321
	}
322
}
(-)src/org/eclipse/core/internal/databinding/validation/NonEmptyStringValidator.java (+51 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.validation;
13
14
import org.eclipse.core.databinding.validation.IValidator;
15
import org.eclipse.core.databinding.validation.ValidationStatus;
16
import org.eclipse.core.internal.databinding.BindingMessages;
17
import org.eclipse.core.runtime.IStatus;
18
19
/**
20
 * @since 1.3
21
 */
22
public class NonEmptyStringValidator implements IValidator {
23
24
	private static final String NON_EMPTY_STRING_VALIDATION_MESSAGE = BindingMessages
25
			.getString(BindingMessages.VALIDATE_NON_EMPTY_STRING);
26
27
	private final String validationMessage;
28
29
	/**
30
	 * 
31
	 */
32
	public NonEmptyStringValidator() {
33
		this(null);
34
	}
35
36
	/**
37
	 * @param validationMessage
38
	 */
39
	public NonEmptyStringValidator(String validationMessage) {
40
		this.validationMessage = validationMessage != null ? validationMessage
41
				: NON_EMPTY_STRING_VALIDATION_MESSAGE;
42
	}
43
44
	public IStatus validate(Object value) {
45
		String input = (String) value;
46
		if (input == null || input.length() == 0) {
47
			return ValidationStatus.error(validationMessage);
48
		}
49
		return ValidationStatus.ok();
50
	}
51
}
(-)src/org/eclipse/core/internal/databinding/conversion/StringStripConverter.java (+61 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.core.internal.databinding.conversion;
13
14
import org.eclipse.core.databinding.conversion.Converter;
15
16
/**
17
 * @since 1.3
18
 */
19
public class StringStripConverter extends Converter {
20
21
	private final boolean stripToNull;
22
23
	/**
24
	 * 
25
	 * @param stripToNull
26
	 */
27
	public StringStripConverter(boolean stripToNull) {
28
		super(String.class, String.class);
29
		this.stripToNull = stripToNull;
30
	}
31
32
	public Object convert(Object fromObject) {
33
		String string = (String) fromObject;
34
35
		if (string != null && string.length() != 0) {
36
			int stripStart = 0;
37
			while (stripStart < string.length()
38
					&& Character.isWhitespace(string.charAt(stripStart))) {
39
				stripStart++;
40
			}
41
42
			int stripEnd = string.length() - 1;
43
			while (stripEnd >= stripStart
44
					&& Character.isWhitespace(string.charAt(stripEnd))) {
45
				stripEnd--;
46
			}
47
48
			if (stripStart <= stripEnd) {
49
				string = string.substring(stripStart, stripEnd + 1);
50
			} else {
51
				string = ""; //$NON-NLS-1$
52
			}
53
		}
54
55
		if (stripToNull && string != null && string.length() == 0) {
56
			string = null;
57
		}
58
59
		return string;
60
	}
61
}
(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 17-21 Link Here
17
 org.eclipse.jface.examples.databinding.mask.internal;x-internal:=true,
17
 org.eclipse.jface.examples.databinding.mask.internal;x-internal:=true,
18
 org.eclipse.jface.examples.databinding.model;x-internal:=false,
18
 org.eclipse.jface.examples.databinding.model;x-internal:=false,
19
 org.eclipse.jface.examples.databinding.radioGroup;x-internal:=false
19
 org.eclipse.jface.examples.databinding.radioGroup;x-internal:=false
20
Import-Package: com.ibm.icu.text
20
Import-Package: com.ibm.icu.math,
21
 com.ibm.icu.text
21
Bundle-RequiredExecutionEnvironment: J2SE-1.5
22
Bundle-RequiredExecutionEnvironment: J2SE-1.5
(-)src/org/eclipse/jface/examples/databinding/util/ObservableMapEditingSupport.java (+88 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.jface.examples.databinding.util;
13
14
import org.eclipse.core.databinding.editing.Editing;
15
import org.eclipse.core.databinding.observable.map.IObservableMap;
16
import org.eclipse.core.databinding.util.Policy;
17
import org.eclipse.core.runtime.IStatus;
18
import org.eclipse.core.runtime.MultiStatus;
19
import org.eclipse.jface.dialogs.MessageDialog;
20
import org.eclipse.jface.viewers.CellEditor;
21
import org.eclipse.jface.viewers.ColumnViewer;
22
import org.eclipse.jface.viewers.EditingSupport;
23
import org.eclipse.jface.viewers.TextCellEditor;
24
import org.eclipse.swt.widgets.Composite;
25
26
/**
27
 * @since 3.2
28
 */
29
public class ObservableMapEditingSupport extends EditingSupport {
30
31
	private final IObservableMap attributeMap;
32
33
	private final Editing editing;
34
35
	private final CellEditor cellEditor;
36
37
	public ObservableMapEditingSupport(ColumnViewer viewer, IObservableMap attributeMap, Editing editing) {
38
		super(viewer);
39
		this.attributeMap = attributeMap;
40
		this.editing = editing;
41
		this.cellEditor = new TextCellEditor((Composite) getViewer().getControl());
42
	}
43
44
	protected boolean canEdit(Object element) {
45
		return true;
46
	}
47
48
	protected CellEditor getCellEditor(Object element) {
49
		return cellEditor;
50
	}
51
52
	protected Object getValue(Object element) {
53
		return editing.convertToTarget(attributeMap.get(element));
54
	}
55
56
	protected void setValue(Object element, Object value) {
57
		MultiStatus validationStatus = new MultiStatus(Policy.JFACE_DATABINDING, 0, null, null);
58
		Object modelValue = editing.convertToModel(value, validationStatus);
59
		if (handleValidation(validationStatus)) {
60
			attributeMap.put(element, modelValue);
61
		}
62
	}
63
64
	private boolean handleValidation(IStatus validationStatus) {
65
		if (validationStatus.matches(IStatus.ERROR | IStatus.CANCEL)) {
66
			MessageDialog.openError(getViewer().getControl().getShell(), "Validation Error", getValidationMessage(validationStatus));
67
			return false;
68
		}
69
		return true;
70
	}
71
72
	private static String getValidationMessage(IStatus validationStatus) {
73
		if (!validationStatus.isMultiStatus()) {
74
			return validationStatus.getMessage();
75
		}
76
77
		MultiStatus multiStatus = (MultiStatus) validationStatus;
78
		StringBuffer sb = new StringBuffer();
79
		IStatus[] childStatus = multiStatus.getChildren();
80
		for (int i = 0; i < childStatus.length; i++) {
81
			if (i > 0) {
82
				sb.append('\n');
83
			}
84
			sb.append(getValidationMessage(childStatus[i]));
85
		}
86
		return sb.toString();
87
	}
88
}
(-)src/org/eclipse/jface/examples/databinding/snippets/Snippet035Editing.java (+284 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2006, 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.jface.examples.databinding.snippets;
13
14
import java.util.Calendar;
15
import java.util.Date;
16
17
import org.eclipse.core.databinding.Binding;
18
import org.eclipse.core.databinding.DataBindingContext;
19
import org.eclipse.core.databinding.editing.BooleanEditing;
20
import org.eclipse.core.databinding.editing.DateEditing;
21
import org.eclipse.core.databinding.editing.DecimalEditing;
22
import org.eclipse.core.databinding.editing.Editing;
23
import org.eclipse.core.databinding.editing.IntegerEditing;
24
import org.eclipse.core.databinding.editing.StringEditing;
25
import org.eclipse.core.databinding.observable.Realm;
26
import org.eclipse.core.databinding.observable.list.WritableList;
27
import org.eclipse.core.databinding.observable.value.IObservableValue;
28
import org.eclipse.core.databinding.observable.value.WritableValue;
29
import org.eclipse.core.databinding.validation.IValidator;
30
import org.eclipse.core.databinding.validation.ValidationStatus;
31
import org.eclipse.core.databinding.validation.constraint.Constraints;
32
import org.eclipse.core.databinding.validation.constraint.IntegerConstraints;
33
import org.eclipse.core.runtime.IStatus;
34
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
35
import org.eclipse.jface.databinding.swt.SWTObservables;
36
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
37
import org.eclipse.jface.examples.databinding.util.EditingFactory;
38
import org.eclipse.jface.internal.databinding.provisional.fieldassist.ControlDecorationSupport;
39
import org.eclipse.jface.layout.GridDataFactory;
40
import org.eclipse.jface.layout.GridLayoutFactory;
41
import org.eclipse.jface.viewers.LabelProvider;
42
import org.eclipse.jface.viewers.ListViewer;
43
import org.eclipse.swt.SWT;
44
import org.eclipse.swt.events.FocusAdapter;
45
import org.eclipse.swt.events.FocusEvent;
46
import org.eclipse.swt.events.SelectionAdapter;
47
import org.eclipse.swt.events.SelectionEvent;
48
import org.eclipse.swt.layout.GridLayout;
49
import org.eclipse.swt.widgets.Composite;
50
import org.eclipse.swt.widgets.Control;
51
import org.eclipse.swt.widgets.Display;
52
import org.eclipse.swt.widgets.Group;
53
import org.eclipse.swt.widgets.Label;
54
import org.eclipse.swt.widgets.Shell;
55
import org.eclipse.swt.widgets.Text;
56
57
import com.ibm.icu.text.MessageFormat;
58
59
public class Snippet035Editing {
60
61
	private DataBindingContext dbc;
62
63
	public static void main(String[] args) {
64
		Display display = new Display();
65
66
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
67
			public void run() {
68
				Shell shell = new Snippet035Editing().createShell();
69
				Display display = Display.getCurrent();
70
				while (!shell.isDisposed()) {
71
					if (!display.readAndDispatch()) {
72
						display.sleep();
73
					}
74
				}
75
			}
76
		});
77
	}
78
79
	private Shell createShell() {
80
		Display display = Display.getCurrent();
81
		Shell shell = new Shell(display);
82
		shell.setText("Editing");
83
		shell.setLayout(new GridLayout(1, false));
84
85
		dbc = new DataBindingContext();
86
87
		createValueSection(shell);
88
		createListSection(shell);
89
90
		shell.pack();
91
		shell.open();
92
93
		return shell;
94
	}
95
96
	private void createValueSection(Composite parent) {
97
		Group section = createSectionGroup(parent, "Value bindings", false);
98
99
		// Edit an e-mail address.
100
		Text emailText = createTextField(section, "E-Mail*");
101
		StringEditing emailEditing = EditingFactory.forEmailString();
102
		emailEditing.modelStringConstraints().required();
103
		bindTextField(emailText, new WritableValue(), emailEditing);
104
105
		// Edit a required, positive short using the default validation message.
106
		Text positiveText = createTextField(section, "Positive short*");
107
		IntegerEditing positiveEditing = EditingFactory.forShort();
108
		positiveEditing.modelIntegerConstraints().required().positive();
109
		bindTextField(positiveText, new WritableValue(), positiveEditing);
110
111
		// Edit a required double with a maximum of five significant and two
112
		// fractional digits.
113
		Text doubleText = createTextField(section, "Price [$]*");
114
		DecimalEditing priceEditing = EditingFactory.forDouble();
115
		priceEditing.modelDecimalConstraints().required().maxPrecision(5).maxScale(2);
116
		bindTextField(doubleText, new WritableValue(), priceEditing);
117
118
		// Edit an integer within the range [1, 100] using the default
119
		// validation message.
120
		Text rangeText = createTextField(section, "Value in [1, 100]");
121
		IntegerEditing rangeEditing = EditingFactory.forInteger();
122
		rangeEditing.modelIntegerConstraints().range(1, 100);
123
		bindTextField(rangeText, new WritableValue(0, null), rangeEditing);
124
125
		// Edit a percentage value which must lie within [0, 100] using a custom
126
		// validation message which indicates that the value actually represents
127
		// a percentage value. Note that the constraint message must be specified
128
		// before the actual constraint.
129
		Text percentText = createTextField(section, "Percentage [%]");
130
		IntegerEditing percentEditing = EditingFactory.forInteger();
131
		percentEditing.modelIntegerConstraints()
132
			.rangeMessage("Please specify a percentage value within [{0}, {1}].")
133
			.range(0, 100);
134
		bindTextField(percentText, new WritableValue(-1, null), percentEditing);
135
136
		// Edit a hex integer within the range [0x00, 0xff]. The range validation
137
		// message will display the range boundaries in hex format as well.
138
		Text hexText = createTextField(section, "Hex value in [0x00, 0xff]");
139
		IntegerEditing hexEditing = EditingFactory.forHexInteger(2);
140
		hexEditing.modelIntegerConstraints().range(0x00, 0xff);
141
		bindTextField(hexText, new WritableValue(0, null), hexEditing);
142
143
		// Edit a boolean value.
144
		Text boolText = createTextField(section, "Boolean value");
145
		BooleanEditing boolEditing = EditingFactory.forBoolean();
146
		bindTextField(boolText, new WritableValue(true, null), boolEditing);
147
148
		// Edit a value within [1, 10] or [20, 30].
149
		Text rangesText = createTextField(section, "Value in [1, 10] or [20, 30]");
150
		IntegerEditing rangesEditing = EditingFactory.forInteger();
151
		rangesEditing.modelIntegerConstraints().addValidator(new RangesValidator(1, 10, 20, 30));
152
		bindTextField(rangesText, new WritableValue(), rangesEditing);
153
	}
154
155
	private void createListSection(Composite parent) {
156
		Group section = createSectionGroup(parent, "List bindings", true);
157
158
		// Our date should be >= 01.01.1990.
159
		Calendar year1990Calendar = Calendar.getInstance();
160
		year1990Calendar.clear();
161
		year1990Calendar.set(1990, 0, 1);
162
		Date year1990 = year1990Calendar.getTime();
163
164
		// Edit a date supporting the default input/display patterns.
165
		Text dateText = createTextField(section, "Date");
166
		DateEditing dateEditing = EditingFactory.forDate();
167
		dateEditing.modelDateConstraints().afterEqual(year1990);
168
		final WritableValue dateObservable = new WritableValue();
169
		final Binding dateBinding = bindTextField(dateText, dateObservable, dateEditing);
170
171
		// Create a list to which the dates are added when the user hits ENTER.
172
		new Label(section, SWT.LEFT);
173
		ListViewer dateListViewer = new ListViewer(section);
174
		GridDataFactory.fillDefaults().grab(true, true).hint(150, 200).applyTo(dateListViewer.getList());
175
176
		dateListViewer.setContentProvider(new ObservableListContentProvider());
177
		dateListViewer.setLabelProvider(new LabelProvider());
178
179
		// We use the same DateEditing object as for the text field above to
180
		// create a list binding which maps the entered dates to their string
181
		// representation which is then set as input on the ListViewer.
182
		final WritableList targetDateList = new WritableList();
183
		final WritableList modelDateList = new WritableList();
184
		dateEditing.bindList(dbc, targetDateList, modelDateList);
185
186
		// Set the list containing the string representation of the dates as input.
187
		dateListViewer.setInput(targetDateList);
188
189
		// Add the current date in the text field when the user hits ENTER.
190
		dateText.addSelectionListener(new SelectionAdapter() {
191
			public void widgetDefaultSelected(SelectionEvent e) {
192
				IStatus dateValidationStatus = (IStatus) dateBinding.getValidationStatus().getValue();
193
				Date date = (Date) dateObservable.getValue();
194
				if (dateValidationStatus.isOK() && date != null) {
195
					modelDateList.add(date);
196
				}
197
			}
198
		});
199
	}
200
201
	private Binding bindTextField(Text text, IObservableValue modelValue, Editing editing) {
202
		// Create the binding using the editing object.
203
		ISWTObservableValue textObservable = SWTObservables.observeText(text, SWT.Modify);
204
		Binding binding = editing.bindValue(dbc, textObservable, modelValue);
205
206
		// Decorate the control with the validation status.
207
		ControlDecorationSupport.create(binding, SWT.TOP);
208
209
		// Re-format when the text field looses the focus in order to always
210
		// display the model in the default format in case multiple input formats
211
		// are supported.
212
		formatOnFocusOut(text, binding);
213
214
		return binding;
215
	}
216
217
	private static void formatOnFocusOut(final Control control, final Binding binding) {
218
		control.addFocusListener(new FocusAdapter() {
219
			public void focusLost(FocusEvent e) {
220
				IStatus dateValidationStatus = (IStatus) binding.getValidationStatus().getValue();
221
				if (dateValidationStatus.isOK()) {
222
					binding.updateModelToTarget();
223
				}
224
			}
225
		});
226
	}
227
228
	private static Group createSectionGroup(Composite parent, String groupText, boolean grabVertical) {
229
		Group section = new Group(parent, SWT.SHADOW_ETCHED_IN);
230
		section.setText(groupText);
231
		GridLayoutFactory.fillDefaults()
232
				.numColumns(2)
233
				.equalWidth(false)
234
				.margins(5, 5)
235
				.spacing(15, 5)
236
				.applyTo(section);
237
		GridDataFactory.fillDefaults().grab(true, grabVertical).applyTo(section);
238
		return section;
239
	}
240
241
	private static Text createTextField(Composite parent, String labelText) {
242
		Label label = new Label(parent, SWT.LEFT);
243
		label.setText(labelText);
244
		GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).applyTo(label);
245
246
		final Text text = new Text(parent, SWT.BORDER);
247
		GridDataFactory.fillDefaults().grab(true, false).hint(150, SWT.DEFAULT).applyTo(text);
248
249
		// Select the text when gaining focus.
250
		text.addFocusListener(new FocusAdapter() {
251
			public void focusGained(FocusEvent e) {
252
				text.selectAll();
253
			}
254
		});
255
256
		return text;
257
	}
258
259
	private static final class RangesValidator implements IValidator {
260
261
		private final String validationMessage;
262
263
		private final IValidator validator;
264
265
		public RangesValidator(int min1, int max1, int min2, int max2) {
266
			this.validationMessage = MessageFormat.format(
267
					"The value must lie within [{0}, {1}] or [{2}, {3}].",
268
					new Object[] { min1, max1, min2, max2 });
269
			this.validator =
270
				new IntegerConstraints()
271
					.range(min1, max1)
272
					.range(min2, max2)
273
					.aggregationPolicy(Constraints.AGGREGATION_MIN_SEVERITY)
274
					.createValidator();
275
		}
276
277
		public IStatus validate(Object value) {
278
			if (!validator.validate(value).isOK()) {
279
				return ValidationStatus.error(validationMessage);
280
			}
281
			return ValidationStatus.ok();
282
		}
283
	}
284
}
(-)src/org/eclipse/jface/examples/databinding/util/EditingFactory.java (+214 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.jface.examples.databinding.util;
13
14
import java.util.Locale;
15
16
import org.eclipse.core.databinding.editing.BooleanEditing;
17
import org.eclipse.core.databinding.editing.DateEditing;
18
import org.eclipse.core.databinding.editing.DecimalEditing;
19
import org.eclipse.core.databinding.editing.IntegerEditing;
20
import org.eclipse.core.databinding.editing.StringEditing;
21
22
import com.ibm.icu.text.DateFormat;
23
import com.ibm.icu.text.NumberFormat;
24
25
/**
26
 * @since 3.2
27
 */
28
public final class EditingFactory {
29
30
	private static final String REQUIRED_MESSAGE = "Please specify a value.";
31
32
	private static final String NUMBER_PARSE_ERROR_MESSAGE = "The input is invalid.";
33
34
	private static final String NUMBER_OUT_OF_RANGE_MESSAGE = "The value lies outside the supported range.";
35
36
	private static final String NUMBER_RANGE_MESSAGE = "The value must lie between {0} and {1}.";
37
38
	private static final String[] BOOLEAN_TRUE_VALUES = new String[] {
39
		"yes", "y", "true", "1"
40
	};
41
42
	private static final String[] BOOLEAN_FALSE_VALUES = new String[] {
43
		"no", "n", "false", "0"
44
	};
45
46
	private static final String[] DATE_INPUT_PATTERNS = new String[] {
47
		"yyMMdd",
48
		"yyyyMMdd"
49
	};
50
51
	private static final String DATE_DISPLAY_PATTERN = "yyyyMMdd";
52
53
	private static final String DATE_PARSE_ERROR_MESSAGE = createDateParseErrorMessage(DATE_INPUT_PATTERNS);
54
55
	private static final String EMAIL_REGEX = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b";
56
57
	private static final String EMAIL_ERROR_MESSAGE = "Please specify a valid e-mail address.";
58
59
	private EditingFactory() {
60
		// prevent instantiation
61
	}
62
63
	public static StringEditing forString() {
64
		return StringEditing.strippedToNull();
65
	}
66
67
	public static StringEditing forEmailString() {
68
		StringEditing editing = StringEditing.strippedToNull();
69
		editing.modelStringConstraints()
70
				.matchesMessage(EMAIL_ERROR_MESSAGE)
71
				.matches(EMAIL_REGEX);
72
		return editing;
73
	}
74
75
	public static IntegerEditing forLong() {
76
		return forLong(Locale.getDefault());
77
	}
78
79
	public static IntegerEditing forLong(Locale locale) {
80
		IntegerEditing editing = IntegerEditing.forLongFormat(
81
				NumberFormat.getIntegerInstance(locale),
82
				NUMBER_PARSE_ERROR_MESSAGE,
83
				NUMBER_OUT_OF_RANGE_MESSAGE);
84
		configure(editing, locale);
85
		return editing;
86
	}
87
88
	public static IntegerEditing forInteger() {
89
		return forInteger(Locale.getDefault());
90
	}
91
92
	public static IntegerEditing forInteger(Locale locale) {
93
		IntegerEditing editing = IntegerEditing.forIntegerFormat(
94
				NumberFormat.getIntegerInstance(locale),
95
				NUMBER_PARSE_ERROR_MESSAGE,
96
				NUMBER_OUT_OF_RANGE_MESSAGE);
97
		configure(editing, locale);
98
		return editing;
99
	}
100
101
	public static IntegerEditing forShort() {
102
		return forShort(Locale.getDefault());
103
	}
104
105
	public static IntegerEditing forShort(Locale locale) {
106
		IntegerEditing editing = IntegerEditing.forShortFormat(
107
				NumberFormat.getIntegerInstance(locale),
108
				NUMBER_PARSE_ERROR_MESSAGE,
109
				NUMBER_OUT_OF_RANGE_MESSAGE);
110
		configure(editing, locale);
111
		return editing;
112
	}
113
114
	public static IntegerEditing forByte() {
115
		return forByte(Locale.getDefault());
116
	}
117
118
	public static IntegerEditing forByte(Locale locale) {
119
		IntegerEditing editing = IntegerEditing.forByteFormat(
120
				NumberFormat.getIntegerInstance(locale),
121
				NUMBER_PARSE_ERROR_MESSAGE,
122
				NUMBER_OUT_OF_RANGE_MESSAGE);
123
		configure(editing, locale);
124
		return editing;
125
	}
126
127
	public static IntegerEditing forHexInteger(int digits) {
128
		RadixNumberFormat hexFormat = RadixNumberFormat.getHexInstance("0x", digits);
129
		IntegerEditing editing = IntegerEditing.forIntegerFormat(
130
				hexFormat,
131
				NUMBER_PARSE_ERROR_MESSAGE,
132
				NUMBER_OUT_OF_RANGE_MESSAGE);
133
		configure(editing, Locale.getDefault());
134
		editing.modelIntegerConstraints().integerFormat(hexFormat);
135
		return editing;
136
	}
137
138
	private static void configure(IntegerEditing editing, Locale locale) {
139
		editing.modelIntegerConstraints()
140
				.integerFormat(NumberFormat.getIntegerInstance(locale))
141
				.requiredMessage(REQUIRED_MESSAGE)
142
				.rangeMessage(NUMBER_RANGE_MESSAGE);
143
	}
144
145
	public static DecimalEditing forDouble() {
146
		return forDouble(Locale.getDefault());
147
	}
148
149
	public static DecimalEditing forDouble(Locale locale) {
150
		DecimalEditing editing = DecimalEditing.forDoubleFormat(
151
				NumberFormat.getNumberInstance(locale),
152
				NUMBER_PARSE_ERROR_MESSAGE,
153
				NUMBER_OUT_OF_RANGE_MESSAGE);
154
		configure(editing, locale);
155
		return editing;
156
	}
157
158
	private static void configure(DecimalEditing editing, Locale locale) {
159
		editing.modelDecimalConstraints()
160
				.decimalFormat(NumberFormat.getNumberInstance(locale))
161
				.scaleFormat(NumberFormat.getIntegerInstance(locale))
162
				.precisionFormat(NumberFormat.getIntegerInstance(locale))
163
				.requiredMessage(REQUIRED_MESSAGE)
164
				.rangeMessage(NUMBER_RANGE_MESSAGE);
165
	}
166
167
	public static BooleanEditing forBoolean() {
168
		BooleanEditing editing =
169
			BooleanEditing.forStringValues(
170
					BOOLEAN_TRUE_VALUES,
171
					BOOLEAN_FALSE_VALUES);
172
		configure(editing);
173
		return editing;
174
	}
175
176
	private static void configure(BooleanEditing editing) {
177
		editing.modelBooleanConstraints()
178
				.requiredMessage(REQUIRED_MESSAGE);
179
	}
180
181
	public static DateEditing forDate() {
182
		return forDate(Locale.getDefault());
183
	}
184
185
	public static DateEditing forDate(Locale locale) {
186
		DateEditing editing = DateEditing
187
				.forFormats(
188
						createDateFormats(DATE_INPUT_PATTERNS, locale),
189
						DATE_PARSE_ERROR_MESSAGE,
190
						DateFormat.getPatternInstance(DATE_DISPLAY_PATTERN, locale));
191
		editing.modelDateConstraints().requiredMessage(REQUIRED_MESSAGE);
192
		return editing;
193
	}
194
195
	private static DateFormat[] createDateFormats(String[] datePatterns, Locale locale) {
196
		DateFormat[] dateFormats = new DateFormat[datePatterns.length];
197
		for (int i = 0; i < dateFormats.length; i++) {
198
			dateFormats[i] = DateFormat.getPatternInstance(datePatterns[i], locale);
199
		}
200
		return dateFormats;
201
	}
202
203
	private static String createDateParseErrorMessage(String[] datePatterns) {
204
		StringBuffer messageSb = new StringBuffer();
205
		messageSb.append("Supported formats: ");
206
		for (int i = 0; i < datePatterns.length; i++) {
207
			if (i > 0) {
208
				messageSb.append(", ");
209
			}
210
			messageSb.append(datePatterns[i]);
211
		}
212
		return messageSb.toString();
213
	}
214
}
(-)src/org/eclipse/jface/examples/databinding/util/RadixNumberFormat.java (+99 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.jface.examples.databinding.util;
13
14
import java.math.BigInteger;
15
import java.text.FieldPosition;
16
import java.text.ParsePosition;
17
18
import com.ibm.icu.math.BigDecimal;
19
import com.ibm.icu.text.NumberFormat;
20
21
/**
22
 * @since 3.2
23
 *
24
 */
25
public class RadixNumberFormat extends NumberFormat {
26
27
	private static final long serialVersionUID = 411884077848863891L;
28
29
	private final int radix;
30
31
	private final String prefix;
32
33
	private final int digits;
34
35
	private RadixNumberFormat(int radix, String prefix, int digits) {
36
		this.radix = radix;
37
		this.prefix = prefix != null ? prefix : "";
38
		this.digits = digits;
39
	}
40
41
	public static RadixNumberFormat getHexInstance() {
42
		return getHexInstance(null, 0);
43
	}
44
45
	public static RadixNumberFormat getHexInstance(String prefix, int digits) {
46
		return new RadixNumberFormat(16, prefix, digits);
47
	}
48
49
	public StringBuffer format(double number, StringBuffer toAppendTo,
50
			FieldPosition pos) {
51
		return format((long) number, toAppendTo, pos);
52
	}
53
54
	public StringBuffer format(long number, StringBuffer toAppendTo,
55
			FieldPosition pos) {
56
		return toAppendTo.append(prefix).append(addPadding(Long.toString(number, radix)));
57
	}
58
59
	public StringBuffer format(BigInteger number, StringBuffer toAppendTo,
60
			FieldPosition pos) {
61
		return toAppendTo.append(prefix).append(addPadding(number.toString(radix)));
62
	}
63
64
	public StringBuffer format(BigDecimal number, StringBuffer toAppendTo,
65
			FieldPosition pos) {
66
		throw new UnsupportedOperationException();
67
	}
68
69
	public Number parse(String text, ParsePosition parsePosition) {
70
		if (text.length() == 0) {
71
			return null;
72
		}
73
74
		parsePosition.setIndex(parsePosition.getIndex() + text.length());
75
76
		try {
77
			if (text.startsWith(prefix)) {
78
				return Integer.parseInt(text.substring(prefix.length()), radix);
79
			}
80
			return Integer.parseInt(text, radix);
81
		} catch (NumberFormatException e) {
82
			parsePosition.setErrorIndex(0);
83
			return null;
84
		}
85
	}
86
87
	private String addPadding(String numberText) {
88
		if (numberText.length() >= digits) {
89
			return numberText;
90
		}
91
92
		StringBuffer sb = new StringBuffer();
93
		for (int i = numberText.length(); i < digits; i++) {
94
			sb.append('0');
95
		}
96
		sb.append(numberText);
97
		return sb.toString();
98
	}
99
}
(-)src/org/eclipse/jface/examples/databinding/util/ObservableMapEditingCellLabelProvider.java (+40 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.jface.examples.databinding.util;
13
14
import org.eclipse.core.databinding.editing.Editing;
15
import org.eclipse.core.databinding.observable.map.IObservableMap;
16
import org.eclipse.jface.databinding.viewers.ObservableMapCellLabelProvider;
17
import org.eclipse.jface.viewers.ViewerCell;
18
19
/**
20
 * @since 3.2
21
 */
22
public class ObservableMapEditingCellLabelProvider extends
23
		ObservableMapCellLabelProvider {
24
25
	private final IObservableMap attributeMap;
26
27
	private final Editing editing;
28
29
	public ObservableMapEditingCellLabelProvider(IObservableMap attributeMap, Editing editing) {
30
		super(attributeMap);
31
		this.attributeMap = attributeMap;
32
		this.editing = editing;
33
	}
34
35
	public void update(ViewerCell cell) {
36
		Object element = cell.getElement();
37
		Object attribute = attributeMap.get(element);
38
		cell.setText((String) editing.convertToTarget(attribute));
39
	}
40
}
(-)src/org/eclipse/jface/examples/databinding/snippets/Snippet036EditingTable.java (+261 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2006, 2009 Ovidio Mallo and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Ovidio Mallo - initial API and implementation (bug 183055)
10
 ******************************************************************************/
11
12
package org.eclipse.jface.examples.databinding.snippets;
13
14
import java.util.Date;
15
16
import org.eclipse.core.databinding.Binding;
17
import org.eclipse.core.databinding.DataBindingContext;
18
import org.eclipse.core.databinding.beans.BeansObservables;
19
import org.eclipse.core.databinding.editing.DateEditing;
20
import org.eclipse.core.databinding.editing.Editing;
21
import org.eclipse.core.databinding.editing.IntegerEditing;
22
import org.eclipse.core.databinding.editing.StringEditing;
23
import org.eclipse.core.databinding.observable.Realm;
24
import org.eclipse.core.databinding.observable.list.WritableList;
25
import org.eclipse.core.databinding.observable.map.IObservableMap;
26
import org.eclipse.core.databinding.observable.set.IObservableSet;
27
import org.eclipse.core.databinding.observable.value.IObservableValue;
28
import org.eclipse.core.runtime.IStatus;
29
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
30
import org.eclipse.jface.databinding.swt.SWTObservables;
31
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
32
import org.eclipse.jface.databinding.viewers.ViewersObservables;
33
import org.eclipse.jface.examples.databinding.ModelObject;
34
import org.eclipse.jface.examples.databinding.util.EditingFactory;
35
import org.eclipse.jface.examples.databinding.util.ObservableMapEditingCellLabelProvider;
36
import org.eclipse.jface.examples.databinding.util.ObservableMapEditingSupport;
37
import org.eclipse.jface.internal.databinding.provisional.fieldassist.ControlDecorationSupport;
38
import org.eclipse.jface.layout.GridDataFactory;
39
import org.eclipse.jface.layout.GridLayoutFactory;
40
import org.eclipse.jface.viewers.StructuredSelection;
41
import org.eclipse.jface.viewers.TableViewer;
42
import org.eclipse.jface.viewers.TableViewerColumn;
43
import org.eclipse.swt.SWT;
44
import org.eclipse.swt.events.FocusAdapter;
45
import org.eclipse.swt.events.FocusEvent;
46
import org.eclipse.swt.layout.GridLayout;
47
import org.eclipse.swt.widgets.Composite;
48
import org.eclipse.swt.widgets.Control;
49
import org.eclipse.swt.widgets.Display;
50
import org.eclipse.swt.widgets.Group;
51
import org.eclipse.swt.widgets.Label;
52
import org.eclipse.swt.widgets.Shell;
53
import org.eclipse.swt.widgets.Text;
54
55
public class Snippet036EditingTable {
56
57
	private StringEditing nameEditing;
58
59
	private IntegerEditing ageEditing;
60
61
	private DateEditing bdayEditing;
62
63
	private DataBindingContext dbc;
64
65
	private TableViewer tableViewer;
66
67
	public static void main(String[] args) {
68
		Display display = new Display();
69
70
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
71
			public void run() {
72
				Shell shell = new Snippet036EditingTable().createShell();
73
				Display display = Display.getCurrent();
74
				while (!shell.isDisposed()) {
75
					if (!display.readAndDispatch()) {
76
						display.sleep();
77
					}
78
				}
79
			}
80
		});
81
	}
82
83
	private Shell createShell() {
84
		Display display = Display.getCurrent();
85
		Shell shell = new Shell(display);
86
		shell.setText("Editing");
87
		shell.setLayout(new GridLayout(2, false));
88
89
		nameEditing = EditingFactory.forString();
90
		nameEditing.modelStringConstraints().required();
91
92
		ageEditing = EditingFactory.forInteger();
93
		ageEditing.modelIntegerConstraints().required().nonNegative();
94
95
		bdayEditing = EditingFactory.forDate();
96
		bdayEditing.modelDateConstraints().before(new Date());
97
98
		dbc = new DataBindingContext();
99
100
		createTableSection(shell);
101
		createFieldSection(shell);
102
103
		shell.pack();
104
		shell.open();
105
106
		return shell;
107
	}
108
109
	private void createTableSection(Composite parent) {
110
		Group section = createSectionGroup(parent, 1);
111
112
		tableViewer = new TableViewer(section, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
113
		GridDataFactory.fillDefaults().grab(true, true).hint(350, 250).applyTo(tableViewer.getTable());
114
		tableViewer.getTable().setHeaderVisible(true);
115
		tableViewer.getTable().setLinesVisible(true);
116
117
		ObservableListContentProvider contentProvider = new ObservableListContentProvider();
118
		tableViewer.setContentProvider(contentProvider);
119
		IObservableSet contentElements = contentProvider.getKnownElements();
120
121
		IObservableMap nameMap = BeansObservables.observeMap(contentElements, "name");
122
		createColumn("Name*", 150, nameMap, nameEditing);
123
124
		IObservableMap ageMap = BeansObservables.observeMap(contentElements, "age");
125
		createColumn("Age*", 50, ageMap, ageEditing);
126
127
		IObservableMap bdayMap = BeansObservables.observeMap(contentElements, "birthday");
128
		createColumn("Birthday", 80, bdayMap, bdayEditing);
129
130
		WritableList people = new WritableList();
131
		people.add(new Person("John Doe", 27));
132
		people.add(new Person("Steve Northover", 33));
133
		people.add(new Person("Grant Gayed", 54));
134
		people.add(new Person("Veronika Irvine", 25));
135
		people.add(new Person("Mike Wilson", 44));
136
		people.add(new Person("Christophe Cornu", 37));
137
		people.add(new Person("Lynne Kues", 65));
138
		people.add(new Person("Silenio Quarti", 15));
139
140
		tableViewer.setInput(people);
141
142
		tableViewer.setSelection(new StructuredSelection(people.get(0)));
143
	}
144
145
	private TableViewerColumn createColumn(String text, int width, IObservableMap attributeMap, Editing modelEditing) {
146
		TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
147
		column.getColumn().setText(text);
148
		column.getColumn().setWidth(width);
149
		column.setLabelProvider(new ObservableMapEditingCellLabelProvider(attributeMap, modelEditing));
150
		column.setEditingSupport(new ObservableMapEditingSupport(tableViewer, attributeMap, modelEditing));
151
		return column;
152
	}
153
154
	private void createFieldSection(Composite parent) {
155
		final Group section = createSectionGroup(parent, 2);
156
157
		final IObservableValue personObservable = ViewersObservables.observeSingleSelection(tableViewer);
158
159
		Text nameText = createTextField(section, "Name*");
160
		IObservableValue nameObservable = BeansObservables.observeDetailValue(personObservable, "name", null);
161
		bindTextField(nameText, nameObservable, nameEditing);
162
163
		Text ageText = createTextField(section, "Age*");
164
		IObservableValue ageObservable = BeansObservables.observeDetailValue(personObservable, "age", null);
165
		bindTextField(ageText, ageObservable, ageEditing);
166
167
		Text bdayText = createTextField(section, "Birthday");
168
		IObservableValue bdayObservable = BeansObservables.observeDetailValue(personObservable, "birthday", null);
169
		bindTextField(bdayText, bdayObservable, bdayEditing);
170
	}
171
172
	private Binding bindTextField(
173
			Text text,
174
			IObservableValue modelValue,
175
			Editing editing) {
176
		// Create the binding using the editing object.
177
		ISWTObservableValue textObservable = SWTObservables.observeText(text, SWT.Modify);
178
		Binding binding = editing.bindValue(dbc, textObservable, modelValue);
179
180
		// Decorate the control with the validation status.
181
		ControlDecorationSupport.create(binding, SWT.TOP);
182
183
		formatOnFocusOut(text, binding);
184
185
		return binding;
186
	}
187
188
	private static void formatOnFocusOut(final Control control, final Binding binding) {
189
		control.addFocusListener(new FocusAdapter() {
190
			public void focusLost(FocusEvent e) {
191
				IStatus dateValidationStatus = (IStatus) binding.getValidationStatus().getValue();
192
				if (dateValidationStatus.isOK()) {
193
					binding.updateModelToTarget();
194
				}
195
			}
196
		});
197
	}
198
199
	private Group createSectionGroup(Composite parent, int numColumns) {
200
		Group section = new Group(parent, SWT.SHADOW_ETCHED_IN);
201
		GridLayoutFactory.fillDefaults().numColumns(numColumns).equalWidth(false).margins(5, 5).spacing(15, 5).applyTo(section);
202
		GridDataFactory.fillDefaults().grab(true, true).applyTo(section);
203
		return section;
204
	}
205
206
	private static Text createTextField(Composite parent, String labelText) {
207
		Label label = new Label(parent, SWT.LEFT);
208
		label.setText(labelText);
209
		GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).applyTo(label);
210
211
		final Text text = new Text(parent, SWT.BORDER);
212
		GridDataFactory.fillDefaults().grab(true, false).hint(200, SWT.DEFAULT).applyTo(text);
213
214
		// Select the text when gaining focus.
215
		text.addFocusListener(new FocusAdapter() {
216
			public void focusGained(FocusEvent e) {
217
				text.selectAll();
218
			}
219
		});
220
221
		return text;
222
	}
223
224
	public static final class Person extends ModelObject {
225
226
		private String name;
227
228
		private int age;
229
230
		private Date birthday;
231
232
		public Person(String name, int age) {
233
			this.name = name;
234
			this.age = age;
235
		}
236
237
		public String getName() {
238
			return name;
239
		}
240
241
		public void setName(String name) {
242
			firePropertyChange("name", this.name, this.name = name);
243
		}
244
245
		public int getAge() {
246
			return age;
247
		}
248
249
		public void setAge(int age) {
250
			firePropertyChange("age", this.age, this.age = age);
251
		}
252
253
		public Date getBirthday() {
254
			return birthday;
255
		}
256
257
		public void setBirthday(Date birthday) {
258
			firePropertyChange("birthday", this.birthday, this.birthday = birthday);
259
		}
260
	}
261
}

Return to bug 183055