forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceLoader.java
More file actions
223 lines (204 loc) · 8.03 KB
/
ResourceLoader.java
File metadata and controls
223 lines (204 loc) · 8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package act.inject.util;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import act.Act;
import act.app.App;
import act.app.data.StringValueResolverManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.osgl.$;
import org.osgl.exception.UnexpectedException;
import org.osgl.inject.BeanSpec;
import org.osgl.inject.Genie;
import org.osgl.inject.Injector;
import org.osgl.inject.ValueLoader;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.storage.ISObject;
import org.osgl.storage.impl.SObject;
import org.osgl.util.E;
import org.osgl.util.IO;
import org.osgl.util.S;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
public class ResourceLoader<T> extends ValueLoader.Base<T> {
protected static final Logger LOGGER = LogManager.get(ResourceLoader.class);
protected Object resource;
@Override
protected void initialized() {
String path = (String) options.get("value");
E.unexpectedIf(S.blank(path), "resource path not specified");
boolean trimLeadingSlash = !(Boolean) options.get("skipTrimLeadingSlash");
while (trimLeadingSlash && path.startsWith("/")) {
path = path.substring(1);
}
E.unexpectedIf(S.blank(path), "resource path not specified");
resource = load(path, spec);
}
@Override
public T get() {
return (T) resource;
}
private static Injector injector = Genie.create();
/**
* A static method to load resource content
*
* If any exception encountered during resource load, this method returns `null`
*
* @param path the relative path to the resource
* @param type the return value type
* @param <T> generic type of return value
* @return loaded resource or `null` if exception encountered.
*/
public static <T> T load(String path, Class<T> type) {
return load(path, type, false);
}
public static <T> T load(String path, Class<T> type, boolean ignoreResourceNotFound) {
return load(path, BeanSpec.of(type, injector), ignoreResourceNotFound);
}
/**
* A static method to load resource content
*
* If any exception encountered during resource load, this method returns `null`
*
* @param path the relative path to the resource
* @param typeReference the return value type
* @param <T> generic type of return value
* @return loaded resource or `null` if exception encountered.
*/
public static <T> T load(String path, TypeReference<T> typeReference) {
return load(path, typeReference, false);
}
public static <T> T load(String path, TypeReference<T> typeReference, boolean ignoreResourceNotFound) {
BeanSpec spec = BeanSpec.of(typeReference.getType(), injector);
return load(path, spec, ignoreResourceNotFound);
}
/**
* Load resource content from given path into variable with
* type specified by `spec`.
*
* @param resourcePath the resource path
* @param spec {@link BeanSpec} specifies the return value type
* @return the resource content in a specified type or `null` if resource not found
* @throws UnexpectedException if return value type not supported
*/
public static <T> T load(String resourcePath, BeanSpec spec) {
return load(resourcePath, spec, false);
}
public static <T> T load(String resourcePath, BeanSpec spec, boolean ignoreResourceNotFound) {
return $.cast(_load(resourcePath, spec, ignoreResourceNotFound));
}
protected static Object _load(String resourcePath, BeanSpec spec, boolean ignoreResourceNotFound) {
URL url = loadResource(resourcePath);
if (null == url) {
if (!ignoreResourceNotFound) {
LOGGER.warn("resource not found: " + resourcePath);
}
return null;
}
boolean isJson = resourcePath.endsWith(".json");
Class<?> rawType = spec.rawType();
if (URL.class == rawType) {
return url;
} else if (String.class == rawType) {
return IO.readContentAsString(url);
} else if (byte[].class == rawType) {
return readContent(url);
} else if (List.class.equals(rawType)) {
List<Type> typeParams = spec.typeParams();
if (!typeParams.isEmpty()) {
if (String.class == typeParams.get(0)) {
return IO.readLines(url);
} else if (isJson) {
return JSON.parseObject(IO.readContentAsString(url), spec.type());
}
}
} else if (Collection.class.isAssignableFrom(rawType)) {
List<Type> typeParams = spec.typeParams();
if (!typeParams.isEmpty()) {
Collection col = (Collection)Act.getInstance(rawType);
if (String.class == typeParams.get(0)) {
col.addAll(IO.readLines(url));
return col;
} else {
StringValueResolverManager resolverManager = Act.app().resolverManager();
try {
Class componentType = spec.componentSpec().rawType();
List<String> stringList = IO.readLines(url);
for (String line : stringList) {
col.add(resolverManager.resolve(line, componentType));
}
} catch (RuntimeException e) {
throw new UnexpectedException("return type not supported: " + spec);
}
}
}
} else if (ByteBuffer.class == rawType) {
byte[] ba = readContent(url);
ByteBuffer buffer = ByteBuffer.allocateDirect(ba.length);
buffer.put(ba);
buffer.flip();
return buffer;
} else if (Path.class.isAssignableFrom(rawType)) {
try {
return Paths.get(url.toURI());
} catch (URISyntaxException exception) {
throw E.unexpected(exception);
}
} else if (File.class.isAssignableFrom(rawType)) {
return new File(url.getFile());
} else if (ISObject.class.isAssignableFrom(rawType)) {
return SObject.of(readContent(url));
} else if (InputStream.class == rawType) {
return IO.is(url);
} else if (Reader.class == rawType) {
return new InputStreamReader(IO.is(url));
}
if (isJson) {
return JSON.parseObject(IO.readContentAsString(url), spec.type());
}
try {
return Act.app().resolverManager().resolve(IO.readContentAsString(url), rawType);
} catch (RuntimeException e) {
throw new UnexpectedException("return type not supported: " + spec);
}
}
private static byte[] readContent(URL url) {
return IO.readContent(IO.is(url));
}
private static URL loadResource(String path) {
App app = Act.app();
if (null == app || null == app.classLoader()) {
return ResourceLoader.class.getClassLoader().getResource(path);
} else {
return app.classLoader().getResource(path);
}
}
}