1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.callbackparams.support;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.File;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URL;
25 import java.util.HashMap;
26 import java.util.Map;
27
28
29
30
31 public class ResourceMap {
32
33 private static final String tmpResourceDirProperty =
34 "callbackparams.temp.resources";
35 private static final File tmpResourceDir = setupTmpResourceDir();
36
37 private Map map = new HashMap();
38
39 public void put(Class rebytedClass, byte[] byteCode) {
40 map.put(asClassPathResourcePath(rebytedClass), byteCode);
41 }
42
43 public InputStream getAsStream(String name) {
44 Object resource = map.get(name);
45 if (null == resource) {
46 return null;
47
48 } else if (resource instanceof byte[]) {
49 return new ByteArrayInputStream((byte[])resource);
50
51 } else if (resource instanceof URL) {
52 try {
53 return ((URL) resource).openStream();
54 } catch (IOException ex) {
55 throw new Error(ex);
56 }
57
58 } else {
59 throw new Error("Unexpected resource-type: " + resource.getClass());
60 }
61 }
62
63 public URL getURL(String name) {
64 Object resource = map.get(name);
65
66 if (resource instanceof byte[]) {
67 resource = createTmpResourceFile((byte[])resource);
68 map.put(name, resource);
69 }
70
71 return (URL) resource;
72 }
73
74 private static String asClassPathResourcePath(Class classResource) {
75 return classResource.getName().replace('.', '/') + ".class";
76 }
77
78 private static URL createTmpResourceFile(byte[] b) {
79 FileOutputStream fos = null;
80 try {
81 String prefix = "org.callbackparams$";
82 String suffix = "class$rebyted";
83 File resourceFile = null == tmpResourceDir
84 ? File.createTempFile(prefix, suffix)
85 : File.createTempFile(prefix, suffix, tmpResourceDir);
86 resourceFile.deleteOnExit();
87 fos = new FileOutputStream(resourceFile);
88 fos.write(b);
89 return resourceFile.toURI().toURL();
90
91 } catch (IOException x) {
92 throw new Error(x);
93 } finally {
94 if (null != fos) {
95 try {
96 fos.close();
97 } catch (IOException ignore) {
98
99 }
100 }
101 }
102 }
103
104 private static File setupTmpResourceDir() {
105 String tmpResourceValue = System.getProperty(tmpResourceDirProperty);
106 if (null == tmpResourceValue) {
107 return null;
108 }
109
110 File resourceDir = new File(tmpResourceValue.trim());
111 if (resourceDir.isDirectory() || resourceDir.mkdirs()) {
112 return resourceDir;
113 } else {
114 return null;
115 }
116 }
117 }