-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathResourceManager.java
More file actions
72 lines (62 loc) · 2.44 KB
/
ResourceManager.java
File metadata and controls
72 lines (62 loc) · 2.44 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
package com.rntensorflow;
import android.content.res.Resources;
import android.webkit.URLUtil;
import com.facebook.react.bridge.ReactContext;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ResourceManager {
private ReactContext reactContext;
public ResourceManager(ReactContext reactContext) {
this.reactContext = reactContext;
}
public String loadResourceAsString(String resource) {
return new String(loadResource(resource));
}
public byte[] loadResource(String resource) {
if(resource.startsWith("file://")) {
return loadFromLocal(resource.substring(7));
} else if(URLUtil.isValidUrl(resource)) {
return loadFromUrl(resource);
} else {
return loadFromLocal(resource);
}
}
private byte[] loadFromLocal(String resource) {
try {
int identifier = reactContext.getResources().getIdentifier(resource, "drawable", reactContext.getPackageName());
InputStream inputStream = reactContext.getResources().openRawResource(identifier);
return inputStreamToByteArray(inputStream);
} catch (IOException | Resources.NotFoundException e) {
try {
InputStream inputStream = reactContext.getAssets().open(resource);
return inputStreamToByteArray(inputStream);
} catch (IOException e1) {
try {
InputStream inputStream = new FileInputStream(resource);
return inputStreamToByteArray(inputStream);
} catch (IOException e2) {
throw new IllegalArgumentException("Could not load resource");
}
}
}
}
private byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
byte[] b = new byte[inputStream.available()];
inputStream.read(b);
return b;
}
private byte[] loadFromUrl(String url) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).get().build();
Response response = client.newCall(request).execute();
return response.body().bytes();
} catch (IOException e) {
throw new IllegalStateException("Could not fetch data from url " + url);
}
}
}