View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.syncope.client.console.commons;
20  
21  import java.io.Serializable;
22  import java.util.Comparator;
23  import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
24  import org.apache.wicket.model.IModel;
25  import org.apache.wicket.model.PropertyModel;
26  
27  public class SortableDataProviderComparator<T> implements Comparator<T>, Serializable {
28  
29      private static final long serialVersionUID = -8897687699977460543L;
30  
31      protected final SortableDataProvider<T, String> provider;
32  
33      public SortableDataProviderComparator(final SortableDataProvider<T, String> provider) {
34          this.provider = provider;
35      }
36  
37      @SuppressWarnings({ "unchecked", "rawtypes" })
38      protected int compare(final IModel<Comparable> model1, final IModel<Comparable> model2) {
39          int result;
40  
41          if (model1.getObject() == null && model2.getObject() == null) {
42              result = 0;
43          } else if (model1.getObject() == null) {
44              result = 1;
45          } else if (model2.getObject() == null) {
46              result = -1;
47          } else {
48              result = model1.getObject().compareTo(model2.getObject());
49          }
50  
51          result = provider.getSort().isAscending()
52                  ? result
53                  : -result;
54  
55          return result;
56      }
57  
58      @SuppressWarnings("rawtypes")
59      @Override
60      public int compare(final T object1, final T object2) {
61          IModel<Comparable> model1 = new PropertyModel<>(object1, provider.getSort().getProperty());
62          IModel<Comparable> model2 = new PropertyModel<>(object2, provider.getSort().getProperty());
63  
64          return compare(model1, model2);
65      }
66  }