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

Collapse All | Expand All

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

Return to bug 183055