View Javadoc
1   package org.argeo.connect.ui.util;
2   
3   import javax.jcr.Node;
4   import javax.jcr.PropertyType;
5   import javax.jcr.RepositoryException;
6   import javax.jcr.Value;
7   import javax.jcr.query.Row;
8   
9   import org.argeo.connect.ConnectException;
10  import org.eclipse.jface.viewers.Viewer;
11  
12  /**
13   * Extends canonical row comparator adding an experimental implementation to
14   * enable comparison of multiple value String properties
15   */
16  public class RowViewerComparator extends org.argeo.eclipse.ui.jcr.lists.RowViewerComparator {
17  
18  	private static final long serialVersionUID = 5409706129676092059L;
19  
20  	public RowViewerComparator() {
21  	}
22  
23  	/**
24  	 * e1 and e2 must both be Jcr rows.
25  	 * 
26  	 * @param viewer
27  	 * @param e1
28  	 * @param e2
29  	 * @return
30  	 */
31  	@Override
32  	public int compare(Viewer viewer, Object e1, Object e2) {
33  		try {
34  
35  			Node n1 = ((Row) e1).getNode(selectorName);
36  			Node n2 = ((Row) e2).getNode(selectorName);
37  
38  			if (n1.hasProperty(propertyName) && n1.getProperty(propertyName).isMultiple())
39  				if (n1.getProperty(propertyName).getType() == PropertyType.STRING)
40  					return compareMultipleStrings(n1, n2);
41  				else
42  					throw new ConnectException(
43  							"Comparison of multiple value properties is only implemented for Strings");
44  			else if (n2.hasProperty(propertyName) && n2.getProperty(propertyName).isMultiple())
45  				if (n2.getProperty(propertyName).getType() == PropertyType.STRING)
46  					return compareMultipleStrings(n1, n2);
47  				else
48  					throw new ConnectException("Comparison of multi-value propertyis only implemented for Strings");
49  			else
50  				return super.compare(viewer, e1, e2);
51  		} catch (RepositoryException re) {
52  			throw new ConnectException("Unexpected error " + "while comparing rows", re);
53  		}
54  	}
55  
56  	private String getString(Value[] values) throws RepositoryException {
57  		StringBuilder builder = new StringBuilder();
58  		for (Value value : values)
59  			builder.append(value.getString());
60  		return builder.toString();
61  	}
62  
63  	private int compareMultipleStrings(Node n1, Node n2) throws RepositoryException {
64  		int rc = 0;
65  
66  		if (!n1.hasProperty(propertyName))
67  			rc = -1;
68  		else if (!n2.hasProperty(propertyName))
69  			rc = 1;
70  		else {
71  			String s1 = getString(n1.getProperty(propertyName).getValues());
72  			String s2 = getString(n2.getProperty(propertyName).getValues());
73  			rc = s1.compareTo(s2);
74  		}
75  
76  		if (direction == DESCENDING) {
77  			rc = -rc;
78  		}
79  		return rc;
80  	}
81  }