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

Collapse All | Expand All

(-)src/org/eclipse/core/internal/databinding/conversion/StringToNumberParser.java (-4 / +21 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-125 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(BindingMessages.VALIDATE_NUMBER_PARSE_ERROR,
119
			return BindingMessages.getFormattedString(BindingMessages.VALIDATE_NUMBER_PARSE_ERROR,
119
					new Object[] { value, new Integer(errorIndex + 1),
120
					new Object[] { value, new Integer(errorIndex + 1),
120
							new Character(value.charAt(errorIndex)) });
121
							new Character(value.charAt(errorIndex)) });
121
		}
122
		}
122
		return BindingMessages.formatString(BindingMessages.VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER,
123
		return BindingMessages.getFormattedString(BindingMessages.VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER,
123
				new Object[] { value, new Integer(errorIndex + 1) });
124
				new Object[] { value, new Integer(errorIndex + 1) });
124
	}
125
	}
125
126
Lines 133-138 Link Here
133
	 */
134
	 */
134
	public static String createOutOfRangeMessage(Number minValue,
135
	public static String createOutOfRangeMessage(Number minValue,
135
			Number maxValue, NumberFormat numberFormat) {
136
			Number maxValue, NumberFormat numberFormat) {
137
		return createOutOfRangeMessage(
138
				BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_OUT_OF_RANGE_ERROR), minValue, maxValue, numberFormat);
139
	}
140
141
	/**
142
	 * Formats an appropriate message for an out of range error.
143
	 * 
144
	 * @param message
145
	 * @param minValue
146
	 * @param maxValue
147
	 * @param numberFormat
148
	 *            when accessed method synchronizes on instance
149
	 * @return message
150
	 */
151
	public static String createOutOfRangeMessage(String message,
152
			Number minValue, Number maxValue, NumberFormat numberFormat) {
136
		String min = null;
153
		String min = null;
137
		String max = null;
154
		String max = null;
138
155
Lines 141-148 Link Here
141
			max = numberFormat.format(maxValue);
158
			max = numberFormat.format(maxValue);
142
		}
159
		}
143
160
144
		return BindingMessages.formatString(
161
		return BindingMessages.formatMessage(message, new Object[] { min,
145
				"Validate_NumberOutOfRangeError", new Object[] { min, max }); //$NON-NLS-1$
162
				max });
146
	}
163
	}
147
164
148
	/**
165
	/**
(-)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.
(-).settings/org.eclipse.jdt.ui.prefs (-2 / +2 lines)
Lines 1-4 Link Here
1
#Tue Feb 10 16:05:48 MST 2009
1
#Mon Sep 21 22:46:47 CEST 2009
2
cleanup.add_default_serial_version_id=true
2
cleanup.add_default_serial_version_id=true
3
cleanup.add_generated_serial_version_id=false
3
cleanup.add_generated_serial_version_id=false
4
cleanup.add_missing_annotations=true
4
cleanup.add_missing_annotations=true
Lines 78-84 Link Here
78
sp_cleanup.always_use_this_for_non_static_method_access=false
78
sp_cleanup.always_use_this_for_non_static_method_access=false
79
sp_cleanup.convert_to_enhanced_for_loop=false
79
sp_cleanup.convert_to_enhanced_for_loop=false
80
sp_cleanup.correct_indentation=false
80
sp_cleanup.correct_indentation=false
81
sp_cleanup.format_source_code=true
81
sp_cleanup.format_source_code=false
82
sp_cleanup.format_source_code_changes_only=false
82
sp_cleanup.format_source_code_changes_only=false
83
sp_cleanup.make_local_variable_final=false
83
sp_cleanup.make_local_variable_final=false
84
sp_cleanup.make_parameters_final=false
84
sp_cleanup.make_parameters_final=false
(-)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/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/BindingMessages.java (-4 / +111 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 109-118 Link Here
109
	public static final String VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER = "Validate_NumberParseErrorNoCharacter"; //$NON-NLS-1$
115
	public static final String VALIDATE_NUMBER_PARSE_ERROR_NO_CHARACTER = "Validate_NumberParseErrorNoCharacter"; //$NON-NLS-1$
110
116
111
	/**
117
	/**
118
	 * Key to be used for a "Validate_NonNull" message
119
	 */
120
	public static final String VALIDATE_NON_NULL = "Validate_NonNull"; //$NON-NLS-1$
121
122
	/**
123
	 * Key to be used for a "Validate_NonEmptyString" message
124
	 */
125
	public static final String VALIDATE_NON_EMPTY_STRING = "Validate_NonEmptyString"; //$NON-NLS-1$
126
127
	/**
128
	 * Key to be used for a "Validate_NonStringRegex" message
129
	 */
130
	public static final String VALIDATE_STRING_REGEX = "Validate_NonStringRegex"; //$NON-NLS-1$
131
132
	/**
133
	 * Key to be used for a "Validate_NumberRangeGreater" message
134
	 */
135
	public static final String VALIDATE_NUMBER_RANGE_GREATER = "Validate_NumberRangeGreater"; //$NON-NLS-1$
136
137
	/**
138
	 * Key to be used for a "Validate_NumberRangeGreaterEqual" message
139
	 */
140
	public static final String VALIDATE_NUMBER_RANGE_GREATER_EQUAL = "Validate_NumberRangeGreaterEqual"; //$NON-NLS-1$
141
142
	/**
143
	 * Key to be used for a "Validate_NumberRangeLess" message
144
	 */
145
	public static final String VALIDATE_NUMBER_RANGE_LESS = "Validate_NumberRangeLess"; //$NON-NLS-1$
146
147
	/**
148
	 * Key to be used for a "Validate_NumberRangeLessEqual" message
149
	 */
150
	public static final String VALIDATE_NUMBER_RANGE_LESS_EQUAL = "Validate_NumberRangeLessEqual"; //$NON-NLS-1$
151
152
	/**
153
	 * Key to be used for a "Validate_NumberRangeWithinRange" message
154
	 */
155
	public static final String VALIDATE_NUMBER_RANGE_WITHIN_RANGE = "Validate_NumberRangeWithinRange"; //$NON-NLS-1$
156
157
	/**
158
	 * Key to be used for a "Validate_NumberRangePositive" message
159
	 */
160
	public static final String VALIDATE_NUMBER_RANGE_POSITIVE = "Validate_NumberRangePositive"; //$NON-NLS-1$
161
162
	/**
163
	 * Key to be used for a "Validate_NumberRangeNonNegative" message
164
	 */
165
	public static final String VALIDATE_NUMBER_RANGE_NON_NEGATIVE = "Validate_NumberRangeNonNegative"; //$NON-NLS-1$
166
167
	/**
168
	 * Key to be used for a "Validate_DateRangeAfter" message
169
	 */
170
	public static final String VALIDATE_DATE_RANGE_AFTER = "Validate_DateRangeAfter"; //$NON-NLS-1$
171
172
	/**
173
	 * Key to be used for a "Validate_DateRangeAfterEqual" message
174
	 */
175
	public static final String VALIDATE_DATE_RANGE_AFTER_EQUAL = "Validate_DateRangeAfterEqual"; //$NON-NLS-1$
176
177
	/**
178
	 * Key to be used for a "Validate_DateRangeBefore" message
179
	 */
180
	public static final String VALIDATE_DATE_RANGE_BEFORE = "Validate_DateRangeBefore"; //$NON-NLS-1$
181
182
	/**
183
	 * Key to be used for a "Validate_DateRangeBeforeEqual" message
184
	 */
185
	public static final String VALIDATE_DATE_RANGE_BEFORE_EQUAL = "Validate_DateRangeBeforeEqual"; //$NON-NLS-1$
186
187
	/**
188
	 * Key to be used for a "Validate_DateRangeWithinRange" message
189
	 */
190
	public static final String VALIDATE_DATE_RANGE_WITHIN_RANGE = "Validate_DateRangeWithinRange"; //$NON-NLS-1$
191
192
	/**
193
	 * Key to be used for a "Validate_StringLengthMin" message
194
	 */
195
	public static final String VALIDATE_STRING_LENGTH_MIN = "Validate_StringLengthMin"; //$NON-NLS-1$
196
197
	/**
198
	 * Key to be used for a "Validate_StringLengthMax" message
199
	 */
200
	public static final String VALIDATE_STRING_LENGTH_MAX = "Validate_StringLengthMax"; //$NON-NLS-1$
201
202
	/**
203
	 * Key to be used for a "Validate_StringLengthRange" message
204
	 */
205
	public static final String VALIDATE_STRING_LENGTH_RANGE = "Validate_StringLengthRange"; //$NON-NLS-1$
206
207
	/**
112
	 * Returns the resource object with the given key in the resource bundle for
208
	 * 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
209
	 * JFace Data Binding. If there isn't any value under the given key, the key
114
	 * is returned.
210
	 * is returned.
115
	 *
211
	 * 
116
	 * @param key
212
	 * @param key
117
	 *            the resource name
213
	 *            the resource name
118
	 * @return the string
214
	 * @return the string
Lines 128-143 Link Here
128
	/**
224
	/**
129
	 * Returns a formatted string with the given key in the resource bundle for
225
	 * Returns a formatted string with the given key in the resource bundle for
130
	 * JFace Data Binding.
226
	 * JFace Data Binding.
131
	 *
227
	 * 
132
	 * @param key
228
	 * @param key
133
	 * @param arguments
229
	 * @param arguments
134
	 * @return formatted string, the key if the key is invalid
230
	 * @return formatted string, the key if the key is invalid
135
	 */
231
	 */
136
	public static String formatString(String key, Object[] arguments) {
232
	public static String getFormattedString(String key, Object[] arguments) {
137
		try {
233
		try {
138
			return MessageFormat.format(bundle.getString(key), arguments);
234
			return formatMessage(getString(key), arguments);
139
		} catch (MissingResourceException e) {
235
		} catch (MissingResourceException e) {
140
			return key;
236
			return key;
141
		}
237
		}
142
	}
238
	}
239
240
	/**
241
	 * Formats the given message pattern with the provided arguments.
242
	 * 
243
	 * @param pattern
244
	 * @param arguments
245
	 * @return formatted string
246
	 */
247
	public static String formatMessage(String pattern, Object[] arguments) {
248
		return MessageFormat.format(pattern, arguments);
249
	}
143
}
250
}
(-)src/org/eclipse/core/internal/databinding/messages.properties (+32 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
#NonNullValidator
59
Validate_NonNull=The value must not be empty.
60
61
#NonEmptyStringValidator
62
Validate_NonEmptyString=The string must not be empty.
63
64
#StringRegexValidator
65
Validate_NonStringRegex=The string must match the following pattern: {0}.
66
67
#NumberRangeValidator
68
Validate_NumberRangeGreater=The value must be greater than {0}.
69
Validate_NumberRangeGreaterEqual=The value must be greater than or equal to {0}.
70
Validate_NumberRangeLess=The value must be less than {0}.
71
Validate_NumberRangeLessEqual=The value must be less than or equal to {0}.
72
Validate_NumberRangeWithinRange=The value must lie between {0} and {1}.
73
Validate_NumberRangePositive=The value must be positive.
74
Validate_NumberRangeNonNegative=The value must not be negative.
75
76
#DateRangeValidator
77
Validate_DateRangeAfter=The date must be after {0}.
78
Validate_DateRangeAfterEqual=The date must be after or on {0}.
79
Validate_DateRangeBefore=The date must be before {0}.
80
Validate_DateRangeBeforeEqual=The date must be before or on {0}.
81
Validate_DateRangeWithinRange=The date must lie between {0} and {1}.
82
83
#StringLengthValidator
84
Validate_StringLengthMin=The string must have at least {0} characters.
85
Validate_StringLengthMax=The string must not have more than {0} characters.
86
Validate_StringLengthRange=The string must have between {0} and {1} characters.
87
56
Examples=Examples
88
Examples=Examples
(-)src/org/eclipse/core/internal/databinding/validation/IntegerRangeValidator.java (+200 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 integers which must lie within an open/closed range.
18
 * 
19
 * @since 1.4
20
 */
21
public class IntegerRangeValidator extends NumberRangeValidator {
22
23
	private static final Integer ZERO = new Integer(0);
24
	private static final Integer ONE = new Integer(1);
25
26
	/**
27
	 * Single constructor which supports the individual integer range types.
28
	 * 
29
	 * @param min
30
	 *            The min integer of the range or <code>null</code> in case no
31
	 *            lower bound is defined.
32
	 * @param max
33
	 *            The max integer of the range or <code>null</code> in case no
34
	 *            upper bound is defined.
35
	 * @param minConstraint
36
	 *            The type of constraint imposed by the lower bound of the
37
	 *            range.
38
	 * @param maxConstraint
39
	 *            The type of constraint imposed by the upper bound of the
40
	 *            range.
41
	 * @param validationMessage
42
	 *            The validation message pattern to use. Can be parameterized by
43
	 *            the lower and upper bound of the range, if defined.
44
	 * @param format
45
	 *            The integer format to use for formatting integers in the
46
	 *            validation message.
47
	 */
48
	private IntegerRangeValidator(Number min, Number max, int minConstraint,
49
			int maxConstraint, String validationMessage, NumberFormat format) {
50
		super(min, max, minConstraint, maxConstraint, validationMessage, format);
51
	}
52
53
	/**
54
	 * Creates a validator which checks that an input integer is greater than
55
	 * the given number.
56
	 * 
57
	 * @param number
58
	 *            The reference number of the greater constraint.
59
	 * @param validationMessage
60
	 *            The validation message pattern to use. Can be parameterized
61
	 *            with the given reference number.
62
	 * @param format
63
	 *            The display format to use for formatting integers in the
64
	 *            validation message.
65
	 * @return The validator instance.
66
	 */
67
	public static IntegerRangeValidator greater(int number,
68
			String validationMessage, NumberFormat format) {
69
		return new IntegerRangeValidator(new Integer(number), null, GREATER,
70
				UNDEFINED, defaultIfNull(validationMessage, GREATER_MESSAGE),
71
				format);
72
	}
73
74
	/**
75
	 * Creates a validator which checks that an input integer is greater than or
76
	 * equal to the given number.
77
	 * 
78
	 * @param number
79
	 *            The reference number of the greater-equal constraint.
80
	 * @param validationMessage
81
	 *            The validation message pattern to use. Can be parameterized
82
	 *            with the given reference number.
83
	 * @param format
84
	 *            The display format to use for formatting integers in the
85
	 *            validation message.
86
	 * @return The validator instance.
87
	 */
88
	public static IntegerRangeValidator greaterEqual(int number,
89
			String validationMessage, NumberFormat format) {
90
		return new IntegerRangeValidator(new Integer(number), null,
91
				GREATER_EQUAL, UNDEFINED, defaultIfNull(validationMessage,
92
						GREATER_EQUAL_MESSAGE), format);
93
	}
94
95
	/**
96
	 * Creates a validator which checks that an input integer is less than the
97
	 * given number.
98
	 * 
99
	 * @param number
100
	 *            The reference number of the less constraint.
101
	 * @param validationMessage
102
	 *            The validation message pattern to use. Can be parameterized
103
	 *            with the given reference number.
104
	 * @param format
105
	 *            The display format to use for formatting integers in the
106
	 *            validation message.
107
	 * @return The validator instance.
108
	 */
109
	public static IntegerRangeValidator less(int number,
110
			String validationMessage, NumberFormat format) {
111
		return new IntegerRangeValidator(null, new Integer(number), UNDEFINED,
112
				LESS, defaultIfNull(validationMessage, LESS_MESSAGE), format);
113
	}
114
115
	/**
116
	 * Creates a validator which checks that an input integer is less than or
117
	 * equal to the given number.
118
	 * 
119
	 * @param number
120
	 *            The reference number of the less-equal constraint.
121
	 * @param validationMessage
122
	 *            The validation message pattern to use. Can be parameterized
123
	 *            with the given reference number.
124
	 * @param format
125
	 *            The display format to use for formatting integers in the
126
	 *            validation message.
127
	 * @return The validator instance.
128
	 */
129
	public static IntegerRangeValidator lessEqual(int number,
130
			String validationMessage, NumberFormat format) {
131
		return new IntegerRangeValidator(null, new Integer(number), UNDEFINED,
132
				LESS_EQUAL,
133
				defaultIfNull(validationMessage, LESS_EQUAL_MESSAGE), format);
134
	}
135
136
	/**
137
	 * Creates a validator which checks that an input integer is within the
138
	 * given range.
139
	 * 
140
	 * @param min
141
	 *            The lower bound of the range (inclusive).
142
	 * @param max
143
	 *            The upper bound of the range (inclusive).
144
	 * @param validationMessage
145
	 *            The validation message pattern to use. Can be parameterized
146
	 *            with the range's lower and upper bound.
147
	 * @param format
148
	 *            The display format to use for formatting integers in the
149
	 *            validation message.
150
	 * @return The validator instance.
151
	 */
152
	public static IntegerRangeValidator range(int min, int max,
153
			String validationMessage, NumberFormat format) {
154
		return new IntegerRangeValidator(new Integer(min), new Integer(max),
155
				GREATER_EQUAL, LESS_EQUAL, defaultIfNull(validationMessage,
156
						WITHIN_RANGE_MESSAGE), format);
157
	}
158
159
	/**
160
	 * Creates a validator which checks that an input integer is positive.
161
	 * 
162
	 * @param validationMessage
163
	 *            The validation message to use.
164
	 * @param format
165
	 *            The display format to use for formatting integers in the
166
	 *            validation message.
167
	 * @return The validator instance.
168
	 */
169
	public static IntegerRangeValidator positive(String validationMessage,
170
			NumberFormat format) {
171
		return new IntegerRangeValidator(ONE, null, GREATER_EQUAL, UNDEFINED,
172
				defaultIfNull(validationMessage, POSITIVE_MESSAGE), format);
173
	}
174
175
	/**
176
	 * Creates a validator which checks that an input integer is non-negative.
177
	 * 
178
	 * @param validationMessage
179
	 *            The validation message to use.
180
	 * @param format
181
	 *            The display format to use for formatting integers in the
182
	 *            validation message.
183
	 * @return The validator instance.
184
	 */
185
	public static IntegerRangeValidator nonNegative(String validationMessage,
186
			NumberFormat format) {
187
		return new IntegerRangeValidator(ZERO, null, GREATER_EQUAL, UNDEFINED,
188
				defaultIfNull(validationMessage, NON_NEGATIVE_MESSAGE), format);
189
	}
190
191
	protected int compare(Number number1, Number number2) {
192
		Integer integer1 = (Integer) number1;
193
		Integer integer2 = (Integer) number2;
194
		return integer1.compareTo(integer2);
195
	}
196
197
	private static String defaultIfNull(String string, String defaultString) {
198
		return (string != null) ? string : defaultString;
199
	}
200
}
(-)src/org/eclipse/core/databinding/editing/StringEditing.java (+232 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
 * @since 1.4
22
 */
23
public final class StringEditing extends Editing {
24
25
	private StringEditing(IConverter targetConverter) {
26
		setTargetConverter(targetConverter);
27
	}
28
29
	/**
30
	 * Creates a new editing object for strings which performs no validation or
31
	 * conversion.
32
	 * 
33
	 * @return The new editing object which performs no validation or
34
	 *         conversion.
35
	 */
36
	public static StringEditing withDefaults() {
37
		return new StringEditing(null);
38
	}
39
40
	/**
41
	 * Creates a new editing object which strips whitespace from both ends of
42
	 * the input string.
43
	 * 
44
	 * @param stripToNull
45
	 *            Whether to convert the input string to <code>null</code> in
46
	 *            case stripping the input string results in an empty string.
47
	 * @return The new editing object which strips whitespace from both ends of
48
	 *         the input string.
49
	 * 
50
	 * @see Character#isWhitespace(char)
51
	 */
52
	public static StringEditing stripped(boolean stripToNull) {
53
		return new StringEditing(new StringStripConverter(stripToNull));
54
	}
55
56
	/**
57
	 * Creates a new editing object which {@link String#trim()}s the input
58
	 * string.
59
	 * 
60
	 * @param trimToNull
61
	 *            Whether to convert the input string to <code>null</code> in
62
	 *            case trimming the input string results in an empty string.
63
	 * @return The new editing object which trims whitespace from both ends of
64
	 *         the input string.
65
	 * 
66
	 * @see String#trim()
67
	 */
68
	public static StringEditing trimmed(boolean trimToNull) {
69
		return new StringEditing(new StringTrimConverter(trimToNull));
70
	}
71
72
	/**
73
	 * Returns the target constraints to apply.
74
	 * 
75
	 * <p>
76
	 * This method provides a typesafe access to the {@link StringConstraints
77
	 * string target constraints} of this editing object and is equivalent to
78
	 * {@code (StringConstraints) targetConstraints()}.
79
	 * </p>
80
	 * 
81
	 * @return The target constraints to apply.
82
	 * 
83
	 * @see #targetConstraints()
84
	 * @see StringConstraints
85
	 */
86
	public StringConstraints targetStringConstraints() {
87
		return (StringConstraints) targetConstraints();
88
	}
89
90
	/**
91
	 * Returns the model constraints to apply.
92
	 * 
93
	 * <p>
94
	 * This method provides a typesafe access to the {@link StringConstraints
95
	 * string model constraints} of this editing object and is equivalent to
96
	 * {@code (StringConstraints) modelConstraints()}.
97
	 * </p>
98
	 * 
99
	 * @return The target constraints to apply.
100
	 * 
101
	 * @see #modelConstraints()
102
	 * @see StringConstraints
103
	 */
104
	public StringConstraints modelStringConstraints() {
105
		return (StringConstraints) modelConstraints();
106
	}
107
108
	/**
109
	 * Returns the before-set model constraints to apply.
110
	 * 
111
	 * <p>
112
	 * This method provides a typesafe access to the {@link StringConstraints
113
	 * string before-set model constraints} of this editing object and is
114
	 * equivalent to {@code (StringConstraints) beforeSetModelConstraints()}.
115
	 * </p>
116
	 * 
117
	 * @return The target constraints to apply.
118
	 * 
119
	 * @see #beforeSetModelConstraints()
120
	 * @see StringConstraints
121
	 */
122
	public StringConstraints beforeSetModelStringConstraints() {
123
		return (StringConstraints) beforeSetModelConstraints();
124
	}
125
126
	protected Constraints createTargetConstraints() {
127
		return new StringConstraints();
128
	}
129
130
	protected Constraints createModelConstraints() {
131
		return new StringConstraints();
132
	}
133
134
	protected Constraints createBeforeSetModelConstraints() {
135
		return new StringConstraints();
136
	}
137
138
	/**
139
	 * Convenience method which adds a {@link StringConstraints#required()
140
	 * required constraint} to the set of {@link #modelStringConstraints()}.
141
	 * 
142
	 * @return This editing instance for method chaining.
143
	 * 
144
	 * @see StringConstraints#required()
145
	 * @see #modelStringConstraints()
146
	 */
147
	public StringEditing required() {
148
		modelStringConstraints().required();
149
		return this;
150
	}
151
152
	/**
153
	 * Convenience method which adds a {@link StringConstraints#nonEmpty()
154
	 * non-empty constraint} to the set of {@link #modelStringConstraints()}.
155
	 * 
156
	 * @return This editing instance for method chaining.
157
	 * 
158
	 * @see StringConstraints#nonEmpty()
159
	 * @see #modelStringConstraints()
160
	 */
161
	public StringEditing nonEmpty() {
162
		modelStringConstraints().nonEmpty();
163
		return this;
164
	}
165
166
	/**
167
	 * Convenience method which adds a {@link StringConstraints#minLength(int)
168
	 * min-length constraint} to the set of {@link #modelStringConstraints()}.
169
	 * 
170
	 * @param minLength
171
	 *            The min length of the min-length constraint.
172
	 * @return This editing instance for method chaining.
173
	 * 
174
	 * @see StringConstraints#minLength(int)
175
	 * @see #modelStringConstraints()
176
	 */
177
	public StringEditing minLength(int minLength) {
178
		modelStringConstraints().minLength(minLength);
179
		return this;
180
	}
181
182
	/**
183
	 * Convenience method which adds a {@link StringConstraints#maxLength(int)
184
	 * max-length constraint} to the set of {@link #modelStringConstraints()}.
185
	 * 
186
	 * @param maxLength
187
	 *            The max length of the max-length constraint.
188
	 * @return This editing instance for method chaining.
189
	 * 
190
	 * @see StringConstraints#maxLength(int)
191
	 * @see #modelStringConstraints()
192
	 */
193
	public StringEditing maxLength(int maxLength) {
194
		modelStringConstraints().maxLength(maxLength);
195
		return this;
196
	}
197
198
	/**
199
	 * Convenience method which adds a
200
	 * {@link StringConstraints#lengthRange(int, int) length-range constraint}
201
	 * to the set of {@link #modelStringConstraints()}.
202
	 * 
203
	 * @param minLength
204
	 *            The min length of the length-range constraint.
205
	 * @param maxLength
206
	 *            The max length of the length-range constraint.
207
	 * @return This editing instance for method chaining.
208
	 * 
209
	 * @see StringConstraints#lengthRange(int, int)
210
	 * @see #modelStringConstraints()
211
	 */
212
	public StringEditing lengthRange(int minLength, int maxLength) {
213
		modelStringConstraints().lengthRange(minLength, maxLength);
214
		return this;
215
	}
216
217
	/**
218
	 * Convenience method which adds a {@link StringConstraints#matches(String)
219
	 * matches constraint} to the set of {@link #modelStringConstraints()}.
220
	 * 
221
	 * @param regex
222
	 *            The regular expression of the matches constraint.
223
	 * @return This editing instance for method chaining.
224
	 * 
225
	 * @see StringConstraints#matches(String)
226
	 * @see #modelStringConstraints()
227
	 */
228
	public StringEditing matches(String regex) {
229
		modelStringConstraints().matches(regex);
230
		return this;
231
	}
232
}
(-)src/org/eclipse/core/internal/databinding/validation/NumberRangeValidator.java (+149 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.4
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.getString(BindingMessages.VALIDATE_NUMBER_RANGE_GREATER);
39
	protected static final String GREATER_EQUAL_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_RANGE_GREATER_EQUAL);
40
	protected static final String LESS_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_RANGE_LESS);
41
	protected static final String LESS_EQUAL_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_RANGE_LESS_EQUAL);
42
	protected static final String WITHIN_RANGE_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_RANGE_WITHIN_RANGE);
