1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.morph.util;
17
18 import java.util.Iterator;
19
20 import net.sf.composite.util.ObjectUtils;
21
22 /**
23 * Assertions built using Morph.
24 *
25 * @author Matt Sgarlata
26 * @since Apr 18, 2005
27 */
28 public abstract class Assert extends net.sf.composite.util.Assert {
29
30 protected interface Validator {
31 public boolean isValid(Object object);
32 }
33
34 protected static void contentsAssertion(Validator validator, Object container, String message) {
35 if (ObjectUtils.isEmpty(container)) return;
36
37 Iterator iterator = ContainerUtils.getIterator(container);
38 int numInvalid = 0;
39 while (iterator.hasNext()) {
40 Object object = iterator.next();
41 if (!validator.isValid(object)) {
42 numInvalid++;
43 }
44 }
45 if (numInvalid > 0) {
46 throw new IllegalArgumentException(message + ", but there were " + numInvalid + " objects which did not meet this criterion.");
47 }
48 }
49
50 /**
51 * Throws an exception if any object in the given container is
52 * <code>null</code>.
53 *
54 * @param container
55 * any container for which Morph provides a
56 * {@link net.sf.morph.reflect.ContainerReflector}
57 * @throws IllegalArgumentException
58 * if any object in the container is <code>null</code>
59 */
60 public static void contentsNotNull(Object container) {
61 Validator callback = new Validator() {
62 public boolean isValid(Object object) {
63 return object != null;
64 }
65 };
66
67 contentsAssertion(callback, container, "The objects in the container cannot be null");
68 }
69
70 /**
71 * Throws an exception if any object in the given container is empty, as
72 * defined by {@link net.sf.composite.util.ObjectUtils#isEmpty(Object)}.
73 *
74 * @param container
75 * any container for which Morph provides a
76 * {@link net.sf.morph.reflect.ContainerReflector}
77 * @throws IllegalArgumentException
78 * if any object in the container is empty, as defined by
79 * {@link net.sf.composite.util.ObjectUtils#isEmpty(Object)}
80 */
81 public static void contentsNotEmpty(Object container) {
82 Validator callback = new Validator() {
83 public boolean isValid(Object object) {
84 return !ObjectUtils.isEmpty(object);
85 }
86 };
87
88 contentsAssertion(callback, container, "The objects in the container cannot be empty");
89 }
90
91 }