1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.trinidad.resource;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.InputStream;
23 import java.net.URL;
24 import java.io.IOException;
25 import java.net.URLConnection;
26 import java.net.URLStreamHandler;
27
28 public abstract class StringContentResourceLoader extends DynamicResourceLoader
29 {
30 public StringContentResourceLoader(String path)
31 {
32 super(path);
33 }
34
35 public StringContentResourceLoader(String path, ResourceLoader parent)
36 {
37 super(path, parent);
38 }
39
40 protected String getContentType(String path)
41 {
42 return "text";
43 }
44
45 protected abstract String getString(String path) throws IOException;
46
47 @Override
48 protected URL getURL(String path) throws IOException
49 {
50 return new URL("dynamic", null, -1, path, new StringContentURLStreamHandler(getString(path), getContentType(path)));
51 }
52
53
54
55
56
57
58 static private class StringContentURLStreamHandler extends URLStreamHandler
59 {
60
61
62
63
64
65
66
67 public StringContentURLStreamHandler(String content, String contentType)
68 {
69 _buff = content.getBytes();
70 _contentType = contentType;
71 }
72
73
74
75
76
77
78
79
80 @Override
81 protected URLConnection openConnection(URL u) throws IOException
82 {
83 return new StringContentURLConnection(u, _buff, _contentType);
84 }
85
86 private byte[] _buff;
87 private String _contentType;
88 }
89
90 static private class StringContentURLConnection extends URLConnection
91 {
92 public StringContentURLConnection(URL url, byte[] buff, String contentType)
93 {
94 super(url);
95 connected = false;
96 _buff = buff;
97 _contentType = contentType;
98 }
99
100 @Override
101 public void connect() throws IOException
102 {
103 connected = true;
104 }
105
106 @Override
107 public String getContentEncoding()
108 {
109
110 return null;
111 }
112
113 @Override
114 public int getContentLength()
115 {
116 return _buff.length;
117 }
118
119 @Override
120 public String getContentType()
121 {
122 return _contentType;
123 }
124
125 @Override
126 public String getHeaderField(String name)
127 {
128 if("content-encoding".equals(name))
129 {
130 return getContentEncoding();
131 }
132 else if ("content-length".equals(name))
133 {
134 return String.valueOf(getContentLength());
135 }
136 else if ("content-type".equals(name))
137 {
138 return getContentType();
139 }
140
141 return null;
142 }
143
144 @Override
145 public InputStream getInputStream() throws IOException
146 {
147 return new ByteArrayInputStream(_buff);
148 }
149
150 private byte[] _buff;
151 private String _contentType;
152 }
153 }