1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.rundeck.api.parser;
26
27 import org.dom4j.Element;
28 import org.dom4j.Node;
29 import org.rundeck.api.RundeckApiException;
30 import org.rundeck.api.util.PagedResults;
31
32 import java.util.*;
33
34
35
36
37
38
39
40 public class PagedResultParser<T> implements XmlNodeParser<PagedResults<T>> {
41 ListParser<T> itemParser;
42 private String xpath;
43
44
45
46
47
48
49
50 public PagedResultParser(ListParser<T> itemParser, String xpath) {
51 this.itemParser = itemParser;
52 this.xpath = xpath;
53 }
54
55 @Override
56 public PagedResults<T> parseXmlNode(Node node) {
57 Node pagedNodeContainer = BaseXpathParser.selectNodeAndUnwrap(node, xpath);
58 if(null==pagedNodeContainer) {
59 throw new RundeckApiException("XML content did not match XPATH expression: " + xpath);
60 }
61 Element el = (Element) pagedNodeContainer;
62 final int max = integerAttribute(el, "max", -1);
63 final int offset = integerAttribute(el, "offset", -1);
64 final int total = integerAttribute(el, "total", -1);
65 final int count = integerAttribute(el, "count", -1);
66
67 final List<T> ts = itemParser.parseXmlNode(pagedNodeContainer);
68
69
70 return new PagedResults<T>() {
71 @Override
72 public int getMax() {
73 return max;
74 }
75
76 @Override
77 public int getOffset() {
78 return offset;
79 }
80
81 @Override
82 public int getTotal() {
83 return total;
84 }
85
86 @Override
87 public List<T> getResults() {
88 return ts;
89 }
90
91 @Override
92 public int getCount() {
93 return count;
94 }
95
96 @Override
97 public Iterator<T> iterator() {
98 return ts.iterator();
99 }
100 };
101 }
102
103
104
105
106
107
108
109
110 private int integerAttribute(Element el, final String attribute, final int defValue) {
111 int parseMax = defValue;
112 try {
113 final String max1 = null != el.attribute(attribute) ? el.attribute(attribute).getStringValue() : null;
114 parseMax = null != max1 ? Integer.parseInt(max1) : defValue;
115 } catch (NumberFormatException e) {
116 }
117 return parseMax;
118 }
119
120 public String getXpath() {
121 return xpath;
122 }
123 }