Skip to content

Commit 768bf3c

Browse files
committed
JAVA-1246: Removed duplicates from hosts list parameter to ClusterSettings.Builder.hosts(). Also, throw if hosts list is null or empty.
1 parent 93b6760 commit 768bf3c

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/main/com/mongodb/ClusterSettings.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818

1919
import org.bson.util.annotations.Immutable;
2020

21+
import java.util.ArrayList;
2122
import java.util.Collections;
23+
import java.util.LinkedHashSet;
2224
import java.util.List;
2325

2426
import static org.bson.util.Assertions.isTrueArgument;
@@ -53,14 +55,17 @@ private Builder() {
5355
// CHECKSTYLE:OFF
5456

5557
/**
56-
* Sets the hosts for the cluster.
58+
* Sets the hosts for the cluster. And duplicate server addresses are removed from the list.
5759
*
5860
* @param hosts the seed list of hosts
5961
* @return this
6062
*/
6163
public Builder hosts(final List<ServerAddress> hosts) {
6264
notNull("hosts", hosts);
63-
this.hosts = Collections.unmodifiableList(hosts);
65+
if (hosts.isEmpty()) {
66+
throw new IllegalArgumentException("hosts list may not be empty");
67+
}
68+
this.hosts = Collections.unmodifiableList(new ArrayList<ServerAddress>(new LinkedHashSet<ServerAddress>(hosts)));
6469
return this;
6570
}
6671

src/test/com/mongodb/ClusterSettingsSpecification.groovy

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,30 @@ class ClusterSettingsSpecification extends Specification {
8484
then:
8585
thrown(IllegalArgumentException)
8686
}
87+
88+
def 'should throws if hosts list is null'() {
89+
when:
90+
ClusterSettings.builder().hosts(null).build();
91+
92+
then:
93+
thrown(IllegalArgumentException)
94+
}
95+
96+
def 'should throws if hosts list is empty'() {
97+
when:
98+
ClusterSettings.builder().hosts([]).build();
99+
100+
then:
101+
thrown(IllegalArgumentException)
102+
}
103+
104+
def 'should remove duplicate hosts'() {
105+
when:
106+
def settings = ClusterSettings.builder().hosts([new ServerAddress('server1'),
107+
new ServerAddress('server2'),
108+
new ServerAddress('server1')]).build();
109+
110+
then:
111+
settings.getHosts() == [new ServerAddress('server1'), new ServerAddress('server2')]
112+
}
87113
}

0 commit comments

Comments
 (0)