1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.chain.web.javax;
18
19 import java.net.URL;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import javax.servlet.ServletContext;
24
25 import org.apache.commons.chain.Catalog;
26 import org.apache.commons.chain.web.CheckedConsumer;
27 import org.apache.commons.chain.web.CheckedFunction;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31
32
33
34
35
36
37
38
39 final class ChainResources {
40
41
42
43
44 private ChainResources() {
45 }
46
47
48
49
50
51
52
53
54
55
56 static <E extends Exception> void parseClassResources(String resources,
57 CheckedConsumer<URL, E> parse) {
58
59 ClassLoader loader =
60 Thread.currentThread().getContextClassLoader();
61 if (loader == null) {
62 loader = ChainResources.class.getClassLoader();
63 }
64 parseResources(loader::getResource, resources, parse);
65 }
66
67
68
69
70
71
72
73
74
75 static <E extends Exception> void parseWebResources(ServletContext context,
76 String resources,
77 CheckedConsumer<URL, E> parse) {
78
79 parseResources(context::getResource, resources, parse);
80 }
81
82
83
84
85
86
87
88
89
90
91 private static <ER extends Exception, EP extends Exception> void parseResources(
92 CheckedFunction<String, URL, ER> resourceFunction, String resources,
93 CheckedConsumer<URL, EP> parse) {
94
95 if (resources == null) {
96 return;
97 }
98 Logger logger = LoggerFactory.getLogger(ChainResources.class);
99 String[] paths = getResourcePaths(resources);
100 String path = null;
101 try {
102 for (String path2 : paths) {
103 path = path2;
104 URL url = resourceFunction.apply(path);
105 if (url == null) {
106 throw new IllegalStateException("Missing chain config resource '" + path + "'");
107 }
108 logger.debug("Loading chain config resource '{}'", path);
109 parse.accept(url);
110 }
111 } catch (Exception e) {
112 throw new RuntimeException("Exception parsing chain config resource '" + path + "': "
113 + e.getMessage());
114 }
115 }
116
117
118
119
120
121
122
123
124
125
126
127
128 static String[] getResourcePaths(String resources) {
129 final List<String> paths = new ArrayList<>();
130
131 if (resources != null) {
132 String path;
133 int comma;
134
135 int lastComma = 0;
136 while ((comma = resources.indexOf(',', lastComma)) >= 0) {
137 path = resources.substring(lastComma, comma).trim();
138 if (path.length() > 0) {
139 paths.add(path);
140 }
141 lastComma = comma + 1;
142 }
143 path = resources.substring(lastComma).trim();
144 if (path.length() > 0) {
145 paths.add(path);
146 }
147 }
148
149 return paths.toArray(new String[0]);
150 }
151 }