summaryrefslogtreecommitdiff
path: root/projects/net.wotonomy.persistence/src/main/java/net/wotonomy/control/PropertyDataSource.java
blob: c02c3e22d4d7b2d148a8e1e9d46e1ee0e2e96d9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
Wotonomy: OpenStep design patterns for pure Java applications.
Copyright (C) 2000 Intersect Software Corporation

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see http://www.gnu.org
*/

package net.wotonomy.control;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;

import net.wotonomy.foundation.NSArray;
import net.wotonomy.foundation.NSMutableArray;
import net.wotonomy.foundation.internal.Introspector;
import net.wotonomy.foundation.internal.WotonomyException;

/**
 * A data source that reads and writes to an indexed property of a java object.
 * This class is used by MasterDetailAssociation to retreive objects from the
 * master display group.
 *
 * @author michael@mpowers.net
 * @author $Author: cgruber $
 * @version $Revision: 894 $
 */
public class PropertyDataSource extends OrderedDataSource {
	protected Object source;
	protected String key;
	protected Class lastKnownType; // for best-guessing
	protected EOClassDescription classDesc;
	protected EOEditingContext context;

	/**
	 * Creates a new PropertyDataSource with no editing context and will try to
	 * guess the appropriate class description when trying to create objects.
	 */
	public PropertyDataSource() {
		this(null, (EOClassDescription) null);
	}

	/**
	 * Creates a new PropertyDataSource that uses the specified editing context, but
	 * will try to guess the appropriate class description when trying to create
	 * objects.
	 */
	public PropertyDataSource(EOEditingContext aContext) {
		this(aContext, (EOClassDescription) null);
	}

	/**
	 * Creates a new PropertyDataSource that uses the specified editing context and
	 * vends objects of the specified class.
	 */
	public PropertyDataSource(EOEditingContext aContext, Class aClass) {
		this(aContext, EOClassDescription.classDescriptionForClass(aClass));
	}

	/**
	 * Creates a new PropertyDataSource that uses the specified editing context and
	 * vends objects of the specified class description.
	 */
	public PropertyDataSource(EOEditingContext aContext, EOClassDescription aClassDesc) {
		source = null;
		key = null;
		lastKnownType = null;
		classDesc = aClassDesc;
		context = aContext;
	}

	/**
	 * Provides the master object for detail display groups.
	 */
	public Object source() {
		return source;
	}

	/**
	 * Allows a detail display group to set the master object.
	 */
	public void setSource(Object anObject) {
		source = anObject;
	}

	/**
	 * Provides the detail key for detail display groups.
	 */
	public String key() {
		return key;
	}

	/**
	 * Allows a detail display group to set the detail key.
	 */
	public void setKey(String aKey) {
		key = aKey;
	}

	/**
	 * Inserts the specified object into this data source. Calls insertObjectAtIndex
	 * and appends to the end of the list.
	 */
	public void insertObject(Object anObject) {
		insertObjectAtIndex(anObject, -1); // trick to force to end
	}

	/**
	 * Inserts the specified object into this data source, at the specified index.
	 */
	public void insertObjectAtIndex(Object anObject, int anIndex) {
		if (source == null)
			return;
		List list = readAsList();
		if (anIndex == -1)
			anIndex = list.size(); // force to end
		if (anIndex > list.size())
			anIndex = list.size(); // force to end
		list.add(anIndex, anObject);
		writeAsList(list);
	}

	/**
	 * Deletes the specified object from this data source.
	 */
	public void deleteObject(Object anObject) {
		if (source == null)
			return;
		List list = readAsList();
		list.remove(anObject);
		writeAsList(list);
	}

	public EOEditingContext editingContext() {
		return context;
	}

	/**
	 * Returns a List containing the objects in this data source.
	 */
	public NSArray fetchObjects() {
		if (source == null)
			return NSArray.EmptyArray;
		return readAsList();
	}

	/**
	 * Returns a new instance of this class.
	 */
	public EODataSource dataSourceQualifiedByKey(String aKey) {
		// determine the target class desc if possible
		EOClassDescription keyClassDesc = null;
		if (classDesc != null) {
			keyClassDesc = classDesc.classDescriptionForDestinationKey(aKey);
		}
		return new PropertyDataSource(editingContext(), keyClassDesc);
	}

