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.sql.SQLException;
20  
21  import org.dbunit.database.IDatabaseConnection;
22  import org.springframework.util.Assert;
23  import org.springframework.util.StringUtils;
24  
25  /**
26   * Holds a number of {@link IDatabaseConnection} beans.
27   *
28   * @author Phillip Webb
29   */
30  public class DatabaseConnections {
31  
32  	private final String[] names;
33  
34  	private final IDatabaseConnection[] connections;
35  
36  	public DatabaseConnections(String[] names, IDatabaseConnection[] connections) {
37  		Assert.notEmpty(names, "Names must not be empty");
38  		Assert.notEmpty(connections, "Connections must not be empty");
39  		Assert.isTrue(names.length == connections.length, "Names and Connections must have the same length");
40  		this.names = names;
41  		this.connections = connections;
42  	}
43  
44  	public void closeAll() throws SQLException {
45  		for (IDatabaseConnection connection : this.connections) {
46  			connection.close();
47  		}
48  	}
49  
50  	public IDatabaseConnection get(String name) {
51  		if (!StringUtils.hasLength(name)) {
52  			return this.connections[0];
53  		}
54  		for (int i = 0; i < this.names.length; i++) {
55  			if (this.names[i].equals(name)) {
56  				return this.connections[i];
57  			}
58  		}
59  		throw new IllegalStateException("Unable to find connection named " + name);
60  	}
61  
62  }