View Javadoc
1   /*
2    * Copyright 2002-2016 the original author or authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
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  
17  package com.github.springtestdbunit;
18  
19  import java.lang.reflect.Constructor;
20  import java.lang.reflect.Modifier;
21  import java.util.ArrayList;
22  import java.util.List;
23  
24  import org.dbunit.dataset.IDataSet;
25  
26  import com.github.springtestdbunit.dataset.DataSetModifier;
27  
28  /**
29   * A collection of {@link DataSetModifier} items loaded during testing.
30   *
31   * @author Phillip Webb
32   */
33  class DataSetModifiers implements DataSetModifier {
34  
35  	private final List<DataSetModifier> modifiers = new ArrayList<DataSetModifier>();
36  
37  	public IDataSet modify(IDataSet dataSet) {
38  		for (DataSetModifier modifier : this.modifiers) {
39  			dataSet = modifier.modify(dataSet);
40  		}
41  		return dataSet;
42  	}
43  
44  	public void add(Object testInstance, Class<? extends DataSetModifier> modifierClass) {
45  		try {
46  			Class<?> enclosingClass = modifierClass.getEnclosingClass();
47  			if ((enclosingClass == null) || Modifier.isStatic(modifierClass.getModifiers())) {
48  				add(modifierClass.getDeclaredConstructor());
49  			} else {
50  				add(modifierClass.getDeclaredConstructor(enclosingClass), testInstance);
51  			}
52  		} catch (Exception ex) {
53  			throw new IllegalStateException(ex);
54  		}
55  	}
56  
57  	private void add(Constructor<? extends DataSetModifier> constructor, Object... args) throws Exception {
58  		constructor.setAccessible(true);
59  		this.modifiers.add(constructor.newInstance(args));
60  	}
61  
62  }