View Javadoc
1   /*
2    * Copyright 2019 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 org.bremersee.dccon.service;
18  
19  import java.util.regex.Pattern;
20  import org.bremersee.dccon.model.DnsNode;
21  
22  /**
23   * The dns node comparator.
24   *
25   * @author Christian Bremer
26   */
27  public class DnsNodeComparator extends AbstractDnsComparator<DnsNode> {
28  
29    /**
30     * Instantiates a dns node comparator.
31     */
32    DnsNodeComparator() {
33      this(Boolean.TRUE);
34    }
35  
36    /**
37     * Instantiates a dns node comparator.
38     *
39     * @param asc use ascending sort order or not
40     */
41    private DnsNodeComparator(Boolean asc) {
42      super(asc);
43    }
44  
45    @Override
46    public int compare(DnsNode o1, DnsNode o2) {
47      final String s1 = o1 != null && o1.getName() != null ? o1.getName() : "";
48      final String s2 = o2 != null && o2.getName() != null ? o2.getName() : "";
49  
50      final String[] sa1 = s1.split(Pattern.quote("."));
51      final String[] sa2 = s2.split(Pattern.quote("."));
52      if (sa1.length == sa2.length) {
53        for (int i = 0; i < sa1.length; i++) {
54          int result = format(sa1[i], 3).compareToIgnoreCase(format(sa2[i], 3));
55          if (result != 0) {
56            return isAsc() ? result : -1 * result;
57          }
58        }
59        return 0;
60      }
61  
62      int result = format(s1, 3).compareToIgnoreCase(format(s2, 3));
63      return isAsc() ? result : -1 * result;
64    }
65  }