00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 package dochelper;
00011
00012 import dochelper.exceptions.IllegalParamterTypeException;
00013 import dochelper.exceptions.InitializationException;
00014 import dochelper.exceptions.InvalidValueException;
00015 import dochelper.exceptions.MissingArgumentException;
00016 import dochelper.exceptions.ResourceUnavailableException;
00017 import java.util.ArrayList;
00018 import java.util.Collections;
00019 import java.util.Comparator;
00020 import java.util.HashMap;
00021 import java.util.List;
00022
00044 public class NaturalOrderParamProcessor implements Processor {
00045
00046
00050 protected static final String DIRECTION = "direction";
00051 protected static final String SORT_PARAM = "sortparam";
00052
00056 protected HashMap<String, Object> params = new HashMap<String, Object>();
00057
00058
00059 public ResultNode operate(ResultNode doc) {
00060
00061
00062
00063
00064 orderTree(doc);
00065 return doc;
00066 }
00067
00068
00069 private void orderTree(ResultNode doc) {
00070
00071 if (doc.isLeaf()) return;
00072
00073
00074 for(ResultNode child : doc.getChildren()) {
00075 orderTree(child);
00076 }
00077
00078
00079
00080 Collections.sort(doc.getChildren(), new ParamResultNodeComparator((String)params.get(SORT_PARAM)));
00081
00082 }
00083
00084 public void setParam(String paramName, Object value) throws IllegalParamterTypeException {
00085 params.put(paramName, value);;
00086 }
00087
00088
00089 public void checkParams() throws InvalidValueException, MissingArgumentException, ResourceUnavailableException {
00090
00091 if (!params.containsKey(DIRECTION)) {
00092 params.put(DIRECTION, "asc");
00093 }
00094
00095
00096 if(!params.containsKey(SORT_PARAM))
00097 throw new MissingArgumentException(SORT_PARAM);
00098 }
00099
00100
00101 public void init() throws InitializationException, ResourceUnavailableException {
00102
00103 }
00104
00105 public class ParamResultNodeComparator implements Comparator {
00106
00107 private String paramKey;
00108
00109 public ParamResultNodeComparator(String paramKey) {
00110 this.paramKey = paramKey;
00111 }
00112
00113 public int compare(Object o1, Object o2) {
00114
00115
00116
00117 ResultNode r1 = (ResultNode)o1;
00118 ResultNode r2 = (ResultNode)o2;
00119
00120 if(r1.getParams()==null || r2.getParams() == null)
00121 return 0;
00122
00123 Comparable p1 = (Comparable)r1.getParams().get(paramKey);
00124 Comparable p2 = (Comparable)r2.getParams().get(paramKey);
00125
00126
00127 if(p1==null||p2==null)
00128 return 0;
00129
00130 int base = p1.compareTo(p2);
00131 int direction = ((String)(params.get(DIRECTION))).equalsIgnoreCase("desc")?-1:1;
00132
00133 return base*direction;
00134 }
00135 }
00136 }