1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.tooling.commons.packmgr.httpaction;
21
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Set;
25 import java.util.regex.Pattern;
26
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.commons.lang3.Strings;
29 import org.json.JSONArray;
30 import org.json.JSONObject;
31
32
33
34
35 final class BundleStatusParser {
36
37 private final List<Pattern> bundleStatusWhitelistBundleNames;
38
39 BundleStatusParser(List<Pattern> bundleStatusWhitelistBundleNames) {
40 this.bundleStatusWhitelistBundleNames = bundleStatusWhitelistBundleNames;
41 }
42
43 @SuppressWarnings("java:S3776")
44 BundleStatus parse(String jsonString) {
45 JSONObject json = new JSONObject(jsonString);
46
47 String statusLine = json.getString("status");
48
49
50 int total = 0;
51 int active = 0;
52 int activeFragment = 0;
53 int resolved = 0;
54 int installed = 0;
55 int ignored = 0;
56
57
58 Set<String> bundleSymbolicNames = new HashSet<>();
59 JSONArray data = json.getJSONArray("data");
60 for (int i = 0; i < data.length(); i++) {
61 JSONObject item = data.getJSONObject(i);
62
63 String symbolicName = item.optString("symbolicName");
64 String state = item.optString("state");
65 boolean fragment = item.optBoolean("fragment");
66 boolean whitelisted = isWhitelisted(symbolicName);
67
68 total++;
69 if (fragment) {
70 activeFragment++;
71 }
72 else if (isActive(state)) {
73 active++;
74 }
75 else if (isResolved(state)) {
76 if (whitelisted) {
77 ignored++;
78 }
79 else {
80 resolved++;
81 }
82 }
83 else if (isInstalled(state)) {
84 if (whitelisted) {
85 ignored++;
86 }
87 else {
88 installed++;
89 }
90 }
91
92 if (StringUtils.isNotBlank(symbolicName) && !whitelisted) {
93 bundleSymbolicNames.add(symbolicName);
94 }
95 }
96
97 return new BundleStatus(
98 statusLine,
99 total, active, activeFragment, resolved, installed, ignored,
100 bundleSymbolicNames);
101 }
102
103 private boolean isActive(String actual) {
104 return Strings.CI.equals(actual, "Active");
105 }
106
107 private boolean isResolved(String actual) {
108 return Strings.CI.equals(actual, "Resolved");
109 }
110
111 private boolean isInstalled(String actual) {
112 return Strings.CI.equals(actual, "Installed");
113 }
114
115 private boolean isWhitelisted(String symbolicName) {
116 for (Pattern pattern : bundleStatusWhitelistBundleNames) {
117 if (pattern.matcher(symbolicName).matches()) {
118 return true;
119 }
120 }
121 return false;
122 }
123
124 }