43
	protected static final String POSITIVE_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_RANGE_POSITIVE);
44
	protected static final String NON_NEGATIVE_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NUMBER_RANGE_NON_NEGATIVE);
45
46
	private final Number min;
47
	private final Number max;
48
	private final int minConstraint;
49
	private final int maxConstraint;
50
	private final String validationMessage;
51
	private String formattedValidationMessage;
52
	private final NumberFormat format;
53
54
	/**
55
	 * Single constructor which supports the individual number range types.
56
	 * 
57
	 * @param min
58
	 *            The min number of the range or <code>null</code> in case no
59
	 *            lower bound is defined.
60
	 * @param max
61
	 *            The max number of the range or <code>null</code> in case no
62
	 *            upper bound is defined.
63
	 * @param minConstraint
64
	 *            The type of constraint imposed by the lower bound of the
65
	 *            range.
66
	 * @param maxConstraint
67
	 *            The type of constraint imposed by the upper bound of the
68
	 *            range.
69
	 * @param validationMessage
70
	 *            The validation message pattern to use. Can be parameterized by
71
	 *            the lower and upper bound of the range, if defined.
72
	 * @param format
73
	 *            The integer format to use for formatting numbers in the
74
	 *            validation message.
75
	 */
76
	protected NumberRangeValidator(Number min, Number max, int minConstraint,
77
			int maxConstraint, String validationMessage, NumberFormat format) {
78
		this.min = min;
79
		this.max = max;
80
		this.minConstraint = minConstraint;
81
		this.maxConstraint = maxConstraint;
82
		this.validationMessage = validationMessage;
83
		this.format = format;
84
	}
85
86
	public IStatus validate(Object value) {
87
		if (value != null) {
88
			Number number = (Number) value;
89
			if ((min != null && !fulfillsConstraint(number, min, minConstraint))
90
					|| (max != null && !fulfillsConstraint(number, max,
91
							maxConstraint))) {
92
				return ValidationStatus.error(getFormattedValidationMessage());
93
			}
94
		}
95
		return ValidationStatus.ok();
96
	}
97
98
	private boolean fulfillsConstraint(Number number1, Number number2,
99
			int constraint) {
100
		int compareResult = compare(number1, number2);
101
		switch (constraint) {
102
		case GREATER:
103
			return compareResult > 0;
104
		case GREATER_EQUAL:
105
			return compareResult >= 0;
106
		case LESS:
107
			return compareResult < 0;
108
		case LESS_EQUAL:
109
			return compareResult <= 0;
110
		case UNDEFINED:
111
		default:
112
			throw new IllegalArgumentException(
113
					"Unsupported constraint: " + constraint); //$NON-NLS-1$
114
		}
115
	}
116
117
	/**
118
	 * Comparator method to be implemented by subclasses in order to compare two
119
	 * instances of the concrete number type.
120
	 * 
121
	 * @param number1
122
	 *            The first number to compare.
123
	 * @param number2
124
	 *            The second number to compare.
125
	 * @return A negative number, zero, or a positive number in case the first
126
	 *         number is smaller than, equal to, or greater than the second
127
	 *         number, respectively.
128
	 */
129
	protected abstract int compare(Number number1, Number number2);
130
131
	private synchronized String getFormattedValidationMessage() {
132
		if (formattedValidationMessage == null) {
133
			formattedValidationMessage = MessageFormat.format(
134
					validationMessage, getValidationMessageArguments());
135
		}
136
		return formattedValidationMessage;
137
	}
138
139
	private String[] getValidationMessageArguments() {
140
		synchronized (format) {
141
			if (min == null) {
142
				return new String[] { format.format(max) };
143
			} else if (max == null) {
144
				return new String[] { format.format(min) };
145
			}
146
			return new String[] { format.format(min), format.format(max) };
147
		}
148
	}
149
}
(-)src/org/eclipse/core/internal/databinding/validation/DateRangeValidator.java (+238 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.4
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.getString(BindingMessages.VALIDATE_DATE_RANGE_AFTER);
40
	private static final String AFTER_EQUAL_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_DATE_RANGE_AFTER_EQUAL);
41
	private static final String BEFORE_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_DATE_RANGE_BEFORE);
42
	private static final String BEFORE_EQUAL_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_DATE_RANGE_BEFORE_EQUAL);
43
	private static final String WITHIN_RANGE_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_DATE_RANGE_WITHIN_RANGE);
44
45
	private final Date min;
46
	private final Date max;
47
	private final int minConstraint;
48
	private final int maxConstraint;
49
	private final String validationMessage;
50
	private String formattedValidationMessage;
51
	private final DateFormat format;
52
53
	/**
54
	 * Single constructor which supports the individual date range types.
55
	 * 
56
	 * @param min
57
	 *            The min date of the range or <code>null</code> in case no
58
	 *            lower bound is defined.
59
	 * @param max
60
	 *            The max date of the range or <code>null</code> in case no
61
	 *            upper bound is defined.
62
	 * @param minConstraint
63
	 *            The type of constraint imposed by the lower bound of the
64
	 *            range.
65
	 * @param maxConstraint
66
	 *            The type of constraint imposed by the upper bound of the
67
	 *            range.
68
	 * @param validationMessage
69
	 *            The validation message pattern to use. Can be parameterized by
70
	 *            the lower and upper bound of the range, if defined.
71
	 * @param format
72
	 *            The date format to use for formatting dates in the validation
73
	 *            message.
74
	 */
75
	private DateRangeValidator(Date min, Date max, int minConstraint,
76
			int maxConstraint, String validationMessage, DateFormat format) {
77
		this.min = min;
78
		this.max = max;
79
		this.minConstraint = minConstraint;
80
		this.maxConstraint = maxConstraint;
81
		this.validationMessage = validationMessage;
82
		this.format = format;
83
	}
84
85
	/**
86
	 * Creates a validator which checks that an input date is after the given
87
	 * date.
88
	 * 
89
	 * @param date
90
	 *            The reference date of the after constraint.
91
	 * @param validationMessage
92
	 *            The validation message pattern to use. Can be parameterized
93
	 *            with the given reference date.
94
	 * @param format
95
	 *            The display format to use for formatting dates in the
96
	 *            validation message.
97
	 * @return The validator instance.
98
	 */
99
	public static DateRangeValidator after(Date date, String validationMessage,
100
			DateFormat format) {
101
		return new DateRangeValidator(date, null, AFTER, UNDEFINED,
102
				defaultIfNull(validationMessage, AFTER_MESSAGE), format);
103
	}
104
105
	/**
106
	 * Creates a validator which checks that an input date is after or on the
107
	 * given date.
108
	 * 
109
	 * @param date
110
	 *            The reference date of the after-equal constraint.
111
	 * @param validationMessage
112
	 *            The validation message pattern to use. Can be parameterized
113
	 *            with the given reference date.
114
	 * @param format
115
	 *            The display format to use for formatting dates in the
116
	 *            validation message.
117
	 * @return The validator instance.
118
	 */
119
	public static DateRangeValidator afterEqual(Date date,
120
			String validationMessage, DateFormat format) {
121
		return new DateRangeValidator(date, null, AFTER_EQUAL, UNDEFINED,
122
				defaultIfNull(validationMessage, AFTER_EQUAL_MESSAGE), format);
123
	}
124
125
	/**
126
	 * Creates a validator which checks that an input date is before the given
127
	 * date.
128
	 * 
129
	 * @param date
130
	 *            The reference date of the before constraint.
131
	 * @param validationMessage
132
	 *            The validation message pattern to use. Can be parameterized
133
	 *            with the given reference date.
134
	 * @param format
135
	 *            The display format to use for formatting dates in the
136
	 *            validation message.
137
	 * @return The validator instance.
138
	 */
139
	public static DateRangeValidator before(Date date, String validationMessage,
140
			DateFormat format) {
141
		return new DateRangeValidator(null, date, UNDEFINED, BEFORE,
142
				defaultIfNull(validationMessage, BEFORE_MESSAGE), format);
143
	}
144
145
	/**
146
	 * Creates a validator which checks that an input date is before or on the
147
	 * given date.
148
	 * 
149
	 * @param date
150
	 *            The reference date of the before-equal constraint.
151
	 * @param validationMessage
152
	 *            The validation message pattern to use. Can be parameterized
153
	 *            with the given reference date.
154
	 * @param format
155
	 *            The display format to use for formatting dates in the
156
	 *            validation message.
157
	 * @return The validator instance.
158
	 */
159
	public static DateRangeValidator beforeEqual(Date date,
160
			String validationMessage, DateFormat format) {
161
		return new DateRangeValidator(null, date, UNDEFINED, BEFORE_EQUAL,
162
				defaultIfNull(validationMessage, BEFORE_EQUAL_MESSAGE), format);
163
	}
164
165
	/**
166
	 * Creates a validator which checks that an input date is within the given
167
	 * range.
168
	 * 
169
	 * @param min
170
	 *            The lower bound of the range (inclusive).
171
	 * @param max
172
	 *            The upper bound of the range (inclusive).
173
	 * @param validationMessage
174
	 *            The validation message pattern to use. Can be parameterized
175
	 *            with the range's lower and upper bound.
176
	 * @param format
177
	 *            The display format to use for formatting dates in the
178
	 *            validation message.
179
	 * @return The validator instance.
180
	 */
181
	public static DateRangeValidator range(Date min, Date max,
182
			String validationMessage, DateFormat format) {
183
		return new DateRangeValidator(min, max, AFTER_EQUAL, BEFORE_EQUAL,
184
				defaultIfNull(validationMessage, WITHIN_RANGE_MESSAGE), format);
185
	}
186
187
	public IStatus validate(Object value) {
188
		if (value != null) {
189
			Date date = (Date) value;
190
			if ((min != null && !fulfillsConstraint(date, min, minConstraint))
191
					|| (max != null && !fulfillsConstraint(date, max,
192
							maxConstraint))) {
193
				return ValidationStatus.error(getFormattedValidationMessage());
194
			}
195
		}
196
		return ValidationStatus.ok();
197
	}
198
199
	private boolean fulfillsConstraint(Date date1, Date date2, int constraint) {
200
		switch (constraint) {
201
		case AFTER:
202
			return date1.after(date2);
203
		case AFTER_EQUAL:
204
			return date1.after(date2) || date1.equals(date2);
205
		case BEFORE:
206
			return date1.before(date2);
207
		case BEFORE_EQUAL:
208
			return date1.before(date2) || date1.equals(date2);
209
		case UNDEFINED:
210
		default:
211
			throw new IllegalArgumentException(
212
					"Unsupported constraint: " + constraint); //$NON-NLS-1$
213
		}
214
	}
215
216
	private synchronized String getFormattedValidationMessage() {
217
		if (formattedValidationMessage == null) {
218
			formattedValidationMessage = MessageFormat.format(
219
					validationMessage, getValidationMessageArguments());
220
		}
221
		return formattedValidationMessage;
222
	}
223
224
	private String[] getValidationMessageArguments() {
225
		synchronized (format) {
226
			if (min == null) {
227
				return new String[] { format.format(max) };
228
			} else if (max == null) {
229
				return new String[] { format.format(min) };
230
			}
231
			return new String[] { format.format(min), format.format(max) };
232
		}
233
	}
234
235
	private static String defaultIfNull(String string, String defaultString) {
236
		return (string != null) ? string : defaultString;
237
	}
238
}
(-)src/org/eclipse/core/internal/databinding/validation/StringLengthValidator.java (+164 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.4
27
 */
28
public class StringLengthValidator implements IValidator {
29
30
	// The default validation messages.
31
	private static final String MIN_LENGTH_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_STRING_LENGTH_MIN);
32
	private static final String MAX_LENGTH_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_STRING_LENGTH_MAX);
33
	private static final String LENGTH_RANGE_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_STRING_LENGTH_RANGE);
34
35
	private final Integer minLength;
36
	private final Integer maxLength;
37
	private final String validationMessage;
38
	private String formattedValidationMessage;
39
	private final NumberFormat format;
40
41
	/**
42
	 * Creates a string length validator defining a minimum and/or maximum
43
	 * length for a string.
44
	 * 
45
	 * @param minLength
46
	 *            The minimum length of the string or <code>null</code> in case
47
	 *            no minimum length is defined.
48
	 * @param maxLength
49
	 *            The maximum length of the string or <code>null</code> in case
50
	 *            no maximum length is defined.
51
	 * @param validationMessage
52
	 *            The validation message pattern to use. Can be parameterized by
53
	 *            the lower and upper bound of the range, if defined.
54
	 * @param format
55
	 *            The number format to use for formatting integers (the length
56
	 *            bounds) in the validation message.
57
	 */
58
	private StringLengthValidator(Integer minLength, Integer maxLength,
59
			String validationMessage, NumberFormat format) {
60
		this.minLength = minLength;
61
		this.maxLength = maxLength;
62
		this.validationMessage = validationMessage;
63
		this.format = format;
64
	}
65
66
	/**
67
	 * Creates a validator which checks that an input string has the given
68
	 * minimum length.
69
	 * 
70
	 * @param minLength
71
	 *            The minimum length which the input string must have.
72
	 * @param validationMessage
73
	 *            The validation message pattern to use. Can be parameterized
74
	 *            with the given minimum length.
75
	 * @param format
76
	 *            The display format to use for formatting integers (the minimum
77
	 *            length) in the validation message.
78
	 * @return The validator instance.
79
	 */
80
	public static StringLengthValidator minLength(int minLength,
81
			String validationMessage, NumberFormat format) {
82
		return new StringLengthValidator(new Integer(minLength), null,
83
				defaultIfNull(validationMessage, MIN_LENGTH_MESSAGE), format);
84
	}
