01: /*
02: * Copyright 2004-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.springframework.binding.expression.support;
17:
18: import java.util.Collection;
19:
20: import org.springframework.binding.expression.EvaluationContext;
21: import org.springframework.binding.expression.EvaluationException;
22: import org.springframework.binding.expression.Expression;
23: import org.springframework.binding.expression.SetValueAttempt;
24: import org.springframework.binding.expression.SettableExpression;
25: import org.springframework.core.style.ToStringCreator;
26: import org.springframework.util.Assert;
27:
28: /**
29: * A settable expression that adds non-null values to a collection.
30: *
31: * @author Keith Donald
32: */
33: public class CollectionAddingExpression implements SettableExpression {
34:
35: /**
36: * The expression that resolves a mutable collection reference.
37: */
38: private Expression collectionExpression;
39:
40: /**
41: * Creates a collection adding property expression.
42: * @param collectionExpression the collection expression
43: */
44: public CollectionAddingExpression(Expression collectionExpression) {
45: this .collectionExpression = collectionExpression;
46: }
47:
48: public Object evaluate(Object target, EvaluationContext context)
49: throws EvaluationException {
50: return collectionExpression.evaluate(target, context);
51: }
52:
53: public void evaluateToSet(Object target, Object value,
54: EvaluationContext context) throws EvaluationException {
55: Object result = evaluate(target, context);
56: if (result == null) {
57: throw new EvaluationException(
58: new SetValueAttempt(this , target, value, null),
59: new IllegalArgumentException(
60: "The collection expression evaluated to a [null] reference"));
61: }
62: Assert.isInstanceOf(Collection.class, result,
63: "Not a collection: ");
64: if (value != null) {
65: // add the value to the collection
66: ((Collection) result).add(value);
67: }
68: }
69:
70: public String toString() {
71: return new ToStringCreator(this ).append("collectionExpression",
72: collectionExpression).toString();
73: }
74: }
|