1
2
3
4 package net.sourceforge.pmd.util;
5
6 import net.sourceforge.pmd.RuleSetNotFoundException;
7
8 import java.io.File;
9 import java.io.FileInputStream;
10 import java.io.FileNotFoundException;
11 import java.io.InputStream;
12 import java.net.HttpURLConnection;
13 import java.net.URL;
14
15
16
17 public final class ResourceLoader {
18
19 public static final int TIMEOUT;
20 static {
21 int timeoutProperty = 5000;
22 try {
23 timeoutProperty = Integer.parseInt(System.getProperty("net.sourceforge.pmd.http.timeout", "5000"));
24 } catch (NumberFormatException e) {
25 e.printStackTrace();
26 }
27 TIMEOUT = timeoutProperty;
28 }
29
30
31
32
33
34 private ResourceLoader() {
35 }
36
37
38
39
40
41
42
43
44
45 public static InputStream loadResourceAsStream(String name) throws RuleSetNotFoundException {
46 InputStream stream = loadResourceAsStream(name, ResourceLoader.class.getClassLoader());
47 if (stream == null) {
48 throw new RuleSetNotFoundException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
49 }
50 return stream;
51 }
52
53
54
55
56
57
58
59
60
61 public static InputStream loadResourceAsStream(String name, ClassLoader loader) throws RuleSetNotFoundException {
62 File file = new File(name);
63 if (file.exists()) {
64 try {
65 return new FileInputStream(file);
66 } catch (FileNotFoundException e) {
67
68 }
69 } else {
70 try {
71 HttpURLConnection connection = (HttpURLConnection)new URL(name).openConnection();
72 connection.setConnectTimeout(TIMEOUT);
73 connection.setReadTimeout(TIMEOUT);
74 return connection.getInputStream();
75 } catch (Exception e) {
76 return loader.getResourceAsStream(name);
77 }
78 }
79 throw new RuleSetNotFoundException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
80 }
81 }