85
86
	/**
87
	 * Creates a validator which checks that an input string has the given
88
	 * maximum length.
89
	 * 
90
	 * @param maxLength
91
	 *            The maximum length which the input string must have.
92
	 * @param validationMessage
93
	 *            The validation message pattern to use. Can be parameterized
94
	 *            with the given maximum length.
95
	 * @param format
96
	 *            The display format to use for formatting integers (the maximum
97
	 *            length) in the validation message.
98
	 * @return The validator instance.
99
	 */
100
	public static StringLengthValidator maxLength(int maxLength,
101
			String validationMessage, NumberFormat format) {
102
		return new StringLengthValidator(null, new Integer(maxLength),
103
				defaultIfNull(validationMessage, MAX_LENGTH_MESSAGE), format);
104
	}
105
106
	/**
107
	 * Creates a validator which checks that the length of an input string lies
108
	 * in the given range.
109
	 * 
110
	 * @param minLength
111
	 *            The minimum length which the input string must have.
112
	 * @param maxLength
113
	 *            The maximum length which the input string must have.
114
	 * @param validationMessage
115
	 *            The validation message pattern to use. Can be parameterized
116
	 *            with the given minimum and maximum lengths.
117
	 * @param format
118
	 *            The display format to use for formatting integers (the
119
	 *            minimum/maximum length) in the validation message.
120
	 * @return The validator instance.
121
	 */
122
	public static StringLengthValidator lengthRange(int minLength,
123
			int maxLength, String validationMessage, NumberFormat format) {
124
		return new StringLengthValidator(new Integer(minLength), new Integer(
125
				maxLength), defaultIfNull(validationMessage,
126
				LENGTH_RANGE_MESSAGE), format);
127
	}
128
129
	public IStatus validate(Object value) {
130
		String input = (String) value;
131
		if (input != null) {
132
			int inputLength = input.length();
133
			if ((minLength != null && inputLength < minLength.intValue())
134
					|| maxLength != null && inputLength > maxLength.intValue()) {
135
				return ValidationStatus.error(getFormattedValidationMessage());
136
			}
137
		}
138
		return ValidationStatus.ok();
139
	}
140
141
	private synchronized String getFormattedValidationMessage() {
142
		if (formattedValidationMessage == null) {
143
			formattedValidationMessage = MessageFormat.format(
144
					validationMessage, getValidationMessageArguments());
145
		}
146
		return formattedValidationMessage;
147
	}
148
149
	private String[] getValidationMessageArguments() {
150
		synchronized (format) {
151
			if (minLength == null) {
152
				return new String[] { format.format(maxLength) };
153
			} else if (maxLength == null) {
154
				return new String[] { format.format(minLength) };
155
			}
156
			return new String[] { format.format(minLength),
157
					format.format(maxLength) };
158
		}
159
	}
160
161
	private static String defaultIfNull(String string, String defaultString) {
162
		return (string != null) ? string : defaultString;
163
	}
