File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1818
1919import org .bson .util .annotations .Immutable ;
2020
21+ import java .util .ArrayList ;
2122import java .util .Collections ;
23+ import java .util .LinkedHashSet ;
2224import java .util .List ;
2325
2426import 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
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments