-
Notifications
You must be signed in to change notification settings - Fork 127
/
MicroService.java
876 lines (826 loc) · 34.1 KB
/
MicroService.java
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
/*
* Copyright (c) 2016 - 2018 Eric Lange
*
* Distributed under the MIT License. See LICENSE.md at
* https://github.com/LiquidPlayer/LiquidCore for terms and conditions.
*/
package org.liquidplayer.service;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.liquidplayer.javascript.JSContext;
import org.liquidplayer.javascript.JSException;
import org.liquidplayer.javascript.JSFunction;
import org.liquidplayer.javascript.JSON;
import org.liquidplayer.javascript.JSObject;
import org.liquidplayer.javascript.JSValue;
import org.liquidplayer.node.Process;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
/**
* A MicroService is the basic building block of LiquidCore. It encapsulates the runtime
* environment for a client-side micro app. A MicroService is a complete virtual machine
* whose operation is defined by the code referenced by the service URI. When a MicroService
* is instantiated, its Node.js environment is set up, its code downloaded (or fetched from cache)
* from the URI, and is executed in a VM. The host may interact with the VM via a simple
* message-based API.
*/
public class MicroService implements Process.EventListener {
/**
* Listens for a specific event emitted by the MicroService
*/
public interface EventListener {
/**
* Called asynchronously when the MicroService javascript code calls 'LiquidCore.emit()'
* @param service The MicroService which emitted the event
* @param event The event id
* @param payload A JSON data object emitted by the MicroService
*/
void onEvent(MicroService service, String event, JSONObject payload);
}
/**
* Listens for when the MicroService has been inititialized and the environment is ready
* to receive event listeners. This is called after the Node.js environment has been set
* up, but before the MicroService code has been executed. It is safe to add any event
* listeners here, but emitted events will not be seen by the MicroService until its code
* has been run. The MicroService should emit an event to let the host know that it is ready
* to receive events.
*/
public interface ServiceStartListener {
/**
* Called after the environment is set up, but before the MicroService javascript is
* executed.
* @param service The MicroService which is now started
*/
void onStart(MicroService service);
}
/**
* Listens for when the MicroService has exited gracefully. The MicroService is no longer
* available and is shutting down.
*/
public interface ServiceExitListener {
/**
* Called immediately before the MicroService exits. This is a graceful exit, and is
* mutually exclusive with the ServiceErrorListener. Only one of either the exit listener
* or error listener will be called from any MicroService.
* @param service The MicroService which is shutting down
* @param exitCode The code returned by the Node.js process
*/
void onExit(MicroService service, Integer exitCode);
}
/**
* Listens for any errors that may cause the MicroService to shut down unexpectedly. The
* MicroService is no longer available and may have already crashed.
*/
public interface ServiceErrorListener {
/**
* Called upon an exception state. This is an unexpected exit, and is
* mutually exclusive with the ServiceExitListener. Only one of either the exit listener
* or error listener will be called from any MicroService.
* @param service The MicroService which failed
* @param e The thrown exception
*/
void onError(MicroService service, Exception e);
}
/**
* This runtime exception is thrown if an attempt is made to re-start a MicroService if it
* has already been started. A MicroService instance may be executed only once.
*/
public class ServiceAlreadyStartedError extends RuntimeException {
}
/**
* Generates a URI for fetching from a development server on the loopback address (10.0.2.2).
* @param fileName The name of the bundled javascript file to fetch (default: liquid.js)
* @param port The server's port (default: 8082)
* @return A service URI for use in the MicroService constructor
*/
public static URI DevServer(@Nullable String fileName, @Nullable Integer port) {
if (fileName == null) {
fileName = "liquid.js";
}
if (port == null) {
port = 8082;
}
if (fileName.endsWith(".js"))
fileName = fileName.substring(0,fileName.length()-3);
if (!fileName.endsWith((".bundle"))) {
fileName = fileName.concat(".bundle");
}
return URI.create("http://10.0.2.2:" + port + "/" + fileName + "?platform=android&dev=true");
}
/**
* Generates a URI for fetching from a development server on the loopback address (10.0.2.2).
* Assumes the entry js file is 'liquid.js' and is served from port 8082 on the emulator's host
* machine.
* @return A service URI for use in the MicroService constructor
*/
public static URI DevServer() {
return DevServer(null, null);
}
private ServiceStartListener startListener;
private ServiceExitListener exitListener;
private ServiceErrorListener errorListener;
private final URI serviceURI;
private String serviceId;
private final Context androidCtx;
private final String uuid;
private String [] argv;
private String module;
private JSObject emitter;
private JSFunction safeStringify;
private boolean started = false;
private Process process;
/**
* Creates a new instance of the MicroService referenced by serviceURI
* @param ctx The android context of this app
* @param serviceURI The URI (can be a network URL or local file/resource) of the MicroService
* code
* @param start The ServiceStartListener (optional)
* @param error The ServiceErrorListener (optional)
* @param exit The ServiceExitListener (optional)
*/
public MicroService(Context ctx, URI serviceURI, ServiceStartListener start,
ServiceErrorListener error, ServiceExitListener exit) {
this.serviceURI = serviceURI;
try {
this.serviceId = URLEncoder.encode(
serviceURI.toString().substring(0,serviceURI.toString().lastIndexOf('/')), "UTF-8");
} catch (UnsupportedEncodingException e) {
android.util.Log.e("MicrosService", e.toString());
}
this.startListener = start;
this.exitListener = exit;
this.errorListener = error;
this.androidCtx = ctx;
uuid = UUID.randomUUID().toString();
serviceMap.put(uuid, this);
}
/**
* Creates a new instance of the MicroService referenced by serviceURI
* @param ctx The android context of this app
* @param serviceURI The URI (can be a network URL or local file/resource) of the MicroService
* code
* @param start The ServiceStartListener (optional)
* @param error The ServiceErrorListener (optional)
*/
public MicroService(Context ctx, URI serviceURI, ServiceStartListener start,
ServiceErrorListener error) {
this(ctx,serviceURI,start,error,null);
}
/**
* Creates a new instance of the MicroService referenced by serviceURI
* @param ctx The android context of this app
* @param serviceURI The URI (can be a network URL or local file/resource) of the MicroService
* code
* @param start The ServiceStartListener (optional)
*/
public MicroService(Context ctx, URI serviceURI, ServiceStartListener start) {
this(ctx,serviceURI,start,null);
}
/**
* Creates a new instance of the MicroService referenced by serviceURI
* @param ctx The android context of this app
* @param serviceURI The URI (can be a network URL or local file/resource) of the MicroService
* code
*/
public MicroService(Context ctx, URI serviceURI) {
this(ctx,serviceURI,null);
}
private final Map<String, Map<EventListener, JSFunction>> listeners =
Collections.synchronizedMap(new HashMap<String,Map<EventListener,JSFunction>>());
private final Object listenersMutex = new Object();
/**
* Adds an event listener for an event triggered by 'LiquidCore.emit(event, payload)' in
* JavaScript. Example:
* <pre>{@code
* LiquidCore.emit('my_event', { stringData: 'foo', bar : 6 });
* }</pre>
* This will trigger the 'listener' added here, with the JavaScript object represented as a
* JSONObject payload.
* @param event The String event id
* @param listener The event listener
*/
public void addEventListener(final String event, final EventListener listener) {
final String safeStringifyBody = "" +
" function serializer(replacer, cycleReplacer) {\n" +
" var stack = [], keys = []\n" +
" if (cycleReplacer == null) cycleReplacer = function(key, value) {\n"+
" if (stack[0] === value) return '[Circular ~]'\n"+
" return'[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.')+']'\n"+
" }\n"+
" return function(key, value) {\n"+
" if (stack.length > 0) {\n"+
" var thisPos = stack.indexOf(this)\n"+
" ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)\n"+
" ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)\n"+
" if (~stack.indexOf(value))value=cycleReplacer.call(this, key, value)\n"+
" }\n"+
" else stack.push(value)\n"+
"\n" +
// Functions are converted to undefined, try and keep the consistency with the iOS version.
" if (typeof value === 'function') {\n" +
" value = {};\n" +
" }\n" +
"\n"+
" return replacer == null ? value : replacer.call(this, key, value)\n"+
" }\n"+
" }\n"+
" return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)\n";
if (emitter != null) {
if (safeStringify == null) {
safeStringify = new JSFunction(emitter.getContext(), "safeStringify",
safeStringifyBody,
"obj", "replacer", "spaces", "cycleReplacer");
}
JSFunction jsListener = new JSFunction(emitter.getContext(), "on") {
@SuppressWarnings("unused")
public void on(JSValue value) throws JSONException {
JSONObject o = null;
if (value != null && !value.isNull() && !value.isUndefined()) {
if (value.isArray()) {
JSONArray a = new JSONArray(safeStringify.call(null, value).toString());
o = new JSONObject();
o.put("_", a);
} else if (value.isNumber()) {
o = new JSONObject();
o.put("_", value.toNumber());
} else if (value.isBoolean()) {
o = new JSONObject() ;
o.put("_", value.toBoolean());
} else if (value.isDate()) {
o = new JSONObject();
// Convert to ISO8601 date String, same format as if it was a property in an object.
o.put("_", safeStringify.call(null, value).toString());
} else if (value.isObject()) {
// Convert objects and functions.
o = new JSONObject(safeStringify.call(null, value).toString());
} else {
o = new JSONObject();
o.put("_", value.toString());
}
}
listener.onEvent(MicroService.this, event, o);
}
};
synchronized (listenersMutex) {
Map<EventListener, JSFunction> eventMap = listeners.get(event);
if (eventMap == null) {
eventMap = Collections.synchronizedMap(new HashMap<EventListener,JSFunction>());
listeners.put(event, eventMap);
}
eventMap.put(listener, jsListener);
}
emitter.property("on").toFunction().call(emitter,event,jsListener);
}
}
/**
* Each MicroService instance is mapped to a unique String id. This id can be serialized
* in UIs and the instance retrieved by a call to MicroService.getService(id)
* @return The unique id of this instance
*/
public String getId() {
return uuid;
}
/**
* Returns the Node.js Process object.
* @return The Node.js Process object
*/
public Process getProcess() {
return process;
}
/**
* Returns the URI from which the service was started.
* @return The URI of the service
*/
public URI getServiceURI() { return serviceURI; }
/**
* Removes an EventListener previously added with addEventListener.
* @param event The event for which to unregister the listener
* @param listener The listener to unregister
*/
public void removeEventListener(String event, final EventListener listener) {
Map<EventListener, JSFunction> eventMap;
synchronized (listenersMutex) {
eventMap = listeners.get(event);
}
if (eventMap != null) {
JSFunction func;
synchronized (listenersMutex) {
func = eventMap.get(listener);
if (func != null) {
eventMap.remove(listener);
if (eventMap.size() == 0) {
listeners.remove(event);
}
}
}
if (emitter != null) {
emitter.property("removeListener").toFunction().call(emitter, event, func);
}
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(payload) {
* // Do something with the payload data
* console.log(payload.hello);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* JSONObject foo = new JSONObject();
* foo.putString("hello", "world");
* myService.emit("my_event", foo);
* }</pre>
* @param event The event to trigger
* @param payload The JSONObject data structure to emit
*/
public void emit(String event, JSONObject payload) {
if (emitter != null) {
JSValue o;
if (payload != null) {
o = JSON.parse(emitter.getContext(), payload.toString());
} else {
o = new JSValue(emitter.getContext());
}
emitter.property("emit").toFunction().call(emitter, event, o);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function() {
* console.log('Received my_event');
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event");
* }</pre>
* @param event The event to trigger
*/
public void emit(String event) {
emit(event, (JSONObject) null);
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event", 5);
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, Integer v) {
if (emitter != null) {
emitter.property("emit").toFunction().call(emitter, event, v);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event", 5L);
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, Long v) {
if (emitter != null) {
emitter.property("emit").toFunction().call(emitter, event, v);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event", 5.2f);
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, Float v) {
if (emitter != null) {
emitter.property("emit").toFunction().call(emitter, event, v);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event", 15.6);
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, Double v) {
if (emitter != null) {
emitter.property("emit").toFunction().call(emitter, event, v);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event", "foo");
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, String v) {
if (emitter != null) {
emitter.property("emit").toFunction().call(emitter, event, v);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* myService.emit("my_event", true);
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, Boolean v) {
if (emitter != null) {
emitter.property("emit").toFunction().call(emitter, event, v);
}
}
/**
* Emits an event that can be received by the JavaScript code, if the MicroService has
* registered a listener. Example:
* <pre>{@code
* LiquidCore.on('my_event', function(val) {
* console.log('Received: ' + val);
* });
* }</pre>
* On the Java side:
* <pre>{@code
* JSONArray a = new JSONArray();
* a.put(0);
* a.put("two");
* myService.emit("my_event", a);
* }</pre>
* @param event The event to trigger
* @param v value to send
*/
public void emit(String event, JSONArray v) {
if (emitter != null) {
JSValue o;
if (v != null) {
o = JSON.parse(emitter.getContext(), v.toString());
} else {
o = new JSValue(emitter.getContext());
}
emitter.property("emit").toFunction().call(emitter, event, o);
}
}
/**
* Starts the MicroService. This method will return immediately and initialization and
* startup will occur asynchronously in a separate thread. It will download the code from
* the service URI (if not cached), set the arguments in `process.argv` and execute the script.
* @param argv The list of arguments to sent to the MicroService. This is similar to running
* node from a command line. The first two arguments will be the application (node)
* followed by the local module code (/home/module/[service.js]. 'argv' arguments
* will then be appended in process.argv[2:]
*/
public synchronized void start(String ... argv) {
if (started) throw new ServiceAlreadyStartedError();
started = true;
this.argv = argv;
process = new Process(androidCtx, serviceId, Process.kMediaAccessPermissionsRW,
MicroService.this);
}
/**
* Uninstalls the MicroService from this host, and removes any global data associated with the
* service
* @param ctx The Android context
* @param serviceURI The URI of the service (should be the same URI that the service was started
* with)
*/
public static void uninstall(Context ctx, URI serviceURI) {
try {
String serviceId = URLEncoder.encode(
serviceURI.toString().substring(0,serviceURI.toString().lastIndexOf('/')), "UTF-8");
Process.uninstall(ctx,serviceId, Process.UninstallScope.Global);
} catch (UnsupportedEncodingException e) {
android.util.Log.e("MicrosService", e.toString());
}
}
private File getModulePath() {
final String suffix = "/__org.liquidplayer.node__/_" + serviceId;
String modules = androidCtx.getFilesDir().getAbsolutePath() + suffix + "/module";
return new File(modules);
}
private File getNodeModulesPath() {
final String suffix = "/__org.liquidplayer.node__/_" + serviceId;
String node_modules = androidCtx.getFilesDir().getAbsolutePath() + suffix + "/node_modules";
return new File(node_modules);
}
private void fetchService() throws IOException {
String path = serviceURI.getPath();
module = path.substring(path.lastIndexOf('/') + 1);
if (!module.endsWith(".js")) {
module = module + ".js";
}
File moduleF = new File(getModulePath().getAbsolutePath() + "/" + module);
long lastModified = moduleF.lastModified();
String scheme = serviceURI.getScheme();
InputStream in = null;
if ("http".equals(scheme) || "https".equals(scheme)) {
URL url = serviceURI.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
if (lastModified > 0) {
SimpleDateFormat sdf =
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
connection.setRequestProperty("If-Modified-Since",
sdf.format(new Date(lastModified)) + " GMT");
}
connection.setRequestProperty("Accept-Encoding", "gzip");
String version = org.liquidplayer.node.BuildConfig.VERSION_NAME;
String info = "Android; API " + Build.VERSION.SDK_INT;
String userAgent = "LiquidCore/" + version + " (" + info + ")";
android.util.Log.d("MicroService", "User-Agent : " + userAgent);
connection.setRequestProperty("User-Agent", userAgent);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
if (connection.getHeaderField("Content-Encoding") != null &&
connection.getHeaderField("Content-Encoding").equals("gzip")) {
in = new GZIPInputStream(connection.getInputStream());
} else {
in = connection.getInputStream();
}
} else if (responseCode != 304) { // 304 just means the file has not changed
android.util.Log.e("FileNotFound", "responseCode = " + responseCode);
throw new FileNotFoundException();
}
} else if ("jarfile".equals(scheme)) {
int loc = serviceURI.getPath().lastIndexOf("/");
ClassLoader loader = getClass().getClassLoader();
if (loader == null) {
throw new IOException("Failed to get class loader");
}
in = loader.getResourceAsStream(serviceURI.getPath().substring(loc+1));
} else {
if ("file".equals(scheme) && path.startsWith("/android_asset/")) {
// Open javascript file located in the android asset directory.
in = androidCtx.getAssets().open(path.substring(15));
} else {
in = androidCtx.getContentResolver().openInputStream(Uri.parse(serviceURI.toString()));
}
}
if (in != null) {
// Write file to /home/module
OutputStream out = new FileOutputStream(moduleF);
byte[] buf = new byte[16 * 1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
}
}
private static String canon(String name) {
name = name.replaceAll("[^a-zA-Z0-9]", "*");
StringBuilder canonical = new StringBuilder();
boolean nextCapital = true;
for (int i=0; i<name.length(); i++) {
if (name.substring(i,i+1).equals("*")) {
nextCapital = true;
} else {
char ch = name.charAt(i);
if (nextCapital && ch >= 'a' && ch <= 'z') {
ch = (char)('A' + ch - 'a');
}
nextCapital = false;
canonical.append(ch);
}
}
return canonical.toString();
}
@SuppressWarnings("unused")
private static void IGNORE_RESULT(boolean b) {}
@SuppressWarnings("unchecked")
private JSValue bindings(JSContext context, String module, JSFunction require) {
final int fndx = module.lastIndexOf('/');
final String fname = module.substring(fndx+1);
final int endx = fname.lastIndexOf('.');
final String ext = (endx >= 0) ? fname.substring(endx+1) : "";
final String moduleName = (endx<0) ? fname : fname.substring(0,endx);
if (!("node".equals(ext))) {
return require.call(null,module);
}
Class<? extends AddOn> addOnClass = AddOn.class;
try {
ClassLoader loader = getClass().getClassLoader();
if (loader == null) {
throw new IOException("Failed to get class loader");
}
Class klass = loader.loadClass("org.liquidplayer.addon." + canon(moduleName));
if (AddOn.class.isAssignableFrom(klass)) {
addOnClass = (Class<? extends AddOn>) klass;
AddOn addOn = addOnClass.getConstructor(Context.class).newInstance(androidCtx);
addOn.register(moduleName);
File node_module = new File(getNodeModulesPath() + "/" + fname);
if (!node_module.exists()) {
try {
IGNORE_RESULT(node_module.createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
}
JSValue binding = require.call(null, "/home/node_modules/" + fname);
addOn.require(binding, this);
return binding;
} else {
android.util.Log.e("LiquidCore.bindings", "Class " +
klass.getCanonicalName() +
" does not implement org.liquidplayer.service.AddOn");
}
} catch (JSException e) {
android.util.Log.e("LiquidCore.bindings", e.stack());
} catch (ClassNotFoundException e) {
android.util.Log.e("bindings", "Class org.liquidplayer.addon." + moduleName +
" not found.");
} catch (NoSuchMethodException e) {
android.util.Log.e("LiquidCore AddOn", "" + addOnClass.getCanonicalName() +
" must have a public constructor that takes os.android.Context as its lone parameter.");
} catch (IllegalAccessException e) {
android.util.Log.e("LiquidCore AddOn", "" + addOnClass.getCanonicalName() +
" must be public.");
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new JSValue(context);
}
@Override
public void onProcessStart(Process process, final JSContext context) {
// Create LiquidCore EventEmitter
emitter = context.evaluateScript(
"(()=>{\n" +
" class LiquidCore extends require('events') {}\n" +
" global.LiquidCore = new LiquidCore();\n" +
" return global.LiquidCore;" +
"})()"
).toObject();
// Override require() function to handle module binding
final JSValue require = context.property("require");
JSFunction bindings = new JSFunction(context,"bindings") {
@SuppressWarnings("unused") public JSValue bindings(String module) {
return MicroService.this.bindings(context, module, require.toFunction());
}
};
bindings.prototype(require);
context.property("require", bindings);
try {
fetchService();
// Notify host that service is ready to accept event listeners
if (startListener != null) {
startListener.onStart(this);
startListener = null;
}
// Construct process.argv
ArrayList<String> args = new ArrayList<>();
args.add("node");
args.add("/home/module/" + module);
if (argv != null) {
args.addAll(Arrays.asList(argv));
}
context.property("process").toObject().property("argv", args);
// Execute code
final String script =
"(()=>{" +
" const fs = require('fs'), vm = require('vm'); " +
" (new vm.Script(fs.readFileSync('/home/module/" + module + "'), "+
" {filename: '" + module + "'} )).runInThisContext();" +
"})()";
try {
context.evaluateScript(script);
} catch (JSException e) {
android.util.Log.e("JSEXCEPTION", "Unhandled exception: " + e.getError().toString());
android.util.Log.e("JSEXCEPTION", e.getError().stack());
}
} catch (IOException e) {
e.printStackTrace();
onProcessFailed(null, e);
}
}
static final private Map<String,MicroService> serviceMap =
Collections.synchronizedMap(new HashMap<String,MicroService>());
static final private Object serviceMapMutex = new Object();
private void clean() {
exitListener = null;
errorListener = null;
emitter = null;
synchronized (serviceMapMutex) {
for (Map.Entry<String, MicroService> entry : serviceMap.entrySet()) {
if (entry.getValue() == this) {
serviceMap.remove(entry.getKey());
process.removeEventListener(this);
break;
}
}
}
this.process = null;
}
@Override
public void onProcessAboutToExit(Process process, int exitCode) {
onProcessExit(process, exitCode);
}
@Override
public void onProcessExit(Process process, int exitCode) {
if (exitListener != null) {
exitListener.onExit(this, exitCode);
}
clean();
}
@Override
public void onProcessFailed(Process process, Exception error) {
if (errorListener != null) {
errorListener.onError(this, error);
}
clean();
}
/**
* Each MicroService instance is mapped to a unique String id. This id can be serialized
* in UIs and the instance retrieved by a call to MicroService.getService(id)
* @param id An id returned by MicroService.getId()
* @return The associated MicroService or null if no such service is active
*/
public static MicroService getService(String id) {
synchronized (serviceMapMutex) {
return serviceMap.get(id);
}
}
}