1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.pipeline.stage;
19
20 import java.util.Collection;
21 import java.util.Collections;
22 import org.apache.commons.pipeline.validation.ConsumedTypes;
23 import org.apache.commons.pipeline.validation.ProducesConsumed;
24
25 /**
26 * This is a simple stage in the pipeline which will add each processed object
27 * to the specified collection.
28 *
29 * For the purposes of validation, this stage is considered to be able to consume
30 * objects of any class although the process() method may throw a ClassCastException
31 * if a processed object cannot be added to the collection.
32 */
33 @ConsumedTypes(Object.class)
34 @ProducesConsumed
35 public class AddToCollectionStage<T> extends BaseStage {
36
37 /**
38 * Holds value of property collection.
39 */
40 private Collection<T> collection;
41
42 /**
43 * Creates a new instance of AddToCollectionStage. This constructor
44 * will synchronized the collection by default.
45 */
46 public AddToCollectionStage(Collection<T> collection) {
47 this(collection, true);
48 }
49
50 /**
51 * Creates a new instance of AddToCollectionStage.
52 * @param collection The collection in which to add objects to
53 * @param synchronized A flag value that determines whether or not accesses
54 * to the underlying collection are synchronized.
55 */
56 public AddToCollectionStage(Collection<T> collection, boolean synchronize) {
57 if (collection == null){
58 throw new IllegalArgumentException("Argument 'collection' can not be null.");
59 }
60
61 this.collection = synchronize ? Collections.synchronizedCollection(collection) : collection;
62 }
63
64 /**
65 * Adds the object to the underlying collection.
66 *
67 * @throws ClassCastException if the object is not of a suitable type to be added
68 * to the collection.
69 */
70 public void process(Object obj) throws org.apache.commons.pipeline.StageException {
71 this.collection.add((T) obj);
72 this.emit(obj);
73 }
74
75 /**
76 * Returns the collection to which elements have been added during
77 * processing.
78 */
79 public Collection<T> getCollection() {
80 return this.collection;
81 }
82 }