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