1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.properties.spi.config.support;
17
18 import java.io.IOException;
19 import java.net.MalformedURLException;
20 import java.net.URL;
21 import java.util.Collections;
22 import java.util.Enumeration;
23 import java.util.LinkedList;
24
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28
29
30
31 public final class UrlUtil
32 {
33
34
35
36
37
38
39
40 private static final Logger LOG = LoggerFactory.getLogger(UrlUtil.class);
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69 public static Enumeration<URL> getResourceUrlsFromFolder(
70 final ClassLoader classLoader, final String resourceFolderName)
71 throws IOException
72 {
73 return getResourceUrls(classLoader, resourceFolderName.endsWith("/")
74 ? resourceFolderName : resourceFolderName + "/");
75 }
76
77
78
79
80
81
82
83
84
85 public static Enumeration<URL> getResourceUrls(final ClassLoader classLoader,
86 final String resourceName) throws IOException
87 {
88 final Enumeration<URL> rootUrls = classLoader.getResources(resourceName);
89 final LinkedList<URL> rootResourceUrls = new LinkedList<URL>();
90 while (rootUrls.hasMoreElements())
91 {
92 final URL current = rootUrls.nextElement();
93 rootResourceUrls.add(shortenUrl(current, resourceName));
94 }
95 return Collections.enumeration(rootResourceUrls);
96 }
97
98 public static URL shortenUrl(final URL current, final String resourceName)
99 throws MalformedURLException
100 {
101 final String path = current.getPath();
102 String strippedPath =
103 path.substring(0, path.length() - resourceName.length());
104 strippedPath = ensureEndsWith(strippedPath, "/");
105 final URL stripped;
106 try
107 {
108 if ("jar".equals(current.getProtocol()))
109 {
110 stripped =
111 new URL("jar:" + new URL(current, strippedPath).toExternalForm());
112 }
113 else
114 {
115 stripped = new URL(current, strippedPath);
116 }
117 }
118 catch (final MalformedURLException e)
119 {
120 LOG.warn("Cannot use URL '{}' in its truncated form '{}'.", current,
121 strippedPath);
122 return current;
123 }
124 return stripped;
125 }
126
127 private static String ensureEndsWith(final String inputString,
128 final String endsWith)
129 {
130 String ensuredString = inputString;
131 if (!ensuredString.endsWith(endsWith))
132 {
133 ensuredString += endsWith;
134 }
135 return ensuredString;
136 }
137 }