1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.jdo.impl.enhancer.util;
18
19 import java.util.Set;
20 import java.util.Map;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Iterator;
24
25 import java.io.IOException;
26 import java.io.File;
27 import java.io.FileNotFoundException;
28 import java.io.PrintWriter;
29 import java.io.InputStream;
30 import java.io.FileInputStream;
31
32 import java.net.URL;
33
34
35 /***
36 * Searches resources among a set of files.
37 */
38 public class ListResourceLocator
39 extends ResourceLocatorBase
40 implements ResourceLocator
41 {
42 /***
43 * The map of jdo files.
44 */
45 final Map files = new HashMap();
46
47 /***
48 * Creates an intsance.
49 */
50 public ListResourceLocator(PrintWriter out,
51 boolean verbose,
52 List fileNames)
53 throws IOException
54 {
55 super(out, verbose);
56 affirm(fileNames != null);
57
58
59 for (Iterator i = fileNames.iterator(); i.hasNext();) {
60 final String s = (String)i.next();
61
62
63 final File file = new File(s).getCanonicalFile();
64 final URL url = file.toURL();
65 final String canonicalName = url.toString();
66 affirm(canonicalName != null);
67
68
69 if (!file.canRead()) {
70 final String msg
71 = getI18N("enhancer.cannot_read_resource",
72 file.toString());
73 throw new IOException(msg);
74 }
75
76
77 files.put(canonicalName, file);
78 printMessage(getI18N("enhancer.using_file",
79 canonicalName));
80 }
81 }
82
83 /***
84 * Finds a resource with a given name.
85 */
86 public InputStream getInputStreamForResource(String resourceName)
87 {
88
89
90 affirm(resourceName != null);
91
92 final Set entries = files.entrySet();
93 for (Iterator i = entries.iterator(); i.hasNext();) {
94 final Map.Entry entry = (Map.Entry)i.next();
95 final String fileName = (String)entry.getKey();
96 if (!fileName.endsWith(resourceName)) {
97 continue;
98 }
99 final File file = (File)entry.getValue();
100
101 final InputStream stream;
102 try {
103 stream = new FileInputStream(file);
104 } catch (FileNotFoundException ex) {
105
106
107 final String msg
108 = getI18N("enhancer.io_error_while_reading_resource",
109 file.toString(), ex.getMessage());
110 throw new RuntimeException(msg);
111 }
112 affirm(stream != null);
113 printMessage(getI18N("enhancer.found_resource", resourceName));
114 return stream;
115 }
116 printMessage(getI18N("enhancer.not_found_resource", resourceName));
117 return null;
118 }
119 }