	/**
	 * Restricts this data source to vend those objects that are associated with the
	 * specified key on the specified object.
	 */
	public void qualifyWithRelationshipKey(String aKey, Object anObject) {
		source = anObject;
		key = aKey;
	}

	/**
	 * Returns the class description passed to the constructor, if any. If no class
	 * description and if the bound property is an indexed property, the type of the
	 * array is returned, otherwise this method returns null. This method is called
	 * by createObject().
	 */
	public EOClassDescription classDescriptionForObjects() {
		// just return the class description if we have one
		if (classDesc != null)
			return classDesc;

		// otherwise, try to do some guesswork
		EOClassDescription result = null;

		// lastKnownType is not updated here
		Class type = lastKnownType;

		// if no last known type
		if (type == null) {
			// if source and key were specified
			if ((source != null) && (key != null)) {
				// try to get an array type
				Method m = Introspector.getPropertyReadMethod(source.getClass(), key, new Class[0]);
				if (m != null) {
					Class returnType = m.getReturnType();
					if (returnType.isArray()) {
						type = returnType.getComponentType();
					}
				} else {
					throw new WotonomyException("Key does not exist for object: " + key + " : " + source);
				}
			}

			// does not update lastKnownType because
			// we prefer to get that info from a fetch.
		}

		// if type has been determined
		if (type != null) {
			result = EOClassDescription.classDescriptionForClass(type);
		}

		return result;
	}

	/**
	 * Calls getValue() and returns the result as a List. Sets lastKnownType to the
	 * retrieved type.
	 */
	protected NSMutableArray readAsList() {
		Object value = getValue();
		if (value == null) {
			return new NSMutableArray();
		}

		Object o;
		NSMutableArray result = new NSMutableArray();
		boolean hasReadType = false;
		lastKnownType = null;

		// if instance of array, convert to list
		if (value.getClass().isArray()) {
			int count = Array.getLength(value);
			for (int i = 0; i < count; i++) {
				o = Array.get(value, i);
				if (o != null) {
					// we've already found a type
					if (hasReadType) {
						// check that this matches the last known type
						if (o.getClass() != lastKnownType) {
							// not all of the same type: set to null
							lastKnownType = null;
						}
					} else // this is the first type we've found
					{
						// remember it
						hasReadType = true;
						lastKnownType = o.getClass();
					}
				}
				result.add(o);
			}
		} else if (value instanceof Collection) {
			// convert to list so we handle sets, etc.
			Iterator i = ((Collection) value).iterator();
			while (i.hasNext()) {
				o = i.next();
				if (o != null) {
					// we've already found a type
					if (hasReadType) {
						// check that this matches the last known type
						if (o.getClass() != lastKnownType) {
							// not all of the same type: set to null
							lastKnownType = null;
						}
					} else // this is the first type we've found
					{
						// remember it
						hasReadType = true;
						lastKnownType = o.getClass();
					}
				}
				result.add(o);
			}
		} else {
			lastKnownType = null;
			throw new WotonomyException("PropertyDataSource: " + "bound property was not an indexed property: " + key);
		}

		return result;
	}

	/**
	 * Converts the specified List to lastKnownType and calls setValue().
	 */
	protected void writeAsList(List anObjectList) {
		if (source == null) {
			throw new WotonomyException("PropertyDataSource: " + "no source object: " + key);
		}

		Class c = source.getClass();
		Method m = Introspector.getPropertyReadMethod(c, key, new Class[0]);
		if (m == null) {
			throw new WotonomyException("Could not read property for object: " + key + " : " + source + " (" + c + ")");
		}

		Class returnType = m.getReturnType();

		int count = anObjectList.size();
		Object result = null;

		if (returnType.isArray()) {
			Class type = returnType.getComponentType();
			result = Array.newInstance(type, count);
			for (int i = 0; i < count; i++) {
				Array.set(result, i, anObjectList.get(i));
			}
		} else {
			Collection collection = null;

			if (!returnType.isInterface()) {
				try {
					collection = (Collection) returnType.newInstance();
				} catch (Exception exc) {
					// no default constructor, leave null
				}
			}

			// try to find an acceptable collections type
			if (collection == null) {
				if (returnType.isAssignableFrom(NSMutableArray.class)) {
					collection = new NSMutableArray();
				} else if (returnType.isAssignableFrom(LinkedList.class)) {
					collection = new LinkedList();
				} else if (returnType.isAssignableFrom(ArrayList.class)) {
					collection = new ArrayList();
				} else if (returnType.isAssignableFrom(HashSet.class)) {
					collection = new HashSet();
				} else if (returnType.isAssignableFrom(TreeSet.class)) {
					collection = new TreeSet();
				}
			}

			if (collection == null) {
				throw new WotonomyException("Could not create a collection of type: " + returnType);
			}

			collection.addAll(anObjectList);
			result = collection;
		}

		setValue(result);
	}