164
}
(-)src/org/eclipse/core/databinding/validation/constraint/DateConstraints.java (+252 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
 * @since 1.4
23
 */
24
public final class DateConstraints extends Constraints {
25
26
	private DateFormat displayFormat = DateFormat.getDateInstance();
27
28
	private String requiredMessage = null;
29
30
	private String afterMessage = null;
31
32
	private String afterEqualMessage = null;
33
34
	private String beforeMessage = null;
35
36
	private String beforeEqualMessage = null;
37
38
	private String rangeMessage = null;
39
40
	/**
41
	 * Sets the format to use when formatting a date to be included in any of
42
	 * the validation messages.
43
	 * 
44
	 * <p>
45
	 * This date format will be used for any subsequent constraints which are
46
	 * applied.
47
	 * </p>
48
	 * 
49
	 * @param format
50
	 *            The format to use for displaying dates in validation messages.
51
	 * @return This constraints instance for method chaining.
52
	 */
53
	public DateConstraints displayFormat(DateFormat format) {
54
		this.displayFormat = format;
55
		return this;
56
	}
57
58
	/**
59
	 * Adds a validator ensuring that the parsed date is not <code>null</code>.
60
	 * Uses the current {@link #requiredMessage(String) validation message}.
61
	 * 
62
	 * @return This constraints instance for method chaining.
63
	 */
64
	public DateConstraints required() {
65
		addValidator(new NonNullValidator(requiredMessage));
66
		return this;
67
	}
68
69
	/**
70
	 * Sets the validation message for the {@link #required()} constraint.
71
	 * 
72
	 * @param message
73
	 *            The validation message for the {@link #required()} constraint.
74
	 * @return This constraints instance for method chaining.
75
	 * 
76
	 * @see #required()
77
	 */
78
	public DateConstraints requiredMessage(String message) {
79
		this.requiredMessage = message;
80
		return this;
81
	}
82
83
	/**
84
	 * Adds a validator ensuring that the parsed date is after the given date.
85
	 * Uses the current {@link #afterMessage(String) validation message}.
86
	 * 
87
	 * @param date
88
	 *            The date which the parsed date must be after.
89
	 * @return This constraints instance for method chaining.
90
	 * 
91
	 * @see Date#after(Date)
92
	 */
93
	public DateConstraints after(Date date) {
94
		addValidator(DateRangeValidator
95
				.after(date, afterMessage, displayFormat));
96
		return this;
97
	}
98
99
	/**
100
	 * Sets the validation message pattern for the {@link #after(Date)}
101
	 * constraint.
102
	 * 
103
	 * @param message
104
	 *            The validation message pattern for the {@link #after(Date)}
105
	 *            constraint. Can be parameterized with the date which the
106
	 *            parsed date must be after.
107
	 * @return This constraints instance for method chaining.
108
	 * 
109
	 * @see #after(Date)
110
	 */
111
	public DateConstraints afterMessage(String message) {
112
		this.afterMessage = message;
113
		return this;
114
	}
115
116
	/**
117
	 * Adds a validator ensuring that the parsed date is after or on the given
118
	 * date. Uses the current {@link #afterEqualMessage(String) validation
119
	 * message}.
120
	 * 
121
	 * @param date
122
	 *            The date which the parsed date must be after or on.
123
	 * @return This constraints instance for method chaining.
124
	 * 
125
	 * @see Date#after(Date)
126
	 * @see Date#equals(Object)
127
	 */
128
	public DateConstraints afterEqual(Date date) {
129
		addValidator(DateRangeValidator.afterEqual(date, afterEqualMessage,
130
				displayFormat));
131
		return this;
132
	}
133
134
	/**
135
	 * Sets the validation message pattern for the {@link #afterEqual(Date)}
136
	 * constraint.
137
	 * 
138
	 * @param message
139
	 *            The validation message pattern for the
140
	 *            {@link #afterEqual(Date)} constraint. Can be parameterized
141
	 *            with the date which the parsed date must be after or on.
142
	 * @return This constraints instance for method chaining.
143
	 * 
144
	 * @see #afterEqual(Date)
145
	 */
146
	public DateConstraints afterEqualMessage(String message) {
147
		this.afterEqualMessage = message;
148
		return this;
149
	}
150
151
	/**
152
	 * Adds a validator ensuring that the parsed date is before the given date.
153
	 * Uses the current {@link #beforeMessage(String) validation message}.
154
	 * 
155
	 * @param date
156
	 *            The date which the parsed date must be before
157
	 * @return This constraints instance for method chaining.
158
	 * 
159
	 * @see Date#before(Date)
160
	 */
161
	public DateConstraints before(Date date) {
162
		addValidator(DateRangeValidator.before(date, beforeMessage,
163
				displayFormat));
164
		return this;
165
	}
166
167
	/**
168
	 * Sets the validation message pattern for the {@link #before(Date)}
169
	 * constraint.
170
	 * 
171
	 * @param message
172
	 *            The validation message pattern for the {@link #before(Date)}
173
	 *            constraint. Can be parameterized with the date which the
174
	 *            parsed date must be before.
175
	 * @return This constraints instance for method chaining.
176
	 * 
177
	 * @see #before(Date)
178
	 */
179
	public DateConstraints beforeMessage(String message) {
180
		this.beforeMessage = message;
181
		return this;
182
	}
183
184
	/**
185
	 * Adds a validator ensuring that the parsed date is before or on the given
186
	 * date. Uses the current {@link #beforeEqualMessage(String) validation
187
	 * message}.
188
	 * 
189
	 * @param date
190
	 *            The date which the parsed date must be before or on.
191
	 * @return This constraints instance for method chaining.
192
	 * 
193
	 * @see Date#before(Date)
194
	 * @see Date#equals(Object)
195
	 */
196
	public DateConstraints beforeEqual(Date date) {
197
		addValidator(DateRangeValidator.beforeEqual(date, beforeEqualMessage,
198
				displayFormat));
199
		return this;
200
	}
201
202
	/**
203
	 * Sets the validation message pattern for the {@link #beforeEqual(Date)}
204
	 * constraint.
205
	 * 
206
	 * @param message
207
	 *            The validation message pattern for the
208
	 *            {@link #beforeEqual(Date)} constraint. Can be parameterized
209
	 *            with the date which the parsed date must be before or on.
210
	 * @return This constraints instance for method chaining.
211
	 * 
212
	 * @see #beforeEqual(Date)
213
	 */
214
	public DateConstraints beforeEqualMessage(String message) {
215
		this.beforeEqualMessage = message;
216
		return this;
217
	}
218
219
	/**
220
	 * Adds a validator ensuring that the parsed date is within the given range.
221
	 * Uses the current {@link #rangeMessage(String) validation message}.
222
	 * 
223
	 * @param minDate
224
	 *            The lower bound of the range (inclusive).
225
	 * @param maxDate
226
	 *            The upper bound of the range (inclusive).
227
	 * @return This constraints instance for method chaining.
228
	 */
229
	public DateConstraints range(Date minDate, Date maxDate) {
230
		addValidator(DateRangeValidator.range(minDate, maxDate, rangeMessage,
231
				displayFormat));
232
		return this;
233
	}
234
235
	/**
236
	 * Sets the validation message pattern for the {@link #range(Date, Date)}
237
	 * constraint.
238
	 * 
239
	 * @param message
240
	 *            The validation message pattern for the
241
	 *            {@link #range(Date, Date)} constraint. Can be parameterized
242
	 *            with the min and max dates of the range in which the parsed
243
	 *            date must lie.
244
	 * @return This constraints instance for method chaining.
245
	 * 
246
	 * @see #range(Date, Date)
247
	 */
248
	public DateConstraints rangeMessage(String message) {
249
		this.rangeMessage = message;
250
		return this;
251
	}
252
}
(-)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.4
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 (+203 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
 * @since 1.4
23
 */
24
public final class BooleanEditing extends Editing {
25
26
	private BooleanEditing(String[] trueValues, String[] falseValues,
27
			String parseErrorMessage) {
28
		StringToBooleanConverter targetConverter = new StringToBooleanConverter();
29
		BooleanToStringConverter modelConverter = new BooleanToStringConverter(
30
				Boolean.class);
31
32
		StringToBooleanValidator targetValidator = new StringToBooleanValidator();
33
		if (parseErrorMessage != null) {
34
			targetValidator.setParseErrorMessage(parseErrorMessage);
35
		}
36
37
		if (trueValues != null && falseValues != null) {
38
			targetValidator.setSourceStrings(trueValues, falseValues);
39
			targetConverter.setSourceStrings(trueValues, falseValues);
40
			modelConverter.setTargetStrings(trueValues[0], falseValues[0]);
41
		}
42
43
		setTargetConverter(targetConverter);
44
		setModelConverter(modelConverter);
45
		targetConstraints().addValidator(targetValidator);
46
	}
47
48
	/**
49
	 * Creates a new editing object which uses the default set of string
50
	 * representations for boolean values for parsing and displaying.
51
	 * 
52
	 * @return The new editing object for the default set of string
53
	 *         representations for boolean values.
54
	 */
55
	public static BooleanEditing withDefaults() {
56
		return new BooleanEditing(null, null, null);
57
	}
58
59
	/**
60
	 * Creates a new editing object which uses the default set of string
61
	 * representations for boolean values for parsing and displaying. Uses the
62
	 * specified custom validation message.
63
	 * 
64
	 * @param parseErrorMessage
65
	 *            The validation message issued in case the input string cannot
66
	 *            be parsed to an boolean.
67
	 * @return The new editing object for the default set of string
68
	 *         representations for boolean values.
69
	 */
70
	public static BooleanEditing withDefaults(String parseErrorMessage) {
71
		return new BooleanEditing(null, null, parseErrorMessage);
72
	}
73
74
	/**
75
	 * Creates a new editing object which uses the given set of string
76
	 * representations for boolean values for parsing and displaying.
77
	 * 
78
	 * <p>
79
	 * For parsing, the given string values will be considered valid
80
	 * representations of {@code true} and {@code false}, respectively. For
81
	 * displaying, the first element of the respective array will be used for
82
	 * representing the corresponding boolean value.
83
	 * </p>
84
	 * 
85
	 * @param trueValues
86
	 *            The set of strings representing a <code>true</code> value.
87
	 * @param falseValues
88
	 *            The set of strings representing a <code>false</code> value.
89
	 * @return The new editing object for the given set of string
90
	 *         representations for boolean values.
91
	 */
92
	public static BooleanEditing forStringValues(String[] trueValues,
93
			String[] falseValues) {
94
		return new BooleanEditing(trueValues, falseValues, null);
95
	}
96
97
	/**
98
	 * Creates a new editing object which uses the given set of string
99
	 * representations for boolean values for parsing and displaying. Uses the
100
	 * specified custom validation message.
101
	 * 
102
	 * <p>
103
	 * For parsing, the given string values will be considered valid
104
	 * representations of {@code true} and {@code false}, respectively. For
105
	 * displaying, the first element of the respective array will be used for
106
	 * representing the corresponding boolean value.
107
	 * </p>
108
	 * 
109
	 * @param trueValues
110
	 *            The set of strings representing a <code>true</code> value.
111
	 * @param falseValues
112
	 *            The set of strings representing a <code>false</code> value.
113
	 * @param parseErrorMessage
114
	 *            The validation message issued in case the input string cannot
115
	 *            be parsed to an boolean.
116
	 * @return The new editing object for the given set of string
117
	 *         representations for boolean values.
118
	 */
119
	public static BooleanEditing forStringValues(String[] trueValues,
120
			String[] falseValues, String parseErrorMessage) {
121
		return new BooleanEditing(trueValues, falseValues, parseErrorMessage);
122
	}
123
124
	/**
125
	 * Returns the target constraints to apply.
126
	 * 
127
	 * <p>
128
	 * This method provides a typesafe access to the {@link StringConstraints
129
	 * string target constraints} of this editing object and is equivalent to
130
	 * {@code (StringConstraints) targetConstraints()}.
131
	 * </p>
132
	 * 
133
	 * @return The target constraints to apply.
134
	 * 
135
	 * @see #targetConstraints()
136
	 * @see StringConstraints
137
	 */
138
	public StringConstraints targetStringConstraints() {
139
		return (StringConstraints) targetConstraints();
140
	}
141
142
	/**
143
	 * Returns the model constraints to apply.
144
	 * 
145
	 * <p>
146
	 * This method provides a typesafe access to the {@link BooleanConstraints
147
	 * bool model constraints} of this editing object and is equivalent to
148
	 * {@code (BooleanConstraints) modelConstraints()}.
149
	 * </p>
150
	 * 
151
	 * @return The target constraints to apply.
152
	 * 
153
	 * @see #modelConstraints()
154
	 * @see BooleanConstraints
155
	 */
156
	public BooleanConstraints modelBooleanConstraints() {
157
		return (BooleanConstraints) modelConstraints();
158
	}
159
160
	/**
161
	 * Returns the before-set model constraints to apply.
162
	 * 
163
	 * <p>
164
	 * This method provides a typesafe access to the {@link BooleanConstraints
165
	 * bool before-set model constraints} of this editing object and is
166
	 * equivalent to {@code (BooleanConstraints) beforeSetModelConstraints()}.
167
	 * </p>
168
	 * 
169
	 * @return The target constraints to apply.
170
	 * 
171
	 * @see #beforeSetModelConstraints()
172
	 * @see BooleanConstraints
173
	 */
174
	public BooleanConstraints beforeSetModelBooleanConstraints() {
175
		return (BooleanConstraints) beforeSetModelConstraints();
176
	}
177
178
	protected Constraints createTargetConstraints() {
179
		return new StringConstraints();
180
	}
181
182
	protected Constraints createModelConstraints() {
183
		return new BooleanConstraints();
184
	}
185
186
	protected Constraints createBeforeSetModelConstraints() {
187
		return new BooleanConstraints();
188
	}
189
190
	/**
191
	 * Convenience method which adds a {@link BooleanConstraints#required()
192
	 * required constraint} to the set of {@link #modelBooleanConstraints()}.
193
	 * 
194
	 * @return This editing instance for method chaining.
195
	 * 
196
	 * @see BooleanConstraints#required()
197
	 * @see #modelBooleanConstraints()
198
	 */
199
	public BooleanEditing required() {
200
		modelBooleanConstraints().required();
201
		return this;
202
	}
203
}
(-)src/org/eclipse/core/internal/databinding/validation/NonNullValidator.java (+42 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.4
21
 */
22
public class NonNullValidator implements IValidator {
23
24
	private static final String NON_NULL_VALIDATION_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NON_NULL);
25
26
	private final String validationMessage;
27
28
	/**
29
	 * @param validationMessage
30
	 */
31
	public NonNullValidator(String validationMessage) {
32
		this.validationMessage = validationMessage != null ? validationMessage
33
				: NON_NULL_VALIDATION_MESSAGE;
34
	}
35
36
	public IStatus validate(Object value) {
37
		if (value == null) {
38
			return ValidationStatus.error(validationMessage);
39
		}
40
		return ValidationStatus.ok();
41
	}
42
}
(-)src/org/eclipse/core/databinding/validation/constraint/BooleanConstraints.java (+47 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
 * @since 1.4
18
 */
19
public final class BooleanConstraints extends Constraints {
20
21
	private String requiredMessage = null;
22
23
	/**
24
	 * Adds a validator ensuring that the boolean value is not <code>null</code>
25
	 * . Uses the current {@link #requiredMessage(String) validation message}.
26
	 * 
27
	 * @return This constraints instance for method chaining.
28
	 */
29
	public BooleanConstraints required() {
30
		addValidator(new NonNullValidator(requiredMessage));
31
		return this;
32
	}
33
34
	/**
35
	 * Sets the validation message for the {@link #required()} constraint.
36
	 * 
37
	 * @param message
38
	 *            The validation message for the {@link #required()} constraint.
39
	 * @return This constraints instance for method chaining.
40
	 * 
41
	 * @see #required()
42
	 */
43
	public BooleanConstraints requiredMessage(String message) {
44
		this.requiredMessage = message;
45
		return this;
46
	}
47
}
(-)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.4
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/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.4
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/validation/constraint/Constraints.java (+180 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
 * @since 1.4
27
 */
28
public class Constraints {
29
30
	/**
31
	 * Constant denoting an aggregation strategy that merges multiple non-OK
32
	 * status objects in a {@link MultiStatus}. Returns an OK status result if
33
	 * all statuses from the set of validators to apply are an OK status.
34
	 * Returns a single status if there is only one non-OK status.
35
	 * 
36
	 * @see #aggregationPolicy(int)
37
	 */
38
	public static final int AGGREGATION_MERGED = 1;
39
40
	/**
41
	 * Constant denoting an aggregation strategy that always returns the most
42
	 * severe status from the set of validators to apply. If there is more than
43
	 * one status at the same severity level, it picks the first one it
44
	 * encounters.
45
	 * 
46
	 * @see #aggregationPolicy(int)
47
	 */
48
	public static final int AGGREGATION_MAX_SEVERITY = 2;
49
50
	// Will be initialized lazily.
51
	private List validators = null;
52
53
	private IValidator cachedValidator = null;
54
55
	private int aggregationPolicy = AGGREGATION_MAX_SEVERITY;
56
57
	/**
58
	 * Adds a custom validator to the set of constraints to apply.
59
	 * 
60
	 * @param validator
61
	 *            The custom validator to add to the set of constraints.
62
	 * @return This constraints instance for method chaining.
63
	 */
64
	public final Constraints addValidator(IValidator validator) {
65
		if (validators == null) {
66
			validators = new ArrayList(2);
67
		}
68
		validators.add(validator);
69
		cachedValidator = null;
70
		return this;
71
	}
72
73
	/**
74
	 * Sets the aggregation policy to apply to the individual validations which
75
	 * constitute this set of constraints.
76
	 * 
77
	 * @param policy
78
	 *            The validation aggregation policy to set. Must be one of
79
	 *            {@link #AGGREGATION_MERGED} or
80
	 *            {@link #AGGREGATION_MAX_SEVERITY}.
81
	 * @return This constraints instance for method chaining.
82
	 * 
83
	 * @see #AGGREGATION_MERGED
84
	 * @see #AGGREGATION_MAX_SEVERITY
85
	 */
86
	public final Constraints aggregationPolicy(int policy) {
87
		this.aggregationPolicy = policy;
88
		cachedValidator = null;
89
		return this;
90
	}
91
92
	/**
93
	 * Creates a validator which enforces the current set of constraints.
94
	 * 
95
	 * <p>
96
	 * Note that this method will return <code>null</code> in case the set of
97
	 * constraints to apply is empty.
98
	 * </p>
99
	 * 
100
	 * @return A validator which enforces the current set of constraints. May be
101
	 *         <code>null</code>.
102
	 */
103
	public final IValidator createValidator() {
104
		if (validators != null && !validators.isEmpty()) {
105
			if (cachedValidator == null) {
106
				if (validators.size() == 1) {
107
					cachedValidator = (IValidator) validators.get(0);
108
				} else {
109
					IValidator[] currentValidators = (IValidator[]) validators
110
							.toArray(new IValidator[validators.size()]);
111
					cachedValidator = new ConstraintsValidator(
112
							currentValidators, aggregationPolicy);
113
				}
114
			}
115
			return cachedValidator;
116
		}
117
		return null;
118
	}
119
120
	private static final class ConstraintsValidator implements IValidator {
121
122
		private final IValidator[] validators;
123
124
		private final int aggregationPolicy;
125
126
		public ConstraintsValidator(IValidator[] validators,
127
				int aggregationPolicy) {
128
			this.validators = validators;
129
			this.aggregationPolicy = aggregationPolicy;
130
		}
131
132
		public IStatus validate(Object value) {
133
			return (aggregationPolicy == AGGREGATION_MERGED) ? validateMerged(value)
134
					: validateMaxSeverity(value);
135
		}
136
137
		private IStatus validateMerged(Object value) {
138
			List statuses = new ArrayList();
139
			for (int i = 0; i < validators.length; i++) {
140
				IValidator validator = validators[i];
141
				IStatus status = validator.validate(value);
142
				if (!status.isOK()) {
143
					statuses.add(status);
144
				}
145
			}
146
147
			if (statuses.size() == 1) {
148
				return (IStatus) statuses.get(0);
149
			}
150
151
			if (!statuses.isEmpty()) {
152
				MultiStatus result = new MultiStatus(Policy.JFACE_DATABINDING,
153
						0, BindingMessages
154
								.getString(BindingMessages.MULTIPLE_PROBLEMS),
155
						null);
156
				for (Iterator it = statuses.iterator(); it.hasNext();) {
157
					IStatus status = (IStatus) it.next();
158
					result.merge(status);
159
				}
160
				return result;
161
			}
162
163
			return Status.OK_STATUS;
164
		}
165
166
		private IStatus validateMaxSeverity(Object value) {
167
			int maxSeverity = IStatus.OK;
168
			IStatus maxStatus = Status.OK_STATUS;
169
			for (int i = 0; i < validators.length; i++) {
170
				IValidator validator = validators[i];
171
				IStatus status = validator.validate(value);
172
				if (status.getSeverity() > maxSeverity) {
173
					maxSeverity = status.getSeverity();
174
					maxStatus = status;
175
				}
176
			}
177
			return maxStatus;
178
		}
179
	}
180
}
(-)src/org/eclipse/core/databinding/validation/constraint/StringConstraints.java (+248 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
 * @since 1.4
25
 */
26
public final class StringConstraints extends Constraints {
27
28
	private NumberFormat integerDisplayFormat = NumberFormat
29
			.getIntegerInstance();
30
31
	private String requiredMessage = null;
32
33
	private String nonEmptyMessage = null;
34
35
	private String minLengthMessage = null;
36
37
	private String maxLengthMessage = null;
38
39
	private String lengthRangeMessage = null;
40
41
	private String matchesMessage = null;
42
43
	/**
44
	 * Sets the format to use when formatting an integer to be included in any
45
	 * of the validation messages.
46
	 * 
47
	 * <p>
48
	 * This integer format will be used for any subsequent constraints which are
49
	 * applied.
50
	 * </p>
51
	 * 
52
	 * @param format
53
	 *            The format to use for displaying integers in validation
54
	 *            messages.
55
	 * @return This constraints instance for method chaining.
56
	 * 
57
	 * @see #minLength(int)
58
	 * @see #maxLength(int)
59
	 * @see #lengthRange(int, int)
60
	 */
61
	public StringConstraints integerDisplayFormat(NumberFormat format) {
62
		this.integerDisplayFormat = format;
63
		return this;
64
	}
65
66
	/**
67
	 * Adds a validator ensuring that the parsed integer is not
68
	 * <code>null</code>. Uses the current {@link #requiredMessage(String)
69
	 * validation message}.
70
	 * 
71
	 * @return This constraints instance for method chaining.
72
	 */
73
	public StringConstraints required() {
74
		addValidator(new NonNullValidator(requiredMessage));
75
		return this;
76
	}
77
78
	/**
79
	 * Sets the validation message for the {@link #required()} constraint.
80
	 * 
81
	 * @param message
82
	 *            The validation message for the {@link #required()} constraint.
83
	 * @return This constraints instance for method chaining.
84
	 * 
85
	 * @see #required()
86
	 */
87
	public StringConstraints requiredMessage(String message) {
88
		this.requiredMessage = message;
89
		return this;
90
	}
91
92
	/**
93
	 * Adds a validator ensuring that the parsed integer is not empty. Uses the
94
	 * current {@link #nonEmptyMessage(String) validation message}.
95
	 * 
96
	 * @return This constraints instance for method chaining.
97
	 */
98
	public StringConstraints nonEmpty() {
99
		addValidator(new NonEmptyStringValidator(nonEmptyMessage));
100
		return this;
101
	}
102
103
	/**
104
	 * Sets the validation message for the {@link #nonEmpty()} constraint.
105
	 * 
106
	 * @param message
107
	 *            The validation message for the {@link #nonEmpty()} constraint.
108
	 * @return This constraints instance for method chaining.
109
	 * 
110
	 * @see #nonEmpty()
111
	 */
112
	public StringConstraints nonEmptyMessage(String message) {
113
		this.nonEmptyMessage = message;
114
		return this;
115
	}
116
117
	/**
118
	 * Adds a validator ensuring that the input string has at least the
119
	 * specified amount of characters. Uses the current
120
	 * {@link #minLengthMessage(String) validation message}.
121
	 * 
122
	 * @param minLength
123
	 *            The minimal length to be enforced on the input string.
124
	 * @return This constraints instance for method chaining.
125
	 */
126
	public StringConstraints minLength(int minLength) {
127
		addValidator(StringLengthValidator.minLength(minLength,
128
				minLengthMessage, integerDisplayFormat));
129
		return this;
130
	}
131
132
	/**
133
	 * Sets the validation message pattern for the {@link #minLength(int)}
134
	 * constraint.
135
	 * 
136
	 * @param message
137
	 *            The validation message pattern for the {@link #minLength(int)}
138
	 *            constraint. Can be parameterized with the minimum string
139
	 *            length.
140
	 * @return This constraints instance for method chaining.
141
	 * 
142
	 * @see #minLength(int)
143
	 */
144
	public StringConstraints minLengthMessage(String message) {
145
		this.minLengthMessage = message;
146
		return this;
147
	}
148
149
	/**
150
	 * Adds a validator ensuring that the input string has not more than the
151
	 * specified amount of characters. Uses the current
152
	 * {@link #maxLengthMessage(String) validation message}.
153
	 * 
154
	 * @param maxLength
155
	 *            The maximum length to be enforced on the input string.
156
	 * @return This constraints instance for method chaining.
157
	 */
158
	public StringConstraints maxLength(int maxLength) {
159
		addValidator(StringLengthValidator.maxLength(maxLength,
160
				maxLengthMessage, integerDisplayFormat));
161
		return this;
162
	}
163
164
	/**
165
	 * Sets the validation message pattern for the {@link #maxLength(int)}
166
	 * constraint.
167
	 * 
168
	 * @param message
169
	 *            The validation message pattern for the {@link #maxLength(int)}
170
	 *            constraint. Can be parameterized with the maximum string
171
	 *            length.
172
	 * @return This constraints instance for method chaining.
173
	 * 
174
	 * @see #maxLength(int)
175
	 */
176
	public StringConstraints maxLengthMessage(String message) {
177
		this.maxLengthMessage = message;
178
		return this;
179
	}
180
181
	/**
182
	 * Adds a validator ensuring that the length of the input string is between
183
	 * the given bounds. Uses the current {@link #lengthRangeMessage(String)
184
	 * validation message}.
185
	 * 
186
	 * @param minLength
187
	 *            The minimal length to be enforced on the input string.
188
	 * @param maxLength
189
	 *            The maximum length to be enforced on the input string.
190
	 * @return This constraints instance for method chaining.
191
	 */
192
	public StringConstraints lengthRange(int minLength, int maxLength) {
193
		addValidator(StringLengthValidator.lengthRange(minLength, maxLength,
194
				lengthRangeMessage, integerDisplayFormat));
195
		return this;
196
	}
197
198
	/**
199
	 * Sets the validation message pattern for the
200
	 * {@link #lengthRange(int, int)} constraint.
201
	 * 
202
	 * @param message
203
	 *            The validation message pattern for the
204
	 *            {@link #lengthRange(int, int)} constraint. Can be
205
	 *            parameterized with the minimum and maximum string lengths.
206
	 * @return This constraints instance for method chaining.
207
	 * 
208
	 * @see #lengthRange(int, int)
209
	 */
210
	public StringConstraints lengthRangeMessage(String message) {
211
		this.lengthRangeMessage = message;
212
		return this;
213
	}
214
215
	/**
216
	 * Adds a validator ensuring that the input string
217
	 * {@link Pattern#matches(String, CharSequence) matches} the given regular
218
	 * expression. Uses the current {@link #matchesMessage(String) validation
219
	 * message}.
220
	 * 
221
	 * @param regex
222
	 *            The regular expression which the input string must match.
223
	 * @return This constraints instance for method chaining.
224
	 * 
225
	 * @see Pattern#matches(String, CharSequence)
226
	 */
227
	public StringConstraints matches(String regex) {
228
		addValidator(new StringRegexValidator(regex, matchesMessage));
229
		return this;
230
	}
231
232
	/**
233
	 * Sets the validation message pattern for the {@link #matches(String)}
234
	 * constraint.
235
	 * 
236
	 * @param message
237
	 *            The validation message pattern for the
238
	 *            {@link #matches(String)} constraint. Can be parameterized with
239
	 *            the pattern string which the parsed integer must match.
240
	 * @return This constraints instance for method chaining.
241
	 * 
242
	 * @see #matches(String)
243
	 */
244
	public StringConstraints matchesMessage(String message) {
245
		this.matchesMessage = message;
246
		return this;
247
	}
248
}
(-)src/org/eclipse/core/databinding/editing/Editing.java (+1010 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.4
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
	 * Convenience method which {@link Constraints#addValidator(IValidator)
196
	 * adds} the given validator to the set of {@link #targetConstraints()}.
197
	 * 
198
	 * @param validator
199
	 *            The validator to add to the target constraints.
200
	 * @return This editing instance for method chaining.
201
	 * 
202
	 * @see Constraints#addValidator(IValidator)
203
	 * @see #targetConstraints()
204
	 */
205
	public final Editing addTargetValidator(IValidator validator) {
206
		targetConstraints().addValidator(validator);
207
		return this;
208
	}
209
210
	/**
211
	 * Convenience method which {@link Constraints#addValidator(IValidator)
212
	 * adds} the given validator to the set of {@link #modelConstraints()}.
213
	 * 
214
	 * @param validator
215
	 *            The validator to add to the model constraints.
216
	 * @return This editing instance for method chaining.
217
	 * 
218
	 * @see Constraints#addValidator(IValidator)
219
	 * @see #modelConstraints()
220
	 */
221
	public final Editing addModelValidator(IValidator validator) {
222
		modelConstraints().addValidator(validator);
223
		return this;
224
	}
225
226
	/**
227
	 * Convenience method which {@link Constraints#addValidator(IValidator)
228
	 * adds} the given validator to the set of
229
	 * {@link #beforeSetModelConstraints()}.
230
	 * 
231
	 * @param validator
232
	 *            The validator to add to the before-set model constraints.
233
	 * @return This editing instance for method chaining.
234
	 * 
235
	 * @see Constraints#addValidator(IValidator)
236
	 * @see #beforeSetModelConstraints
237
	 */
238
	public final Editing addBeforeSetModelValidator(IValidator validator) {
239
		beforeSetModelConstraints().addValidator(validator);
240
		return this;
241
	}
242
243
	/**
244
	 * Sets the target-to-model converter for this editing instance.
245
	 * 
246
	 * @param converter
247
	 *            The target-to-model converter to set.
248
	 */
249
	protected final void setTargetConverter(IConverter converter) {
250
		this.targetConverter = converter;
251
	}
252
253
	/**
254
	 * Sets the model-to-target converter for this editing instance.
255
	 * 
256
	 * @param converter
257
	 *            The model-to-target converter to set.
258
	 */
259
	protected final void setModelConverter(IConverter converter) {
260
		this.modelConverter = converter;
261
	}
262
263
	/**
264
	 * Creates a new target-to-model {@link UpdateValueStrategy} with a default
265
	 * update policy configured by the current state of this editing object.
266
	 * 
267
	 * @return A new target-to-model {@link UpdateValueStrategy} configured by
268
	 *         the current state of this editing object.
269
	 * 
270
	 * @see UpdateValueStrategy#UpdateValueStrategy()
271
	 * @see #applyToT2MValueStrategy(UpdateValueStrategy)
272
	 */
273
	public final UpdateValueStrategy createT2MValueStrategy() {
274
		return applyToT2MValueStrategy(new UpdateValueStrategy());
275
	}
276
277
	/**
278
	 * Creates a new target-to-model {@link UpdateValueStrategy} with the given
279
	 * update policy configured by the current state of this editing object.
280
	 * 
281
	 * @param updatePolicy
282
	 *            The update policy to use.
283
	 * @return A new target-to-model {@link UpdateValueStrategy} configured by
284
	 *         the current state of this editing object.
285
	 * 
286
	 * @see UpdateValueStrategy#UpdateValueStrategy(int)
287
	 * @see #applyToT2MValueStrategy(UpdateValueStrategy)
288
	 */
289
	public final UpdateValueStrategy createT2MValueStrategy(int updatePolicy) {
290
		return applyToT2MValueStrategy(new UpdateValueStrategy(updatePolicy));
291
	}
292
293
	/**
294
	 * Creates a new model-to-target {@link UpdateValueStrategy} with a default
295
	 * update policy configured by the current state of this editing object.
296
	 * 
297
	 * @return A new model-to-target {@link UpdateValueStrategy} configured by
298
	 *         the current state of this editing object.
299
	 * 
300
	 * @see UpdateValueStrategy#UpdateValueStrategy()
301
	 * @see #applyToM2TValueStrategy(UpdateValueStrategy)
302
	 */
303
	public final UpdateValueStrategy createM2TValueStrategy() {
304
		return applyToM2TValueStrategy(new UpdateValueStrategy());
305
	}
306
307
	/**
308
	 * Creates a new model-to-target {@link UpdateValueStrategy} with the given
309
	 * update policy configured by the current state of this editing object.
310
	 * 
311
	 * @param updatePolicy
312
	 *            The update policy to use.
313
	 * @return A new model-to-target {@link UpdateValueStrategy} configured by
314
	 *         the current state of this editing object.
315
	 * 
316
	 * @see UpdateValueStrategy#UpdateValueStrategy(int)
317
	 * @see #applyToM2TValueStrategy(UpdateValueStrategy)
318
	 */
319
	public final UpdateValueStrategy createM2TValueStrategy(int updatePolicy) {
320
		return applyToM2TValueStrategy(new UpdateValueStrategy(updatePolicy));
321
	}
322
323
	/**
324
	 * Creates a new target-to-model {@link UpdateListStrategy} with a default
325
	 * update policy configured by the current state of this editing object.
326
	 * 
327
	 * @return A new target-to-model {@link UpdateListStrategy} configured by
328
	 *         the current state of this editing object.
329
	 * 
330
	 * @see UpdateListStrategy#UpdateListStrategy()
331
	 * @see #applyToT2MListStrategy(UpdateListStrategy)
332
	 */
333
	public final UpdateListStrategy createT2MListStrategy() {
334
		return applyToT2MListStrategy(new UpdateListStrategy());
335
	}
336
337
	/**
338
	 * Creates a new target-to-model {@link UpdateListStrategy} with the given
339
	 * update policy configured by the current state of this editing object.
340
	 * 
341
	 * @param updatePolicy
342
	 *            The update policy to use.
343
	 * @return A new target-to-model {@link UpdateListStrategy} configured by
344
	 *         the current state of this editing object.
345
	 * 
346
	 * @see UpdateListStrategy#UpdateListStrategy(int)
347
	 * @see #applyToT2MListStrategy(UpdateListStrategy)
348
	 */
349
	public final UpdateListStrategy createT2MListStrategy(int updatePolicy) {
350
		return applyToT2MListStrategy(new UpdateListStrategy(updatePolicy));
351
	}
352
353
	/**
354
	 * Creates a new model-to-target {@link UpdateListStrategy} with a default
355
	 * update policy configured by the current state of this editing object.
356
	 * 
357
	 * @return A new model-to-target {@link UpdateListStrategy} configured by
358
	 *         the current state of this editing object.
359
	 * 
360
	 * @see UpdateListStrategy#UpdateListStrategy()
361
	 * @see #applyToM2TListStrategy(UpdateListStrategy)
362
	 */
363
	public final UpdateListStrategy createM2TListStrategy() {
364
		return applyToM2TListStrategy(new UpdateListStrategy());
365
	}
366
367
	/**
368
	 * Creates a new model-to-target {@link UpdateListStrategy} with the given
369
	 * update policy configured by the current state of this editing object.
370
	 * 
371
	 * @param updatePolicy
372
	 *            The update policy to use.
373
	 * @return A new model-to-target {@link UpdateListStrategy} configured by
374
	 *         the current state of this editing object.
375
	 * 
376
	 * @see UpdateListStrategy#UpdateListStrategy(int)
377
	 * @see #applyToM2TListStrategy(UpdateListStrategy)
378
	 */
379
	public final UpdateListStrategy createM2TListStrategy(int updatePolicy) {
380
		return applyToM2TListStrategy(new UpdateListStrategy(updatePolicy));
381
	}
382
383
	/**
384
	 * Creates a new target-to-model {@link UpdateSetStrategy} with a default
385
	 * update policy configured by the current state of this editing object.
386
	 * 
387
	 * @return A new target-to-model {@link UpdateSetStrategy} configured by the
388
	 *         current state of this editing object.
389
	 * 
390
	 * @see UpdateListStrategy#UpdateListStrategy()
391
	 * @see #applyToT2MSetStrategy(UpdateSetStrategy)
392
	 */
393
	public final UpdateSetStrategy createT2MSetStrategy() {
394
		return applyToT2MSetStrategy(new UpdateSetStrategy());
395
	}
396
397
	/**
398
	 * Creates a new target-to-model {@link UpdateListStrategy} with the given
399
	 * update policy configured by the current state of this editing object.
400
	 * 
401
	 * @param updatePolicy
402
	 *            The update policy to use.
403
	 * @return A new target-to-model {@link UpdateListStrategy} configured by
404
	 *         the current state of this editing object.
405
	 * 
406
	 * @see UpdateSetStrategy#UpdateSetStrategy(int)
407
	 * @see #applyToT2MSetStrategy(UpdateSetStrategy)
408
	 */
409
	public final UpdateSetStrategy createT2MSetStrategy(int updatePolicy) {
410
		return applyToT2MSetStrategy(new UpdateSetStrategy(updatePolicy));
411
	}
412
413
	/**
414
	 * Creates a new model-to-target {@link UpdateSetStrategy} with a default
415
	 * update policy configured by the current state of this editing object.
416
	 * 
417
	 * @return A new model-to-target {@link UpdateSetStrategy} configured by the
418
	 *         current state of this editing object.
419
	 * 
420
	 * @see UpdateSetStrategy#UpdateSetStrategy()
421
	 * @see #applyToM2TSetStrategy(UpdateSetStrategy)
422
	 */
423
	public final UpdateSetStrategy createM2TSetStrategy() {
424
		return applyToM2TSetStrategy(new UpdateSetStrategy());
425
	}
426
427
	/**
428
	 * Creates a new model-to-target {@link UpdateSetStrategy} with the given
429
	 * update policy configured by the current state of this editing object.
430
	 * 
431
	 * @param updatePolicy
432
	 *            The update policy to use.
433
	 * @return A new model-to-target {@link UpdateSetStrategy} configured by the
434
	 *         current state of this editing object.
435
	 * 
436
	 * @see UpdateSetStrategy#UpdateSetStrategy(int)
437
	 * @see #applyToM2TSetStrategy(UpdateSetStrategy)
438
	 */
439
	public final UpdateSetStrategy createM2TSetStrategy(int updatePolicy) {
440
		return applyToM2TSetStrategy(new UpdateSetStrategy(updatePolicy));
441
	}
442
443
	/**
444
	 * Configures an existing target-to-model {@link UpdateValueStrategy} with
445
	 * the current state of this editing object.
446
	 * 
447
	 * <p>
448
	 * The configuration is done as follows:
449
	 * <ul>
450
	 * <li>
451
	 * The {@link Constraints#createValidator() validator} of the
452
	 * {@link #targetConstraints() target constraints} is set as the
453
	 * {@link UpdateValueStrategy#setAfterGetValidator(IValidator) after-get
454
	 * validator} of the update strategy.</li>
455
	 * <li>The {@link #setTargetConverter(IConverter) target converter} is set
456
	 * as the {@link UpdateValueStrategy#setConverter(IConverter) converter} of
457
	 * the update strategy.</li>
458
	 * <li>
459
	 * The {@link Constraints#createValidator() validator} of the
460
	 * {@link #modelConstraints() model constraints} is set as the
461
	 * {@link UpdateValueStrategy#setAfterConvertValidator(IValidator)
462
	 * after-convert validator} of the update strategy.</li>
463
	 * <li>The {@link Constraints#createValidator() validator} of the
464
	 * {@link #beforeSetModelConstraints() before-set model constraints} is set
465
	 * as the {@link UpdateValueStrategy#setBeforeSetValidator(IValidator)
466
	 * before-set validator} of the update strategy.</li>
467
	 * </ul>
468
	 * </p>
469
	 * 
470
	 * @param updateStrategy
471
	 *            The {@link UpdateValueStrategy} to configure.
472
	 * @return The passed-in, configured target-to-model
473
	 *         {@link UpdateValueStrategy}.
474
	 * 
475
	 * @see UpdateValueStrategy#setAfterGetValidator(IValidator)
476
	 * @see UpdateValueStrategy#setConverter(IConverter)
477
	 * @see UpdateValueStrategy#setAfterConvertValidator(IValidator)
478
	 * @see UpdateValueStrategy#setBeforeSetValidator(IValidator)
479
	 */
480
	public final UpdateValueStrategy applyToT2MValueStrategy(
481
			UpdateValueStrategy updateStrategy) {
482
		updateStrategy.setAfterGetValidator(createValidator(targetConstraints));
483
		updateStrategy.setConverter(targetConverter);
484
		updateStrategy
485
				.setAfterConvertValidator(createValidator(modelConstraints));
486
		updateStrategy
487
				.setBeforeSetValidator(createValidator(beforeSetModelConstraints));
488
		return updateStrategy;
489
	}
490
491
	/**
492
	 * Configures an existing model-to-target {@link UpdateValueStrategy} with
493
	 * the current state of this editing object by setting the
494
	 * {@link #setModelConverter(IConverter) model converter} as the
495
	 * {@link UpdateValueStrategy#setConverter(IConverter) converter} of the
496
	 * update strategy.
497
	 * 
498
	 * @param updateStrategy
499
	 *            The {@link UpdateValueStrategy} to configure.
500
	 * @return The passed-in, configured model-to-target
501
	 *         {@link UpdateValueStrategy}.
502
	 * 
503
	 * @see UpdateValueStrategy#setConverter(IConverter)
504
	 */
505
	public final UpdateValueStrategy applyToM2TValueStrategy(
506
			UpdateValueStrategy updateStrategy) {
507
		updateStrategy.setConverter(modelConverter);
508
		return updateStrategy;
509
	}
510
511
	/**
512
	 * Configures an existing target-to-model {@link UpdateListStrategy} with
513
	 * the current state of this editing object by setting the
514
	 * {@link #setTargetConverter(IConverter) target converter} as the
515
	 * {@link UpdateListStrategy#setConverter(IConverter) converter} of the
516
	 * update strategy.
517
	 * 
518
	 * @param updateStrategy
519
	 *            The {@link UpdateListStrategy} to configure.
520
	 * @return The passed-in, configured target-to-model
521
	 *         {@link UpdateListStrategy}.
522
	 * 
523
	 * @see UpdateListStrategy#setConverter(IConverter)
524
	 */
525
	public final UpdateListStrategy applyToT2MListStrategy(
526
			UpdateListStrategy updateStrategy) {
527
		updateStrategy.setConverter(targetConverter);
528
		return updateStrategy;
529
	}
530
531
	/**
532
	 * Configures an existing model-to-target {@link UpdateListStrategy} with
533
	 * the current state of this editing object by setting the
534
	 * {@link #setModelConverter(IConverter) model converter} as the
535
	 * {@link UpdateListStrategy#setConverter(IConverter) converter} of the
536
	 * update strategy.
537
	 * 
538
	 * @param updateStrategy
539
	 *            The {@link UpdateListStrategy} to configure.
540
	 * @return The passed-in, configured model-to-target
541
	 *         {@link UpdateListStrategy}.
542
	 * 
543
	 * @see UpdateListStrategy#setConverter(IConverter)
544
	 */
545
	public final UpdateListStrategy applyToM2TListStrategy(
546
			UpdateListStrategy updateStrategy) {
547
		updateStrategy.setConverter(modelConverter);
548
		return updateStrategy;
549
	}
550
551
	/**
552
	 * Configures an existing target-to-model {@link UpdateListStrategy} with
553
	 * the current state of this editing object by setting the
554
	 * {@link #setTargetConverter(IConverter) target converter} as the
555
	 * {@link UpdateSetStrategy#setConverter(IConverter) converter} of the
556
	 * update strategy.
557
	 * 
558
	 * @param updateStrategy
559
	 *            The {@link UpdateSetStrategy} to configure.
560
	 * @return The passed-in, configured target-to-model
561
	 *         {@link UpdateSetStrategy}.
562
	 * 
563
	 * @see UpdateSetStrategy#setConverter(IConverter)
564
	 */
565
	public final UpdateSetStrategy applyToT2MSetStrategy(
566
			UpdateSetStrategy updateStrategy) {
567
		updateStrategy.setConverter(targetConverter);
568
		return updateStrategy;
569
	}
570
571
	/**
572
	 * Configures an existing model-to-target {@link UpdateSetStrategy} with the
573
	 * current state of this editing object by setting the
574
	 * {@link #setModelConverter(IConverter) model converter} as the
575
	 * {@link UpdateSetStrategy#setConverter(IConverter) converter} of the
576
	 * update strategy.
577
	 * 
578
	 * @param updateStrategy
579
	 *            The {@link UpdateSetStrategy} to configure.
580
	 * @return The passed-in, configured model-to-target
581
	 *         {@link UpdateSetStrategy}.
582
	 * 
583
	 * @see UpdateSetStrategy#setConverter(IConverter)
584
	 */
585
	public final UpdateSetStrategy applyToM2TSetStrategy(
586
			UpdateSetStrategy updateStrategy) {
587
		updateStrategy.setConverter(modelConverter);
588
		return updateStrategy;
589
	}
590
591
	/**
592
	 * Converts a target value to a model value by performing the following
593
	 * steps:
594
	 * <ul>
595
	 * <li>
596
	 * Applying all the {@link #targetConstraints() target constraints} to the
597
	 * given target value.</li>
598
	 * <li>
599
	 * {@link #setTargetConverter(IConverter) Converting} the target value to
600
	 * the model value.</li>
601
	 * <li>
602
	 * Applying all the {@link #modelConstraints() model constraints} to the
603
	 * converted model value.</li>
604
	 * <li>
605
	 * Applying all the {@link #beforeSetModelConstraints() before-set model
606
	 * constraints} to the converted model value.</li>
607
	 * </ul>
608
	 * 
609
	 * <p>
610
	 * The conversion process will be aborted by returning <code>null</code>
611
	 * whenever any of the applied validators produces a {@link IStatus
612
	 * validation status} having {@link IStatus#getSeverity() severity}
613
	 * <code>IStatus.ERROR</code> or <code>IStatus.CANCEL</code>. During the
614
	 * conversion process, any validation status whose severity is different
615
	 * from <code>IStatus.OK</code> will be {@link MultiStatus#merge(IStatus)
616
	 * aggregated} on the given <code>validationStatus</code>.
617
	 * </p>
618
	 * 
619
	 * @param targetValue
620
	 *            The target value to be converted to a model value.
621
	 * @param validationStatus
622
	 *            Aggregate validation status to which to add the validations
623
	 *            produced during the conversion process.
624
	 * @return The converted model value or <code>null</code> in case the
625
	 *         conversion has been aborted due to a validation error.
626
	 */
627
	public final Object convertToModel(Object targetValue,
628
			MultiStatus validationStatus) {
629
		IValidator targetValidator = createValidator(targetConstraints);
630
		if (!applyValidator(targetValidator, targetValue, validationStatus)) {
631
			return null;
632
		}
633
634
		Object modelValue = (targetConverter != null) ? targetConverter
635
				.convert(targetValue) : targetValue;
636
637
		IValidator modelValidator = createValidator(modelConstraints);
638
		if (!applyValidator(modelValidator, modelValue, validationStatus)) {
639
			return null;
640
		}
641
642
		IValidator beforeSetModelValidator = createValidator(beforeSetModelConstraints);
643
		if (!applyValidator(beforeSetModelValidator, modelValue,
644
				validationStatus)) {
645
			return null;
646
		}
647
648
		return modelValue;
649
	}
650
651
	/**
652
	 * {@link #setModelConverter(IConverter) Converts} a model value to a target
653
	 * value.
654
	 * 
655
	 * @param modelValue
656
	 *            The model value to be converted to a target value.
657
	 * @return The converted target value.
658
	 */
659
	public final Object convertToTarget(Object modelValue) {
660
		return (modelConverter != null) ? modelConverter.convert(modelValue)
661
				: modelValue;
662
	}
663
664
	/**
665
	 * Creates a binding between a target and model observable value on the
666
	 * given binding context by creating new update strategies which will be
667
	 * both configured with the state of this editing object before passing them
668
	 * to the binding.
669
	 * 
670
	 * <p>
671
	 * The target-to-model and model-to-target update strategies for the binding
672
	 * will be created by the methods {@link #createT2MValueStrategy()} and
673
	 * {@link #createM2TValueStrategy()}, respectively.
674
	 * </p>
675
	 * 
676
	 * @param dbc
677
	 *            The binding context on which to create the value binding.
678
	 * @param targetObservableValue
679
	 *            The target observable value of the binding.
680
	 * @param modelObservableValue
681
	 *            The model observable value of the binding.
682
	 * @return The new value binding.
683
	 * 
684
	 * @see #createT2MValueStrategy()
685
	 * @see #createM2TValueStrategy()
686
	 * @see DataBindingContext#bindValue(IObservableValue, IObservableValue,
687
	 *      UpdateValueStrategy, UpdateValueStrategy)
688
	 */
689
	public final Binding bindValue(DataBindingContext dbc,
690
			IObservableValue targetObservableValue,
691
			IObservableValue modelObservableValue) {
692
		return dbc.bindValue(targetObservableValue, modelObservableValue,
693
				createT2MValueStrategy(), createM2TValueStrategy());
694
	}
695
696
	/**
697
	 * Creates a binding between a target and model observable value on the
698
	 * given binding context by creating new update strategies with the provided
699
	 * update policies which will be both configured with the state of this
700
	 * editing object before passing them to the binding.
701
	 * 
702
	 * @param dbc
703
	 *            The binding context on which to create the value binding.
704
	 * @param targetObservableValue
705
	 *            The target observable value of the binding.
706
	 * @param modelObservableValue
707
	 *            The model observable value of the binding.
708
	 * @param t2mUpdatePolicy
709
	 *            The update policy for the target-to-model
710
	 *            {@link UpdateValueStrategy} which is
711
	 *            {@link #createT2MValueStrategy(int) created} and passed to the
712
	 *            new binding.
713
	 * @param m2tUpdatePolicy
714
	 *            The update policy for the model-to-target
715
	 *            {@link UpdateValueStrategy} which is
716
	 *            {@link #createM2TValueStrategy(int) created} and passed to the
717
	 *            new binding.
718
	 * @return The new value binding.
719
	 * 
720
	 * @see #createT2MValueStrategy(int)
721
	 * @see #createM2TValueStrategy(int)
722
	 * @see DataBindingContext#bindValue(IObservableValue, IObservableValue,
723
	 *      UpdateValueStrategy, UpdateValueStrategy)
724
	 */
725
	public final Binding bindValue(DataBindingContext dbc,
726
			IObservableValue targetObservableValue,
727
			IObservableValue modelObservableValue, int t2mUpdatePolicy,
728
			int m2tUpdatePolicy) {
729
		return dbc.bindValue(targetObservableValue, modelObservableValue,
730
				createT2MValueStrategy(t2mUpdatePolicy),
731
				createM2TValueStrategy(m2tUpdatePolicy));
732
	}
733
734
	/**
735
	 * Creates a binding between a target and model observable value on the
736
	 * given binding context by using the provided update strategies which will
737
	 * be both configured with the state of this editing object before passing
738
	 * them to the binding.
739
	 * 
740
	 * @param dbc
741
	 *            The binding context on which to create the value binding.
742
	 * @param targetObservableValue
743
	 *            The target observable value of the binding.
744
	 * @param modelObservableValue
745
	 *            The model observable value of the binding.
746
	 * @param t2mUpdateStrategy
747
	 *            The target-to-model {@link UpdateValueStrategy} of the binding
748
	 *            to be {@link #applyToT2MValueStrategy(UpdateValueStrategy)
749
	 *            configured} with the state of this editing object before
750
	 *            passing it to the binding.
751
	 * @param m2tUpdateStrategy
752
	 *            The model-to-target {@link UpdateValueStrategy} of the binding
753
	 *            to be {@link #applyToM2TValueStrategy(UpdateValueStrategy)
754
	 *            configured} with the state of this editing object before
755
	 *            passing it to the binding.
756
	 * @return The new value binding.
757
	 * 
758
	 * @see #applyToT2MValueStrategy(UpdateValueStrategy)
759
	 * @see #applyToM2TValueStrategy(UpdateValueStrategy)
760
	 * @see DataBindingContext#bindValue(IObservableValue, IObservableValue,
761
	 *      UpdateValueStrategy, UpdateValueStrategy)
762
	 */
763
	public final Binding bindValue(DataBindingContext dbc,
764
			IObservableValue targetObservableValue,
765
			IObservableValue modelObservableValue,
766
			UpdateValueStrategy t2mUpdateStrategy,
767
			UpdateValueStrategy m2tUpdateStrategy) {
768
		return dbc.bindValue(targetObservableValue, modelObservableValue,
769
				applyToT2MValueStrategy(t2mUpdateStrategy),
770
				applyToM2TValueStrategy(m2tUpdateStrategy));
771
	}
772
773
	/**
774
	 * Creates a binding between a target and model observable list on the given
775
	 * binding context by creating new update strategies which will be both
776
	 * configured with the state of this editing object before passing them to
777
	 * the binding.
778
	 * 
779
	 * <p>
780
	 * The target-to-model and model-to-target update strategies for the binding
781
	 * will be created by the methods {@link #createT2MListStrategy()} and
782
	 * {@link #createM2TListStrategy()}, respectively.
783
	 * </p>
784
	 * 
785
	 * @param dbc
786
	 *            The binding context on which to create the list binding.
787
	 * @param targetObservableList
788
	 *            The target observable list of the binding.
789
	 * @param modelObservableList
790
	 *            The model observable list of the binding.
791
	 * @return The new list binding.
792
	 * 
793
	 * @see #createT2MListStrategy()
794
	 * @see #createM2TListStrategy()
795
	 * @see DataBindingContext#bindList(IObservableList, IObservableList,
796
	 *      UpdateListStrategy, UpdateListStrategy)
797
	 */
798
	public final Binding bindList(DataBindingContext dbc,
799
			IObservableList targetObservableList,
800
			IObservableList modelObservableList) {
801
		return dbc.bindList(targetObservableList, modelObservableList,
802
				createT2MListStrategy(), createM2TListStrategy());
803
	}
804
805
	/**
806
	 * Creates a binding between a target and model observable list on the given
807
	 * binding context by creating new update strategies with the provided
808
	 * update policies which will be both configured with the state of this
809
	 * editing object before passing them to the binding.
810
	 * 
811
	 * @param dbc
812
	 *            The binding context on which to create the list binding.
813
	 * @param targetObservableList
814
	 *            The target observable list of the binding.
815
	 * @param modelObservableList
816
	 *            The model observable list of the binding.
817
	 * @param t2mUpdatePolicy
818
	 *            The update policy for the target-to-model
819
	 *            {@link UpdateListStrategy} which is
820
	 *            {@link #createT2MListStrategy(int) created} and passed to the
821
	 *            new binding.
822
	 * @param m2tUpdatePolicy
823
	 *            The update policy for the model-to-target
824
	 *            {@link UpdateListStrategy} which is
825
	 *            {@link #createM2TListStrategy(int) created} and passed to the
826
	 *            new binding.
827
	 * @return The new list binding.
828
	 * 
829
	 * @see #createT2MListStrategy(int)
830
	 * @see #createM2TListStrategy(int)
831
	 * @see DataBindingContext#bindList(IObservableList, IObservableList,
832
	 *      UpdateListStrategy, UpdateListStrategy)
833
	 */
834
	public final Binding bindList(DataBindingContext dbc,
835
			IObservableList targetObservableList,
836
			IObservableList modelObservableList, int t2mUpdatePolicy,
837
			int m2tUpdatePolicy) {
838
		return dbc.bindList(targetObservableList, modelObservableList,
839
				createT2MListStrategy(t2mUpdatePolicy),
840
				createM2TListStrategy(m2tUpdatePolicy));
841
	}
842
843
	/**
844
	 * Creates a binding between a target and model observable list on the given
845
	 * binding context by using the provided update strategies which will be
846
	 * both configured with the state of this editing object before passing them
847
	 * to the binding.
848
	 * 
849
	 * @param dbc
850
	 *            The binding context on which to create the list binding.
851
	 * @param targetObservableList
852
	 *            The target observable list of the binding.
853
	 * @param modelObservableList
854
	 *            The model observable list of the binding.
855
	 * @param t2mUpdateStrategy
856
	 *            The target-to-model {@link UpdateListStrategy} of the binding
857
	 *            to be {@link #applyToT2MListStrategy(UpdateListStrategy)
858
	 *            configured} with the state of this editing object before
859
	 *            passing it to the binding.
860
	 * @param m2tUpdateStrategy
861
	 *            The model-to-target {@link UpdateListStrategy} of the binding
862
	 *            to be {@link #applyToM2TListStrategy(UpdateListStrategy)
863
	 *            configured} with the state of this editing object before
864
	 *            passing it to the binding.
865
	 * @return The new list binding.
866
	 * 
867
	 * @see #applyToT2MListStrategy(UpdateListStrategy)
868
	 * @see #applyToM2TListStrategy(UpdateListStrategy)
869
	 * @see DataBindingContext#bindList(IObservableList, IObservableList,
870
	 *      UpdateListStrategy, UpdateListStrategy)
871
	 */
872
	public final Binding bindList(DataBindingContext dbc,
873
			IObservableList targetObservableList,
874
			IObservableList modelObservableList,
875
			UpdateListStrategy t2mUpdateStrategy,
876
			UpdateListStrategy m2tUpdateStrategy) {
877
		return dbc.bindList(targetObservableList, modelObservableList,
878
				applyToT2MListStrategy(t2mUpdateStrategy),
879
				applyToM2TListStrategy(m2tUpdateStrategy));
880
	}
881
882
	/**
883
	 * Creates a binding between a target and model observable set on the given
884
	 * binding context by creating new update strategies which will be both
885
	 * configured with the state of this editing object before passing them to
886
	 * the binding.
887
	 * 
888
	 * <p>
889
	 * The target-to-model and model-to-target update strategies for the binding
890
	 * will be created by the methods {@link #createT2MSetStrategy()} and
891
	 * {@link #createM2TSetStrategy()}, respectively.
892
	 * </p>
893
	 * 
894
	 * @param dbc
895
	 *            The binding context on which to create the set binding.
896
	 * @param targetObservableSet
897
	 *            The target observable set of the binding.
898
	 * @param modelObservableSet
899
	 *            The model observable set of the binding.
900
	 * @return The new set binding.
901
	 * 
902
	 * @see #createT2MSetStrategy()
903
	 * @see #createM2TSetStrategy()
904
	 * @see DataBindingContext#bindSet(IObservableSet, IObservableSet,
905
	 *      UpdateSetStrategy, UpdateSetStrategy)
906
	 */
907
	public final Binding bindSet(DataBindingContext dbc,
908
			IObservableSet targetObservableSet,
909
			IObservableSet modelObservableSet) {
910
		return dbc.bindSet(targetObservableSet, modelObservableSet,
911
				createT2MSetStrategy(), createM2TSetStrategy());
912
	}
913
914
	/**
915
	 * Creates a binding between a target and model observable set on the given
916
	 * binding context by creating new update strategies with the provided
917
	 * update policies which will be both configured with the state of this
918
	 * editing object before passing them to the binding.
919
	 * 
920
	 * @param dbc
921
	 *            The binding context on which to create the set binding.
922
	 * @param targetObservableSet
923
	 *            The target observable set of the binding.
924
	 * @param modelObservableSet
925
	 *            The model observable set of the binding.
926
	 * @param t2mUpdatePolicy
927
	 *            The update policy for the target-to-model
928
	 *            {@link UpdateSetStrategy} which is
929
	 *            {@link #createT2MSetStrategy(int) created} and passed to the
930
	 *            new binding.
931
	 * @param m2tUpdatePolicy
932
	 *            The update policy for the model-to-target
933
	 *            {@link UpdateSetStrategy} which is
934
	 *            {@link #createM2TSetStrategy(int) created} and passed to the
935
	 *            new binding.
936
	 * @return The new set binding.
937
	 * 
938
	 * @see #createT2MSetStrategy(int)
939
	 * @see #createM2TSetStrategy(int)
940
	 * @see DataBindingContext#bindSet(IObservableSet, IObservableSet,
941
	 *      UpdateSetStrategy, UpdateSetStrategy)
942
	 */
943
	public final Binding bindSet(DataBindingContext dbc,
944
			IObservableSet targetObservableSet,
945
			IObservableSet modelObservableSet, int t2mUpdatePolicy,
946
			int m2tUpdatePolicy) {
947
		return dbc.bindSet(targetObservableSet, modelObservableSet,
948
				createT2MSetStrategy(t2mUpdatePolicy),
949
				createM2TSetStrategy(m2tUpdatePolicy));
950
	}
951
952
	/**
953
	 * Creates a binding between a target and model observable set on the given
954
	 * binding context by using the provided update strategies which will be
955
	 * both configured with the state of this editing object before passing them
956
	 * to the binding.
957
	 * 
958
	 * @param dbc
959
	 *            The binding context on which to create the set binding.
960
	 * @param targetObservableSet
961
	 *            The target observable set of the binding.
962
	 * @param modelObservableSet
963
	 *            The model observable set of the binding.
964
	 * @param t2mUpdateStrategy
965
	 *            The target-to-model {@link UpdateSetStrategy} of the binding
966
	 *            to be {@link #applyToT2MSetStrategy(UpdateSetStrategy)
967
	 *            configured} with the state of this editing object before
968
	 *            passing it to the binding.
969
	 * @param m2tUpdateStrategy
970
	 *            The model-to-target {@link UpdateSetStrategy} of the binding
971
	 *            to be {@link #applyToM2TSetStrategy(UpdateSetStrategy)
972
	 *            configured} with the state of this editing object before
973
	 *            passing it to the binding.
974
	 * @return The new set binding.
975
	 * 
976
	 * @see #applyToT2MSetStrategy(UpdateSetStrategy)
977
	 * @see #applyToM2TSetStrategy(UpdateSetStrategy)
978
	 * @see DataBindingContext#bindSet(IObservableSet, IObservableSet,
979
	 *      UpdateSetStrategy, UpdateSetStrategy)
980
	 */
981
	public final Binding bindSet(DataBindingContext dbc,
982
			IObservableSet targetObservableSet,
983
			IObservableSet modelObservableSet,
984
			UpdateSetStrategy t2mUpdateStrategy,
985
			UpdateSetStrategy m2tUpdateStrategy) {
986
		return dbc.bindSet(targetObservableSet, modelObservableSet,
987
				applyToT2MSetStrategy(t2mUpdateStrategy),
988
				applyToM2TSetStrategy(m2tUpdateStrategy));
989
	}
990
991
	private static IValidator createValidator(Constraints constraints) {
992
		return constraints != null ? constraints.createValidator() : null;
993
	}
994
995
	private static boolean applyValidator(IValidator validator, Object value,
996
			MultiStatus aggregateStatus) {
997
		if (validator != null) {
998
			IStatus validationStatus = validator.validate(value);
999
			if (!validationStatus.isOK()) {
1000
				aggregateStatus.merge(validationStatus);
1001
			}
1002
			return isValid(validationStatus);
1003
		}
1004
		return true;
1005
	}
1006
1007
	private static boolean isValid(IStatus status) {
1008
		return status.isOK() || status.matches(IStatus.INFO | IStatus.WARNING);
1009
	}
1010
}
(-)src/org/eclipse/core/databinding/validation/constraint/IntegerConstraints.java (+306 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
 * @since 1.4
21
 */
22
public final class IntegerConstraints extends Constraints {
23
24
	private NumberFormat displayFormat = NumberFormat.getIntegerInstance();
25
26
	private String requiredMessage = null;
27
28
	private String greaterMessage = null;
29
30
	private String greaterEqualMessage = null;
31
32
	private String lessMessage = null;
33
34
	private String lessEqualMessage = null;
35
36
	private String rangeMessage = null;
37
38
	private String positiveMessage = null;
39
40
	private String nonNegativeMessage = null;
41
42
	/**
43
	 * Sets the format to use when formatting an integer to be included in any
44
	 * of the validation messages.
45
	 * 
46
	 * <p>
47
	 * This integer format will be used for any subsequent constraints which are
48
	 * applied.
49
	 * </p>
50
	 * 
51
	 * @param format
52
	 *            The format to use for displaying integers in validation
53
	 *            messages.
54
	 * @return This constraints instance for method chaining.
55
	 */
56
	public IntegerConstraints displayFormat(NumberFormat format) {
57
		this.displayFormat = format;
58
		return this;
59
	}
60
61
	/**
62
	 * Adds a validator ensuring that the parsed integer is not
63
	 * <code>null</code>. Uses the current {@link #requiredMessage(String)
64
	 * validation message}.
65
	 * 
66
	 * @return This constraints instance for method chaining.
67
	 */
68
	public IntegerConstraints required() {
69
		addValidator(new NonNullValidator(requiredMessage));
70
		return this;
71
	}
72
73
	/**
74
	 * Sets the validation message for the {@link #required()} constraint.
75
	 * 
76
	 * @param message
77
	 *            The validation message for the {@link #required()} constraint.
78
	 * @return This constraints instance for method chaining.
79
	 * 
80
	 * @see #required()
81
	 */
82
	public IntegerConstraints requiredMessage(String message) {
83
		this.requiredMessage = message;
84
		return this;
85
	}
86
87
	/**
88
	 * Adds a validator ensuring that the parsed integer is greater than the
89
	 * given number. Uses the current {@link #greaterMessage(String) validation
90
	 * message}.
91
	 * 
92
	 * @param number
93
	 *            The number which the parsed integer must be greater than.
94
	 * @return This constraints instance for method chaining.
95
	 */
96
	public IntegerConstraints greater(int number) {
97
		addValidator(IntegerRangeValidator.greater(number, greaterMessage,
98
				displayFormat));
99
		return this;
100
	}
101
102
	/**
103
	 * Sets the validation message pattern for the {@link #greater(int)}
104
	 * constraint.
105
	 * 
106
	 * @param message
107
	 *            The validation message pattern for the {@link #greater(int)}
108
	 *            constraint. Can be parameterized with the number which the
109
	 *            parsed integer must be greater than.
110
	 * @return This constraints instance for method chaining.
111
	 * 
112
	 * @see #greater(int)
113
	 */
114
	public IntegerConstraints greaterMessage(String message) {
115
		this.greaterMessage = message;
116
		return this;
117
	}
118
119
	/**
120
	 * Adds a validator ensuring that the parsed integer is greater than or
121
	 * equal to the given number. Uses the current
122
	 * {@link #greaterEqualMessage(String) validation message}.
123
	 * 
124
	 * @param number
125
	 *            The number which the parsed integer must be greater than or
126
	 *            equal to.
127
	 * @return This constraints instance for method chaining.
128
	 */
129
	public IntegerConstraints greaterEqual(int number) {
130
		addValidator(IntegerRangeValidator.greaterEqual(number,
131
				greaterEqualMessage, displayFormat));
132
		return this;
133
	}
134
135
	/**
136
	 * Sets the validation message pattern for the {@link #greaterEqual(int)}
137
	 * constraint.
138
	 * 
139
	 * @param message
140
	 *            The validation message pattern for the
141
	 *            {@link #greaterEqual(int)} constraint. Can be parameterized
142
	 *            with the number which the parsed integer must be greater than
143
	 *            or equal to.
144
	 * @return This constraints instance for method chaining.
145
	 * 
146
	 * @see #greaterEqual(int)
147
	 */
148
	public IntegerConstraints greaterEqualMessage(String message) {
149
		this.greaterEqualMessage = message;
150
		return this;
151
	}
152
153
	/**
154
	 * Adds a validator ensuring that the parsed integer is less than the given
155
	 * number. Uses the current {@link #lessMessage(String) validation message}.
156
	 * 
157
	 * @param number
158
	 *            The number which the parsed integer must be less than.
159
	 * @return This constraints instance for method chaining.
160
	 */
161
	public IntegerConstraints less(int number) {
162
		addValidator(IntegerRangeValidator.less(number, lessMessage,
163
				displayFormat));
164
		return this;
165
	}
166
167
	/**
168
	 * Sets the validation message pattern for the {@link #less(int)}
169
	 * constraint.
170
	 * 
171
	 * @param message
172
	 *            The validation message pattern for the {@link #less(int)}
173
	 *            constraint. Can be parameterized with the number which the
174
	 *            parsed integer must be less than.
175
	 * @return This constraints instance for method chaining.
176
	 * 
177
	 * @see #less(int)
178
	 */
179
	public IntegerConstraints lessMessage(String message) {
180
		this.lessMessage = message;
181
		return this;
182
	}
183
184
	/**
185
	 * Adds a validator ensuring that the parsed integer is less than or equal
186
	 * to the given number. Uses the current {@link #lessEqualMessage(String)
187
	 * validation message}.
188
	 * 
189
	 * @param number
190
	 *            The number which the parsed integer must be less than or equal
191
	 *            to.
192
	 * @return This constraints instance for method chaining.
193
	 */
194
	public IntegerConstraints lessEqual(int number) {
195
		addValidator(IntegerRangeValidator.greaterEqual(number,
196
				lessEqualMessage, displayFormat));
197
		return this;
198
	}
199
200
	/**
201
	 * Sets the validation message pattern for the {@link #lessEqual(int)}
202
	 * constraint.
203
	 * 
204
	 * @param message
205
	 *            The validation message pattern for the {@link #lessEqual(int)}
206
	 *            constraint. Can be parameterized with the number which the
207
	 *            parsed integer must be less than or equal to.
208
	 * @return This constraints instance for method chaining.
209
	 * 
210
	 * @see #lessEqual(int)
211
	 */
212
	public IntegerConstraints lessEqualMessage(String message) {
213
		this.lessEqualMessage = message;
214
		return this;
215
	}
216
217
	/**
218
	 * Adds a validator ensuring that the parsed integer is within the given
219
	 * range. Uses the current {@link #rangeMessage(String) validation message}.
220
	 * 
221
	 * @param min
222
	 *            The lower bound of the range (inclusive).
223
	 * @param max
224
	 *            The upper bound of the range (inclusive).
225
	 * @return This constraints instance for method chaining.
226
	 */
227
	public IntegerConstraints range(int min, int max) {
228
		addValidator(IntegerRangeValidator.range(min, max, rangeMessage,
229
				displayFormat));
230
		return this;
231
	}
232
233
	/**
234
	 * Sets the validation message pattern for the {@link #range(int, int)}
235
	 * constraint.
236
	 * 
237
	 * @param message
238
	 *            The validation message pattern for the
239
	 *            {@link #range(int, int)} constraint. Can be parameterized with
240
	 *            the min and max values of the range in which the parsed
241
	 *            integer must lie.
242
	 * @return This constraints instance for method chaining.
243
	 * 
244
	 * @see #range(int, int)
245
	 */
246
	public IntegerConstraints rangeMessage(String message) {
247
		this.rangeMessage = message;
248
		return this;
249
	}
250
251
	/**
252
	 * Adds a validator ensuring that the parsed integer is positive. Uses the
253
	 * current {@link #positiveMessage(String) validation message}.
254
	 * 
255
	 * @return This constraints instance for method chaining.
256
	 */
257
	public IntegerConstraints positive() {
258
		addValidator(IntegerRangeValidator.positive(positiveMessage,
259
				displayFormat));
260
		return this;
261
	}
262
263
	/**
264
	 * Sets the validation message pattern for the {@link #positive()}
265
	 * constraint.
266
	 * 
267
	 * @param message
268
	 *            The validation message pattern for the {@link #positive()}
269
	 *            constraint.
270
	 * @return This constraints instance for method chaining.
271
	 * 
272
	 * @see #positive()
273
	 */
274
	public IntegerConstraints positiveMessage(String message) {
275
		this.positiveMessage = message;
276
		return this;
277
	}
278
279
	/**
280
	 * Adds a validator ensuring that the parsed integer is non-negative. Uses
281
	 * the current {@link #nonNegativeMessage(String) validation message}.
282
	 * 
283
	 * @return This constraints instance for method chaining.
284
	 */
285
	public IntegerConstraints nonNegative() {
286
		addValidator(IntegerRangeValidator.nonNegative(nonNegativeMessage,
287
				displayFormat));
288
		return this;
289
	}
290
291
	/**
292
	 * Sets the validation message pattern for the {@link #nonNegative()}
293
	 * constraint.
294
	 * 
295
	 * @param message
296
	 *            The validation message pattern for the {@link #nonNegative()}
297
	 *            constraint.
298
	 * @return This constraints instance for method chaining.
299
	 * 
300
	 * @see #nonNegative()
301
	 */
302
	public IntegerConstraints nonNegativeMessage(String message) {
303
		this.nonNegativeMessage = message;
304
		return this;
305
	}
306
}
(-)src/org/eclipse/core/databinding/editing/IntegerEditing.java (+320 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.StringToIntegerValidator;
20
21
import com.ibm.icu.text.NumberFormat;
22
23
/**
24
 * @since 1.4
25
 */
26
public final class IntegerEditing extends Editing {
27
28
	private final NumberFormat displayFormat;
29
30
	private IntegerEditing(NumberFormat format, String parseErrorMessage,
31
			String outOfRangeMessage) {
32
		this.displayFormat = format;
33
34
		StringToNumberConverter targetConverter = StringToNumberConverter
35
				.toInteger(format, false);
36
		NumberToStringConverter modelConverter = NumberToStringConverter
37
				.fromInteger(format, false);
38
39
		StringToIntegerValidator targetValidator = new StringToIntegerValidator(
40
				targetConverter);
41
		if (parseErrorMessage != null) {
42
			targetValidator.setParseErrorMessage(parseErrorMessage);
43
		}
44
		if (outOfRangeMessage != null) {
45
			targetValidator.setOutOfRangeMessage(outOfRangeMessage);
46
		}
47
48
		targetConstraints().addValidator(targetValidator);
49
		setTargetConverter(targetConverter);
50
		setModelConverter(modelConverter);
51
	}
52
53
	/**
54
	 * Creates a new editing object which defaults the validations and
55
	 * conversions used for editing based on the platform's locale. Uses the
56
	 * default validation messages.
57
	 * 
58
	 * @return The new editing object using the default validations and
59
	 *         conversions for editing.
60
	 * 
61
	 * @see NumberFormat#getIntegerInstance()
62
	 */
63
	public static IntegerEditing withDefaults() {
64
		return withDefaults(null, null);
65
	}
66
67
	/**
68
	 * Creates a new editing object which defaults the validations and
69
	 * conversions used for editing based on the platform's locale. Uses the
70
	 * specified custom validation messages.
71
	 * 
72
	 * @param parseErrorMessage
73
	 *            The validation message issued in case the input string cannot
74
	 *            be parsed to an integer.
75
	 * @param outOfRangeMessage
76
	 *            The validation message issued in case the input string
77
	 *            represents an integer whose value is out of range. Can be
78
	 *            parameterized by the <code>Integer.MIN_VALUE</code> and
79
	 *            <code>Integer.MAX_VALUE</code> values.
80
	 * @return The new editing object using the default validations and
81
	 *         conversions for editing.
82
	 * 
83
	 * @see NumberFormat#getIntegerInstance()
84
	 */
85
	public static IntegerEditing withDefaults(String parseErrorMessage,
86
			String outOfRangeMessage) {
87
		return new IntegerEditing(NumberFormat.getIntegerInstance(),
88
				parseErrorMessage, outOfRangeMessage);
89
	}
90
91
	/**
92
	 * Creates a new editing object whose validations and conversions used for
93
	 * editing are based on the given integer format. Uses the default
94
	 * validation messages.
95
	 * 
96
	 * @param format
97
	 *            The integer format defining the validations and conversions
98
	 *            used for editing.
99
	 * @return The new editing object configured by the given integer format.
100
	 */
101
	public static IntegerEditing forFormat(NumberFormat format) {
102
		return forFormat(format, null, null);
103
	}
104
105
	/**
106
	 * Creates a new editing object whose validations and conversions used for
107
	 * editing are based on the given integer format. Uses the specified custom
108
	 * validation messages.
109
	 * 
110
	 * @param format
111
	 *            The integer format defining the validations and conversions
112
	 *            used for editing.
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>Integer.MIN_VALUE</code> and
120
	 *            <code>Integer.MAX_VALUE</code> values.
121
	 * @return The new editing object configured by the given integer format.
122
	 */
123
	public static IntegerEditing forFormat(NumberFormat format,
124
			String parseErrorMessage, String outOfRangeMessage) {
125
		return new IntegerEditing(format, parseErrorMessage, outOfRangeMessage);
126
	}
127
128
	/**
129
	 * Returns the target constraints to apply.
130
	 * 
131
	 * <p>
132
	 * This method provides a typesafe access to the {@link StringConstraints
133
	 * string target constraints} of this editing object and is equivalent to
134
	 * {@code (StringConstraints) targetConstraints()}.
135
	 * </p>
136
	 * 
137
	 * @return The target constraints to apply.
138
	 * 
139
	 * @see #targetConstraints()
140
	 * @see StringConstraints
141
	 */
142
	public StringConstraints targetStringConstraints() {
143
		return (StringConstraints) targetConstraints();
144
	}
145
146
	/**
147
	 * Returns the model constraints to apply.
148
	 * 
149
	 * <p>
150
	 * This method provides a typesafe access to the {@link IntegerConstraints
151
	 * integer model constraints} of this editing object and is equivalent to
152
	 * {@code (IntegerConstraints) modelConstraints()}.
153
	 * </p>
154
	 * 
155
	 * @return The target constraints to apply.
156
	 * 
157
	 * @see #modelConstraints()
158
	 * @see IntegerConstraints
159
	 */
160
	public IntegerConstraints modelIntegerConstraints() {
161
		return (IntegerConstraints) modelConstraints();
162
	}
163
164
	/**
165
	 * Returns the before-set model constraints to apply.
166
	 * 
167
	 * <p>
168
	 * This method provides a typesafe access to the {@link IntegerConstraints
169
	 * integer before-set model constraints} of this editing object and is
170
	 * equivalent to {@code (IntegerConstraints) beforeSetModelConstraints()}.
171
	 * </p>
172
	 * 
173
	 * @return The target constraints to apply.
174
	 * 
175
	 * @see #beforeSetModelConstraints()
176
	 * @see IntegerConstraints
177
	 */
178
	public IntegerConstraints beforeSetModelIntegerConstraints() {
179
		return (IntegerConstraints) beforeSetModelConstraints();
180
	}
181
182
	protected Constraints createTargetConstraints() {
183
		return new StringConstraints();
184
	}
185
186
	protected Constraints createModelConstraints() {
187
		return new IntegerConstraints().displayFormat(displayFormat);
188
	}
189
190
	protected Constraints createBeforeSetModelConstraints() {
191
		return new IntegerConstraints().displayFormat(displayFormat);
192
	}
193
194
	/**
195
	 * Convenience method which adds a {@link IntegerConstraints#required()
196
	 * required constraint} to the set of {@link #modelIntegerConstraints()}.
197
	 * 
198
	 * @return This editing instance for method chaining.
199
	 * 
200
	 * @see IntegerConstraints#required()
201
	 * @see #modelIntegerConstraints()
202
	 */
203
	public IntegerEditing required() {
204
		modelIntegerConstraints().required();
205
		return this;
206
	}
207
208
	/**
209
	 * Convenience method which adds a {@link IntegerConstraints#greater(int)
210
	 * greater constraint} to the set of {@link #modelIntegerConstraints()}.
211
	 * 
212
	 * @param number
213
	 *            The number of the greater constraint.
214
	 * @return This editing instance for method chaining.
215
	 * 
216
	 * @see IntegerConstraints#greater(int)
217
	 * @see #modelIntegerConstraints()
218
	 */
219
	public IntegerEditing greater(int number) {
220
		modelIntegerConstraints().greater(number);
221
		return this;
222
	}
223
224
	/**
225
	 * Convenience method which adds a
226
	 * {@link IntegerConstraints#greaterEqual(int) greater-equal constraint} to
227
	 * the set of {@link #modelIntegerConstraints()}.
228
	 * 
229
	 * @param number
230
	 *            The number of the greater-equal constraint.
231
	 * @return This editing instance for method chaining.
232
	 * 
233
	 * @see IntegerConstraints#greaterEqual(int)
234
	 * @see #modelIntegerConstraints()
235
	 */
236
	public IntegerEditing greaterEqual(int number) {
237
		modelIntegerConstraints().greaterEqual(number);
238
		return this;
239
	}
240
241
	/**
242
	 * Convenience method which adds a {@link IntegerConstraints#less(int) less
243
	 * constraint} to the set of {@link #modelIntegerConstraints()}.
244
	 * 
245
	 * @param number
246
	 *            The number of the less constraint.
247
	 * @return This editing instance for method chaining.
248
	 * 
249
	 * @see IntegerConstraints#less(int)
250
	 * @see #modelIntegerConstraints()
251
	 */
252
	public IntegerEditing less(int number) {
253
		modelIntegerConstraints().less(number);
254
		return this;
255
	}
256
257
	/**
258
	 * Convenience method which adds a {@link IntegerConstraints#lessEqual(int)
259
	 * less-equal constraint} to the set of {@link #modelIntegerConstraints()}.
260
	 * 
261
	 * @param number
262
	 *            The number of the less-equal constraint.
263
	 * @return This editing instance for method chaining.
264
	 * 
265
	 * @see IntegerConstraints#lessEqual(int)
266
	 * @see #modelIntegerConstraints()
267
	 */
268
	public IntegerEditing lessEqual(int number) {
269
		modelIntegerConstraints().lessEqual(number);
270
		return this;
271
	}
272
273
	/**
274
	 * Convenience method which adds a
275
	 * {@link IntegerConstraints#range(int, int) range constraint} to the set of
276
	 * {@link #modelIntegerConstraints()}.
277
	 * 
278
	 * @param min
279
	 *            The min number of the range constraint.
280
	 * @param max
281
	 *            The max number of the range constraint.
282
	 * @return This editing instance for method chaining.
283
	 * 
284
	 * @see IntegerConstraints#range(int, int)
285
	 * @see #modelIntegerConstraints()
286
	 */
287
	public IntegerEditing range(int min, int max) {
288
		modelIntegerConstraints().range(min, max);
289
		return this;
290
	}
291
292
	/**
293
	 * Convenience method which adds a {@link IntegerConstraints#positive()
294
	 * positive constraint} to the set of {@link #modelIntegerConstraints()}.
295
	 * 
296
	 * @return This editing instance for method chaining.
297
	 * 
298
	 * @see IntegerConstraints#positive()
299
	 * @see #modelIntegerConstraints()
300
	 */
301
	public IntegerEditing positive() {
302
		modelIntegerConstraints().positive();
303
		return this;
304
	}
305
306
	/**
307
	 * Convenience method which adds a {@link IntegerConstraints#nonNegative()
308
	 * non-negative constraint} to the set of {@link #modelIntegerConstraints()}
309
	 * .
310
	 * 
311
	 * @return This editing instance for method chaining.
312
	 * 
313
	 * @see IntegerConstraints#nonNegative()
314
	 * @see #modelIntegerConstraints()
315
	 */
316
	public IntegerEditing nonNegative() {
317
		modelIntegerConstraints().nonNegative();
318
		return this;
319
	}
320
}
(-)src/org/eclipse/core/databinding/editing/DateEditing.java (+279 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.util.Date;
15
16
import org.eclipse.core.databinding.validation.constraint.Constraints;
17
import org.eclipse.core.databinding.validation.constraint.DateConstraints;
18
import org.eclipse.core.databinding.validation.constraint.StringConstraints;
19
import org.eclipse.core.internal.databinding.conversion.DateToStringConverter;
20
import org.eclipse.core.internal.databinding.conversion.StringToDateConverter;
21
import org.eclipse.core.internal.databinding.validation.StringToDateValidator;
22
23
import com.ibm.icu.text.DateFormat;
24
25
/**
26
 * @since 1.4
27
 */
28
public final class DateEditing extends Editing {
29
30
	private final DateFormat displayFormat;
31
32
	private DateEditing(DateFormat[] inputFormats, String parseErrorMessage,
33
			DateFormat displayFormat) {
34
		this.displayFormat = displayFormat;
35
36
		StringToDateConverter targetConverter = new StringToDateConverter();
37
		if (inputFormats != null) {
38
			targetConverter.setFormatters(inputFormats);
39
		}
40
41
		DateToStringConverter modelConverter = new DateToStringConverter();
42
		if (displayFormat != null) {
43
			modelConverter.setFormatters(new DateFormat[] { displayFormat });
44
		}
45
46
		StringToDateValidator targetValidator = new StringToDateValidator(
47
				targetConverter);
48
		if (parseErrorMessage != null) {
49
			targetValidator.setParseErrorMessage(parseErrorMessage);
50
		}
51
52
		setTargetConverter(targetConverter);
53
		setModelConverter(modelConverter);
54
		targetConstraints().addValidator(targetValidator);
55
	}
56
57
	/**
58
	 * Creates a new editing object which defaults the validations and
59
	 * conversions used for editing. Uses the default validation message.
60
	 * 
61
	 * @return The new editing object using the default validations and
62
	 *         conversions for editing.
63
	 */
64
	public static DateEditing withDefaults() {
65
		return withDefaults(null);
66
	}
67
68
	/**
69
	 * Creates a new editing object which defaults the validations and
70
	 * conversions used for editing. Uses the specified custom validation
71
	 * message.
72
	 * 
73
	 * @param parseErrorMessage
74
	 *            The validation message issued in case the input string cannot
75
	 *            be parsed to a date.
76
	 * @return The new editing object using the default validations and
77
	 *         conversions for editing.
78
	 */
79
	public static DateEditing withDefaults(String parseErrorMessage) {
80
		return new DateEditing(null, parseErrorMessage, null);
81
	}
82
83
	/**
84
	 * Creates a new editing object which supports all the given date input
85
	 * formats and which uses the specified format for displaying a date. Uses
86
	 * the default validation message.
87
	 * 
88
	 * @param inputFormats
89
	 *            The date formats supported for reading in dates.
90
	 * @param displayFormat
91
	 *            The date format for displaying dates.
92
	 * @return The new editing object configured by the given date formats.
93
	 */
94
	public static DateEditing forFormats(DateFormat[] inputFormats,
95
			DateFormat displayFormat) {
96
		return new DateEditing(inputFormats, null, displayFormat);
97
	}
98
99
	/**
100
	 * Creates a new editing object which supports all the given date input
101
	 * formats and which uses the specified format for displaying a date. Uses
102
	 * the specified custom validation message.
103
	 * 
104
	 * @param inputFormats
105
	 *            The date formats supported for reading in dates.
106
	 * @param parseErrorMessage
107
	 *            The validation message issued in case the input string cannot
108
	 *            be parsed to a date.
109
	 * @param displayFormat
110
	 *            The date format for displaying dates.
111
	 * @return The new editing object configured by the given date formats.
112
	 */
113
	public static DateEditing forFormats(DateFormat[] inputFormats,
114
			String parseErrorMessage, DateFormat displayFormat) {
115
		return new DateEditing(inputFormats, parseErrorMessage, displayFormat);
116
	}
117
118
	/**
119
	 * Returns the target constraints to apply.
120
	 * 
121
	 * <p>
122
	 * This method provides a typesafe access to the {@link StringConstraints
123
	 * string target constraints} of this editing object and is equivalent to
124
	 * {@code (StringConstraints) targetConstraints()}.
125
	 * </p>
126
	 * 
127
	 * @return The target constraints to apply.
128
	 * 
129
	 * @see #targetConstraints()
130
	 * @see StringConstraints
131
	 */
132
	public StringConstraints targetStringConstraints() {
133
		return (StringConstraints) targetConstraints();
134
	}
135
136
	/**
137
	 * Returns the model constraints to apply.
138
	 * 
139
	 * <p>
140
	 * This method provides a typesafe access to the {@link DateConstraints date
141
	 * model constraints} of this editing object and is equivalent to {@code
142
	 * (DateConstraints) modelConstraints()}.
143
	 * </p>
144
	 * 
145
	 * @return The target constraints to apply.
146
	 * 
147
	 * @see #modelConstraints()
148
	 * @see DateConstraints
149
	 */
150
	public DateConstraints modelDateConstraints() {
151
		return (DateConstraints) modelConstraints();
152
	}
153
154
	/**
155
	 * Returns the before-set model constraints to apply.
156
	 * 
157
	 * <p>
158
	 * This method provides a typesafe access to the {@link DateConstraints date
159
	 * before-set model constraints} of this editing object and is equivalent to
160
	 * {@code (DateConstraints) beforeSetModelConstraints()}.
161
	 * </p>
162
	 * 
163
	 * @return The target constraints to apply.
164
	 * 
165
	 * @see #beforeSetModelConstraints()
166
	 * @see DateConstraints
167
	 */
168
	public DateConstraints beforeSetModelDateConstraints() {
169
		return (DateConstraints) beforeSetModelConstraints();
170
	}
171
172
	protected Constraints createTargetConstraints() {
173
		return new StringConstraints();
174
	}
175
176
	protected Constraints createModelConstraints() {
177
		return new DateConstraints().displayFormat(displayFormat);
178
	}
179
180
	protected Constraints createBeforeSetModelConstraints() {
181
		return new DateConstraints().displayFormat(displayFormat);
182
	}
183
184
	/**
185
	 * Convenience method which adds a {@link DateConstraints#required()
186
	 * required constraint} to the set of {@link #modelDateConstraints()}.
187
	 * 
188
	 * @return This editing instance for method chaining.
189
	 * 
190
	 * @see DateConstraints#required()
191
	 * @see #modelDateConstraints()
192
	 */
193
	public DateEditing required() {
194
		modelDateConstraints().required();
195
		return this;
196
	}
197
198
	/**
199
	 * Convenience method which adds a {@link DateConstraints#after(Date) after
200
	 * constraint} to the set of {@link #modelDateConstraints()}.
201
	 * 
202
	 * @param date
203
	 *            The date of the after constraint.
204
	 * @return This editing instance for method chaining.
205
	 * 
206
	 * @see DateConstraints#after(Date)
207
	 * @see #modelDateConstraints()
208
	 */
209
	public DateEditing after(Date date) {
210
		modelDateConstraints().after(date);
211
		return this;
212
	}
213
214
	/**
215
	 * Convenience method which adds a {@link DateConstraints#afterEqual(Date)
216
	 * after-equal constraint} to the set of {@link #modelDateConstraints()}.
217
	 * 
218
	 * @param date
219
	 *            The date of the after-equal constraint.
220
	 * @return This editing instance for method chaining.
221
	 * 
222
	 * @see DateConstraints#afterEqual(Date)
223
	 * @see #modelDateConstraints()
224
	 */
225
	public DateEditing afterEqual(Date date) {
226
		modelDateConstraints().afterEqual(date);
227
		return this;
228
	}
229
230
	/**
231
	 * Convenience method which adds a {@link DateConstraints#before(Date)
232
	 * before constraint} to the set of {@link #modelDateConstraints()}.
233
	 * 
234
	 * @param date
235
	 *            The date of the before constraint.
236
	 * @return This editing instance for method chaining.
237
	 * 
238
	 * @see DateConstraints#before(Date)
239
	 * @see #modelDateConstraints()
240
	 */
241
	public DateEditing before(Date date) {
242
		modelDateConstraints().before(date);
243
		return this;
244
	}
245
246
	/**
247
	 * Convenience method which adds a {@link DateConstraints#beforeEqual(Date)
248
	 * after-equal constraint} to the set of {@link #modelDateConstraints()}.
249
	 * 
250
	 * @param date
251
	 *            The date of the after-equal constraint.
252
	 * @return This editing instance for method chaining.
253
	 * 
254
	 * @see DateConstraints#afterEqual(Date)
255
	 * @see #modelDateConstraints()
256
	 */
257
	public DateEditing beforeEqual(Date date) {
258
		modelDateConstraints().beforeEqual(date);
259
		return this;
260
	}
261
262
	/**
263
	 * Convenience method which adds a {@link DateConstraints#range(Date, Date)
264
	 * range constraint} to the set of {@link #modelDateConstraints()}.
265
	 * 
266
	 * @param minDate
267
	 *            The min date of the range constraint.
268
	 * @param maxDate
269
	 *            The max date of the range constraint.
270
	 * @return This editing instance for method chaining.
271
	 * 
272
	 * @see DateConstraints#range(Date, Date)
273
	 * @see #modelDateConstraints()
274
	 */
275
	public DateEditing range(Date minDate, Date maxDate) {
276
		modelDateConstraints().range(minDate, maxDate);
277
		return this;
278
	}
279
}
(-)src/org/eclipse/core/internal/databinding/validation/NonEmptyStringValidator.java (+50 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.4
21
 */
22
public class NonEmptyStringValidator implements IValidator {
23
24
	private static final String NON_EMPTY_STRING_VALIDATION_MESSAGE = BindingMessages.getString(BindingMessages.VALIDATE_NON_EMPTY_STRING);
25
26
	private final String validationMessage;
27
28
	/**
29
	 * 
30
	 */
31
	public NonEmptyStringValidator() {
32
		this(null);
33
	}
34
35
	/**
36
	 * @param validationMessage
37
	 */
38
	public NonEmptyStringValidator(String validationMessage) {
39
		this.validationMessage = validationMessage != null ? validationMessage
40
				: NON_EMPTY_STRING_VALIDATION_MESSAGE;
41
	}
42
43
	public IStatus validate(Object value) {
44
		String input = (String) value;
45
		if ("".equals(input)) { //$NON-NLS-1$
46
			return ValidationStatus.error(validationMessage);
47
		}
48
		return ValidationStatus.ok();
49
	}
50
}
(-)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.4
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 >= 0
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
}
(-)src/org/eclipse/core/internal/databinding/validation/StringRegexValidator.java (+70 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.4
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 = Pattern.compile(regex);
48
		this.validationMessage = validationMessage != null ? validationMessage
49
				: REGEX_VALIDATION_MESSAGE;
50
	}
51
52
	public IStatus validate(Object value) {
53
		String input = (String) value;
54
		if (input != null) {
55
			Matcher matcher = pattern.matcher(input);
56
			if (!matcher.matches()) {
57
				return ValidationStatus.error(getFormattedValidationMessage());
58
			}
59
		}
60
		return ValidationStatus.ok();
61
	}
62
63
	private String getFormattedValidationMessage() {
64
		if (formattedValidationMessage == null) {
65
			formattedValidationMessage = MessageFormat.format(
66
					validationMessage, new String[] { pattern.pattern() });
67
		}
68
		return formattedValidationMessage;
69
	}
70
}
(-).settings/org.eclipse.jdt.ui.prefs (-2 / +2 lines)
Lines 1-4 Link Here
1
#Tue Feb 10 16:06:02 MST 2009
1
#Mon Sep 21 22:46:54 CEST 2009
2
cleanup.add_default_serial_version_id=true
2
cleanup.add_default_serial_version_id=true
3
cleanup.add_generated_serial_version_id=false
3
cleanup.add_generated_serial_version_id=false
4
cleanup.add_missing_annotations=true
4
cleanup.add_missing_annotations=true
Lines 78-84 Link Here
78
sp_cleanup.always_use_this_for_non_static_method_access=false
78
sp_cleanup.always_use_this_for_non_static_method_access=false
79
sp_cleanup.convert_to_enhanced_for_loop=false
79
sp_cleanup.convert_to_enhanced_for_loop=false
80
sp_cleanup.correct_indentation=false
80
sp_cleanup.correct_indentation=false
81
sp_cleanup.format_source_code=true
81
sp_cleanup.format_source_code=false
82
sp_cleanup.format_source_code_changes_only=false
82
sp_cleanup.format_source_code_changes_only=false
83
sp_cleanup.make_local_variable_final=false
83
sp_cleanup.make_local_variable_final=false
84
sp_cleanup.make_parameters_final=false
84
sp_cleanup.make_parameters_final=false
(-)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 (+224 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.Editing;
22
import org.eclipse.core.databinding.editing.IntegerEditing;
23
import org.eclipse.core.databinding.observable.Realm;
24
import org.eclipse.core.databinding.observable.list.WritableList;
25
import org.eclipse.core.databinding.observable.value.IObservableValue;
26
import org.eclipse.core.databinding.observable.value.WritableValue;
27
import org.eclipse.core.runtime.IStatus;
28
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
29
import org.eclipse.jface.databinding.swt.SWTObservables;
30
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
31
import org.eclipse.jface.examples.databinding.util.EditingFactory;
32
import org.eclipse.jface.internal.databinding.provisional.fieldassist.ControlDecorationSupport;
33
import org.eclipse.jface.layout.GridDataFactory;
34
import org.eclipse.jface.layout.GridLayoutFactory;
35
import org.eclipse.jface.viewers.LabelProvider;
36
import org.eclipse.jface.viewers.ListViewer;
37
import org.eclipse.swt.SWT;
38
import org.eclipse.swt.events.FocusAdapter;
39
import org.eclipse.swt.events.FocusEvent;
40
import org.eclipse.swt.events.SelectionAdapter;
41
import org.eclipse.swt.events.SelectionEvent;
42
import org.eclipse.swt.layout.GridLayout;
43
import org.eclipse.swt.widgets.Composite;
44
import org.eclipse.swt.widgets.Control;
45
import org.eclipse.swt.widgets.Display;
46
import org.eclipse.swt.widgets.Group;
47
import org.eclipse.swt.widgets.Label;
48
import org.eclipse.swt.widgets.Shell;
49
import org.eclipse.swt.widgets.Text;
50
51
public class Snippet035Editing {
52
53
	private DataBindingContext dbc;
54
55
	public static void main(String[] args) {
56
		Display display = new Display();
57
58
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
59
			public void run() {
60
				Shell shell = new Snippet035Editing().createShell();
61
				Display display = Display.getCurrent();
62
				while (!shell.isDisposed()) {
63
					if (!display.readAndDispatch()) {
64
						display.sleep();
65
					}
66
				}
67
			}
68
		});
69
	}
70
71
	private Shell createShell() {
72
		Display display = Display.getCurrent();
73
		Shell shell = new Shell(display);
74
		shell.setText("Editing");
75
		shell.setLayout(new GridLayout(1, false));
76
77
		dbc = new DataBindingContext();
78
79
		createValueSection(shell);
80
		createListSection(shell);
81
82
		shell.pack();
83
		shell.open();
84
85
		return shell;
86
	}
87
88
	private void createValueSection(Composite parent) {
89
		Group section = createSectionGroup(parent, "Value bindings", false);
90
91
		// Edit an e-mail address.
92
		Text emailText = createTextField(section, "E-Mail*");
93
		Editing emailEditing = EditingFactory.forEmailString().required();
94
		bindTextField(emailText, new WritableValue(), emailEditing);
95
96
		// Edit a required, positive integer using the default validation message.
97
		Text positiveText = createTextField(section, "Positive value*");
98
		IntegerEditing positiveEditing = EditingFactory.forInteger().required().positive();
99
		bindTextField(positiveText, new WritableValue(), positiveEditing);
100
101
		// Edit an integer within the range [1, 100] using the default
102
		// validation message.
103
		Text rangeText = createTextField(section, "Value in [1, 100]");
104
		IntegerEditing rangeEditing = EditingFactory.forInteger().range(1, 100);
105
		bindTextField(rangeText, new WritableValue(new Integer(0), null), rangeEditing);
106
107
		// Edit a percentage value which must lie within [0, 100] using a custom
108
		// validation message which indicates that the value actually represents
109
		// a percentage value.
110
		Text percentText = createTextField(section, "Value [%]");
111
		IntegerEditing percentEditing = EditingFactory.forInteger();
112
		percentEditing.modelIntegerConstraints()
113
			.rangeMessage("Please specify a percentage value within [{0}, {1}].")
114
			.range(0, 100);
115
		bindTextField(percentText, new WritableValue(new Integer(-1), null), percentEditing);
116
117
		// Edit a hex integer within the range [0x00, 0xff]. The range validation
118
		// message will display the range boundaries in hex format as well.
119
		Text hexText = createTextField(section, "Hex value in [0x00, 0xff]");
120
		IntegerEditing hexEditing = EditingFactory.forHexInteger(2).range(0x00, 0xff);
121
		bindTextField(hexText, new WritableValue(new Integer(0), null), hexEditing);
122
123
		// Edit a boolean value.
124
		Text boolText = createTextField(section, "Boolean value");
125
		BooleanEditing boolEditing = EditingFactory.forBoolean();
126
		bindTextField(boolText, new WritableValue(Boolean.TRUE, null), boolEditing);
127
	}
128
129
	private void createListSection(Composite parent) {
130
		Group section = createSectionGroup(parent, "List bindings", true);
131
132
		// Our date should be >= 01.01.1990.
133
		Calendar year1990Calendar = Calendar.getInstance();
134
		year1990Calendar.clear();
135
		year1990Calendar.set(1990, 0, 1);
136
		Date year1990 = year1990Calendar.getTime();
137
138
		// Edit a date supporting the default input/display patterns.
139
		Text dateText = createTextField(section, "Date");
140
		DateEditing dateEditing = EditingFactory.forDate().afterEqual(year1990);
141
		final WritableValue dateObservable = new WritableValue();
142
		final Binding dateBinding = bindTextField(dateText, dateObservable, dateEditing);
143
144
		// Create a list to which the dates are added when the user hits ENTER.
145
		new Label(section, SWT.LEFT);
146
		ListViewer dateListViewer = new ListViewer(section);
147
		GridDataFactory.fillDefaults().grab(true, true).hint(150, 200).applyTo(dateListViewer.getList());
148
149
		dateListViewer.setContentProvider(new ObservableListContentProvider());
150
		dateListViewer.setLabelProvider(new LabelProvider());
151
152
		// We use the same DateEditing object as for the text field above to
153
		// create a list binding which maps the entered dates to their string
154
		// representation which is then set as input on the ListViewer.
155
		final WritableList targetDateList = new WritableList();
156
		final WritableList modelDateList = new WritableList();
157
		dateEditing.bindList(dbc, targetDateList, modelDateList);
158
159
		// Set the list containing the string representation of the dates as input.
160
		dateListViewer.setInput(targetDateList);
161
162
		// Add the current date in the text field when the user hits ENTER.
163
		dateText.addSelectionListener(new SelectionAdapter() {
164
			public void widgetDefaultSelected(SelectionEvent e) {
165
				IStatus dateValidationStatus = (IStatus) dateBinding.getValidationStatus().getValue();
166
				Date date = (Date) dateObservable.getValue();
167
				if (dateValidationStatus.isOK() && date != null) {
168
					modelDateList.add(date);
169
				}
170
			}
171
		});
172
	}
173
174
	private Binding bindTextField(Text text, IObservableValue modelValue, Editing editing) {
175
		// Create the binding using the editing object.
176
		ISWTObservableValue textObservable = SWTObservables.observeText(text, SWT.Modify);
177
		Binding binding = editing.bindValue(dbc, textObservable, modelValue);
178
179
		// Decorate the control with the validation status.
180
		ControlDecorationSupport.create(binding, SWT.TOP);
181
182
		// Re-format when the text field looses the focus in order to always
183
		// display the model in the default format in case multiple input formats
184
		// are supported.
185
		formatOnFocusOut(text, binding);
186
187
		return binding;
188
	}
189
190
	private static void formatOnFocusOut(final Control control, final Binding binding) {
191
		control.addFocusListener(new FocusAdapter() {
192
			public void focusLost(FocusEvent e) {
193
				IStatus dateValidationStatus = (IStatus) binding.getValidationStatus().getValue();
194
				if (dateValidationStatus.isOK()) {
195
					binding.updateModelToTarget();
196
				}
197
			}
198
		});
199
	}
200
201
	private static Group createSectionGroup(Composite parent, String groupText, boolean grabVertical) {
202
		Group section = new Group(parent, SWT.SHADOW_ETCHED_IN);
203
		section.setText(groupText);
204
		GridLayoutFactory.fillDefaults()
205
				.numColumns(2)
206
				.equalWidth(false)
207
				.margins(5, 5)
208
				.spacing(15, 5)
209
				.applyTo(section);
210
		GridDataFactory.fillDefaults().grab(true, grabVertical).applyTo(section);
211
		return section;
212
	}
213
214
	private static Text createTextField(Composite parent, String labelText) {
215
		Label label = new Label(parent, SWT.LEFT);
216
		label.setText(labelText);
217
		GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).applyTo(label);
218
219
		Text text = new Text(parent, SWT.BORDER);
220
		GridDataFactory.fillDefaults().grab(true, false).hint(150, SWT.DEFAULT).applyTo(text);
221
222
		return text;
223
	}
224
}
(-)src/org/eclipse/jface/examples/databinding/util/EditingFactory.java (+149 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.IntegerEditing;
19
import org.eclipse.core.databinding.editing.StringEditing;
20
21
import com.ibm.icu.text.DateFormat;
22
import com.ibm.icu.text.NumberFormat;
23
24
/**
25
 * @since 3.2
26
 */
27
public final class EditingFactory {
28
29
	private static final String REQUIRED_MESSAGE = "Please specify a value.";
30
31
	private static final String INTEGER_PARSE_ERROR_MESSAGE = "The input is invalid.";
32
33
	private static final String INTEGER_OUT_OF_RANGE_MESSAGE = "The value lies outside the supported range.";
34
35
	private static final String INTEGER_RANGE_MESSAGE = "The value must lie between {0} and {1}.";
36
37
	private static final String[] BOOLEAN_TRUE_VALUES = new String[] {
38
		"yes", "y", "true", "1"
39
	};
40
41
	private static final String[] BOOLEAN_FALSE_VALUES = new String[] {
42
		"no", "n", "false", "0"
43
	};
44
45
	private static final String[] DATE_INPUT_PATTERNS = new String[] {
46
		"yyMMdd",
47
		"yyyyMMdd"
48
	};
49
50
	private static final String DATE_DISPLAY_PATTERN = "yyyyMMdd";
51
52
	private static final String DATE_PARSE_ERROR_MESSAGE = createDateParseErrorMessage(DATE_INPUT_PATTERNS);
53
54
	private static final String EMAIL_REGEX = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b";
55
56
	private static final String EMAIL_ERROR_MESSAGE = "Please specify a valid e-mail address.";
57
58
	private EditingFactory() {
59
		// prevent instantiation
60
	}
61
62
	public static StringEditing forString() {
63
		return StringEditing.stripped(true);
64
	}
65
66
	public static StringEditing forEmailString() {
67
		StringEditing editing = StringEditing.stripped(true);
68
		editing.modelStringConstraints()
69
				.matchesMessage(EMAIL_ERROR_MESSAGE)
70
				.matches(EMAIL_REGEX);
71
		return editing;
72
	}
73
74
	public static IntegerEditing forInteger() {
75
		return forInteger(Locale.getDefault());
76
	}
77
78
	public static IntegerEditing forInteger(Locale locale) {
79
		IntegerEditing editing = IntegerEditing.forFormat(
80
				NumberFormat.getIntegerInstance(locale),
81
				INTEGER_PARSE_ERROR_MESSAGE,
82
				INTEGER_OUT_OF_RANGE_MESSAGE);
83
		configure(editing);
84
		return editing;
85
	}
86
87
	public static IntegerEditing forHexInteger(int digits) {
88
		IntegerEditing editing = IntegerEditing.forFormat(
89
				RadixNumberFormat.getHexInstance("0x", digits),
90
				INTEGER_PARSE_ERROR_MESSAGE,
91
				INTEGER_OUT_OF_RANGE_MESSAGE);
92
		configure(editing);
93
		return editing;
94
	}
95
96
	private static void configure(IntegerEditing editing) {
97
		editing.modelIntegerConstraints()
98
				.requiredMessage(REQUIRED_MESSAGE)
99
				.rangeMessage(INTEGER_RANGE_MESSAGE);
100
	}
101
102
	public static BooleanEditing forBoolean() {
103
		BooleanEditing editing =
104
			BooleanEditing.forStringValues(
105
					BOOLEAN_TRUE_VALUES,
106
					BOOLEAN_FALSE_VALUES);
107
		configure(editing);
108
		return editing;
109
	}
110
111
	private static void configure(BooleanEditing editing) {
112
		editing.modelBooleanConstraints()
113
				.requiredMessage(REQUIRED_MESSAGE);
114
	}
115
116
	public static DateEditing forDate() {
117
		return forDate(Locale.getDefault());
118
	}
119
120
	public static DateEditing forDate(Locale locale) {
121
		DateEditing editing = DateEditing
122
				.forFormats(
123
						createDateFormats(DATE_INPUT_PATTERNS, locale),
124
						DATE_PARSE_ERROR_MESSAGE,
125
						DateFormat.getPatternInstance(DATE_DISPLAY_PATTERN, locale));
126
		editing.modelDateConstraints().requiredMessage(REQUIRED_MESSAGE);
127
		return editing;
128
	}
129
130
	private static DateFormat[] createDateFormats(String[] datePatterns, Locale locale) {
131
		DateFormat[] dateFormats = new DateFormat[datePatterns.length];
132
		for (int i = 0; i < dateFormats.length; i++) {
133
			dateFormats[i] = DateFormat.getPatternInstance(datePatterns[i], locale);
134
		}
135
		return dateFormats;
136
	}
137
138
	private static String createDateParseErrorMessage(String[] datePatterns) {
139
		StringBuffer messageSb = new StringBuffer();
140
		messageSb.append("Supported formats: ");
141
		for (int i = 0; i < datePatterns.length; i++) {
142
			if (i > 0) {
143
				messageSb.append(", ");
144
			}
145
			messageSb.append(datePatterns[i]);
146
		}
147
		return messageSb.toString();
148
	}
149
}
(-)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 (+245 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 final StringEditing nameEditing = EditingFactory.forString().required();
58
59
	private final IntegerEditing ageEditing = EditingFactory.forInteger().required().nonNegative();
60
61
	private final DateEditing bdayEditing = EditingFactory.forDate().before(new Date());
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
		dbc = new DataBindingContext();
90
91
		createTableSection(shell);
92
		createFieldSection(shell);
93
94
		shell.pack();
95
		shell.open();
96
97
		return shell;
98
	}
99
100
	private void createTableSection(Composite parent) {
101
		Group section = createSectionGroup(parent, 1);
102
103
		tableViewer = new TableViewer(section, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
104
		GridDataFactory.fillDefaults().grab(true, true).hint(350, 250).applyTo(tableViewer.getTable());
105
		tableViewer.getTable().setHeaderVisible(true);
106
		tableViewer.getTable().setLinesVisible(true);
107
108
		ObservableListContentProvider contentProvider = new ObservableListContentProvider();
109
		tableViewer.setContentProvider(contentProvider);
110
		IObservableSet contentElements = contentProvider.getKnownElements();
111
112
		IObservableMap nameMap = BeansObservables.observeMap(contentElements, "name");
113
		createColumn("Name*", 150, nameMap, nameEditing);
114
115
		IObservableMap ageMap = BeansObservables.observeMap(contentElements, "age");
116
		createColumn("Age*", 50, ageMap, ageEditing);
117
118
		IObservableMap bdayMap = BeansObservables.observeMap(contentElements, "birthday");
119
		createColumn("Birthday", 80, bdayMap, bdayEditing);
120
121
		WritableList people = new WritableList();
122
		people.add(new Person("John Doe", 27));
123
		people.add(new Person("Steve Northover", 33));
124
		people.add(new Person("Grant Gayed", 54));
125
		people.add(new Person("Veronika Irvine", 25));
126
		people.add(new Person("Mike Wilson", 44));
127
		people.add(new Person("Christophe Cornu", 37));
128
		people.add(new Person("Lynne Kues", 65));
129
		people.add(new Person("Silenio Quarti", 15));
130
131
		tableViewer.setInput(people);
132
133
		tableViewer.setSelection(new StructuredSelection(people.get(0)));
134
	}
135
136
	private TableViewerColumn createColumn(String text, int width, IObservableMap attributeMap, Editing modelEditing) {
137
		TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
138
		column.getColumn().setText(text);
139
		column.getColumn().setWidth(width);
140
		column.setLabelProvider(new ObservableMapEditingCellLabelProvider(attributeMap, modelEditing));
141
		column.setEditingSupport(new ObservableMapEditingSupport(tableViewer, attributeMap, modelEditing));
142
		return column;
143
	}
144
145
	private void createFieldSection(Composite parent) {
146
		final Group section = createSectionGroup(parent, 2);
147
148
		final IObservableValue personObservable = ViewersObservables.observeSingleSelection(tableViewer);
149
150
		Text nameText = createTextField(section, "Name*");
151
		IObservableValue nameObservable = BeansObservables.observeDetailValue(personObservable, "name", null);
152
		bindTextField(nameText, nameObservable, nameEditing);
153
154
		Text ageText = createTextField(section, "Age*");
155
		IObservableValue ageObservable = BeansObservables.observeDetailValue(personObservable, "age", null);
156
		bindTextField(ageText, ageObservable, ageEditing);
157
158
		Text bdayText = createTextField(section, "Birthday");
159
		IObservableValue bdayObservable = BeansObservables.observeDetailValue(personObservable, "birthday", null);
160
		bindTextField(bdayText, bdayObservable, bdayEditing);
161
	}
162
163
	private Binding bindTextField(
164
			Text text,
165
			IObservableValue modelValue,
166
			Editing editing) {
167
		// Create the binding using the editing object.
168
		ISWTObservableValue textObservable = SWTObservables.observeText(text, SWT.Modify);
169
		Binding binding = editing.bindValue(dbc, textObservable, modelValue);
170
171
		// Decorate the control with the validation status.
172
		ControlDecorationSupport.create(binding, SWT.TOP);
173
174
		formatOnFocusOut(text, binding);
175
176
		return binding;
177
	}
178
179
	private static void formatOnFocusOut(final Control control, final Binding binding) {
180
		control.addFocusListener(new FocusAdapter() {
181
			public void focusLost(FocusEvent e) {
182
				IStatus dateValidationStatus = (IStatus) binding.getValidationStatus().getValue();
183
				if (dateValidationStatus.isOK()) {
184
					binding.updateModelToTarget();
185
				}
186
			}
187
		});
188
	}
189
190
	private Group createSectionGroup(Composite parent, int numColumns) {
191
		Group section = new Group(parent, SWT.SHADOW_ETCHED_IN);
192
		GridLayoutFactory.fillDefaults().numColumns(numColumns).equalWidth(false).margins(5, 5).spacing(15, 5).applyTo(section);
193
		GridDataFactory.fillDefaults().grab(true, true).applyTo(section);
194
		return section;
195
	}
196
197
	private static Text createTextField(Composite parent, String labelText) {
198
		Label label = new Label(parent, SWT.LEFT);
199
		label.setText(labelText);
200
		GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).applyTo(label);
201
202
		Text text = new Text(parent, SWT.BORDER);
203
		GridDataFactory.fillDefaults().grab(true, false).hint(200, SWT.DEFAULT).applyTo(text);
204
205
		return text;
206
	}
207
208
	public static final class Person extends ModelObject {
209
210
		private String name;
211
212
		private int age;
213
214
		private Date birthday;
215
216
		public Person(String name, int age) {
217
			this.name = name;
218
			this.age = age;
219
		}
220
221
		public String getName() {
222
			return name;
223
		}
224
225
		public void setName(String name) {
226
			firePropertyChange("name", this.name, this.name = name);
227
		}
228
229
		public int getAge() {
230
			return age;
231
		}
232
233
		public void setAge(int age) {
234
			firePropertyChange("age", this.age, this.age = age);
235
		}
236
237
		public Date getBirthday() {
238
			return birthday;
239
		}
240
241
		public void setBirthday(Date birthday) {
242
			firePropertyChange("birthday", this.birthday, this.birthday = birthday);
243
		}
244
	}
245
}
(-)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
}

Return to bug 183055