	/**
	 * Returns the value of the indexed property specified by
	 * qualifyWithRelationshipKey.
	 */
	protected Object getValue() {
		if (source instanceof EOKeyValueCoding) {
			return ((EOKeyValueCoding) source).valueForKey(key);
		}
		return EOKeyValueCodingSupport.valueForKey(source, key);
	}

	/**
	 * Sets the value of the indexed property specified by
	 * qualifyWithRelationshipKey. The argument is assumed to be of appropriate type
	 * for the property. EOObserverCenter is notified that the object will change.
	 */
	protected void setValue(Object aValue) {
		EOClassDescription sourceDesc = EOClassDescription.classDescriptionForClass(source.getClass());

		// if we're not editing a relationship (?)
//        if ( ! sourceDesc.toManyRelationshipKeys().containsObject( key ) )
		{
			// mark the parent as changed
			EOObserverCenter.notifyObserversObjectWillChange(source);
		}

		if (source instanceof EOKeyValueCoding) {
			((EOKeyValueCoding) source).takeValueForKey(aValue, key);
		} else {
			EOKeyValueCodingSupport.takeValueForKey(source, aValue, key);
		}
	}

}

/*
 * $Log$ Revision 1.2 2006/02/16 16:47:14 cgruber Move some classes in to
 * "internal" packages and re-work imports, etc.
 *
 * Also use UnsupportedOperationExceptions where appropriate, instead of
 * WotonomyExceptions.
 *
 * Revision 1.1 2006/02/16 13:19:57 cgruber Check in all sources in
 * eclipse-friendly maven-enabled packages.
 *
 * Revision 1.14 2003/01/18 23:30:42 mpowers WODisplayGroup now compiles.
 *
 * Revision 1.13 2002/10/24 21:15:36 mpowers New implementations of NSArray and
 * subclasses.
 *
 * Revision 1.12 2002/10/24 18:18:12 mpowers NSArray's are now considered
 * read-only, so we can return our internal representation to reduce unnecessary
 * object allocation.
 *
 * Revision 1.11 2002/04/15 21:55:33 mpowers Catching a condition where the get
 * may not return the value passed to set.
 *
 * Revision 1.10 2002/03/08 23:20:37 mpowers insertObject now calls
 * insertObjectAtIndex.
 *
 * Revision 1.9 2001/06/05 19:10:41 mpowers Better handling of null properties.
 *
 * Revision 1.8 2001/05/21 14:03:35 mpowers Added a convenience constructor for
 * java classes.
 *
 * Revision 1.7 2001/04/30 13:15:24 mpowers Child contexts re-initializing
 * objects invalidated in parent now propery transpose relationships.
 *
 * Revision 1.6 2001/04/29 02:29:31 mpowers Debugging relationship faulting.
 *
 * Revision 1.5 2001/04/28 22:17:51 mpowers Revised PropertyDataSource to be
 * EOClassDescription-aware.
 *
 * Revision 1.4 2001/04/27 23:37:20 mpowers Now using EOClassDescription in the
 * EODataSource class, as we should.
 *
 * Revision 1.3 2001/03/29 03:29:49 mpowers Now using KeyValueCoding and Support
 * instead of Introspector.
 *
 * Revision 1.2 2001/01/24 14:10:53 mpowers Contributing OrderedDataSource, and
 * PropertyDataSource extends it.
 *
 * Revision 1.1.1.1 2000/12/21 15:46:50 mpowers Contributing wotonomy.
 *
 * Revision 1.3 2000/12/20 16:25:35 michael Added log to all files.
 *
 *
 */