-
Notifications
You must be signed in to change notification settings - Fork 7
/
java_class_instance.rs
522 lines (448 loc) · 20.7 KB
/
java_class_instance.rs
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
use crate::node::extensions::java_call_result_ext::ToNapiValue;
use crate::node::extensions::java_type_ext::NapiToJava;
use crate::node::helpers::arg_convert::{call_context_to_java_args, call_results_to_args};
use crate::node::helpers::napi_error::{MapToNapiError, NapiError};
use crate::node::helpers::napi_ext::{load_napi_library, uv_run, uv_run_mode};
use crate::node::interface_proxy::proxies::interface_proxy_exists;
use crate::node::java::Java;
use crate::node::java_class_proxy::JavaClassProxy;
use crate::node::util::traits::UnwrapOrEmpty;
use futures::future;
use java_rs::java_call_result::JavaCallResult;
use java_rs::java_type::JavaType;
use java_rs::objects::class::GlobalJavaClass;
use java_rs::objects::object::GlobalJavaObject;
use napi::{
CallContext, Callback, Env, JsBoolean, JsFunction, JsObject, JsUnknown, Property,
PropertyAttributes, Status,
};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
pub const CLASS_PROXY_PROPERTY: &str = "class.proxy";
pub const OBJECT_PROPERTY: &str = "class.object";
pub struct JavaClassInstance;
impl JavaClassInstance {
pub fn create_class_instance(
env: &Env,
proxy: Arc<JavaClassProxy>,
) -> napi::Result<JsFunction> {
let mut proxy_obj = env.create_object()?;
env.wrap(&mut proxy_obj, proxy.clone())?;
let mut constructor = env
.define_class("JavaClass", constructor as Callback, &[])?
.coerce_to_object()?;
constructor.set_named_property(CLASS_PROXY_PROPERTY, proxy_obj)?;
constructor.set_named_property(
"newInstanceAsync",
env.create_function("newInstanceAsync", new_instance as Callback)?,
)?;
constructor.define_properties(&[Property::new("class")?
.with_getter(get_class_field as Callback)
.with_property_attributes(PropertyAttributes::Enumerable)])?;
for method in &proxy.static_methods {
let name = method.0.clone();
let name_cpy = name.clone();
let name_async = name.clone() + proxy.config.async_suffix.unwrap_or_empty();
let name_sync = name.clone() + proxy.config.sync_suffix.unwrap_or_empty();
constructor.set_named_property(
name_sync.clone().as_str(),
env.create_function_from_closure(
name_sync.clone().as_str(),
move |ctx: CallContext| -> napi::Result<JsUnknown> {
Self::call_static_method(&ctx, &name_cpy)
},
)?,
)?;
constructor.set_named_property(
name_async.clone().as_str(),
env.create_function_from_closure(
name_async.as_str(),
move |ctx: CallContext| -> napi::Result<JsObject> {
Self::call_static_method_async(&ctx, &name)
},
)?,
)?;
}
constructor.define_properties(
(&proxy.static_fields)
.iter()
.map(|(name, field)| {
let name = name.clone();
let name_cpy = name.clone();
let mut property = Property::new(&name)?
.with_property_attributes(PropertyAttributes::Enumerable)
.with_getter_closure(move |env, this| {
let proxy_obj: JsObject =
this.get_named_property(CLASS_PROXY_PROPERTY)?;
let proxy: &Arc<JavaClassProxy> = env.unwrap(&proxy_obj)?;
let field = proxy
.get_static_field_by_name(name.as_str())
.map_napi_err()?;
let res = field.get_static().map_napi_err()?;
let j_env = proxy.vm.attach_thread().map_napi_err()?;
res.to_napi_value(&j_env, &env).map_napi_err()
});
if !field.is_final() {
property =
property.with_setter_closure(move |env, this, value: JsUnknown| {
let proxy_obj: JsObject =
this.get_named_property(CLASS_PROXY_PROPERTY)?;
let proxy: &Arc<JavaClassProxy> = env.unwrap(&proxy_obj)?;
let field =
proxy.get_static_field_by_name(&name_cpy).map_napi_err()?;
let field_type = field.get_type();
let j_env = proxy.vm.attach_thread().map_napi_err()?;
let val = field_type
.convert_to_java_value(&j_env, &env, value)
.map_napi_err()?;
field.set_static(val).map_napi_err()?;
Ok(())
});
}
Ok(property)
})
.collect::<napi::Result<Vec<_>>>()?
.as_ref(),
)?;
JsFunction::try_from(constructor.into_unknown())
}
pub fn from_existing(
proxy: Arc<JavaClassProxy>,
env: &Env,
instance: GlobalJavaObject,
) -> napi::Result<JsUnknown> {
let mut this = env.create_object()?;
let mut proxy_obj = env.create_object()?;
env.wrap(&mut proxy_obj, proxy.clone())?;
this.set_named_property(CLASS_PROXY_PROPERTY, proxy_obj)?;
JavaClassInstance::add_class_methods(env, &mut this, &proxy, instance)?;
Ok(this.into_unknown())
}
fn add_class_methods(
env: &Env,
this: &mut JsObject,
proxy: &Arc<JavaClassProxy>,
instance: GlobalJavaObject,
) -> napi::Result<()> {
let mut instance_obj = env.create_object()?;
env.wrap(&mut instance_obj, instance)?;
this.set_named_property(OBJECT_PROPERTY, instance_obj)?;
if proxy.config.custom_inspect {
Self::add_custom_inspect(env, this);
}
for method in &proxy.methods {
if method.0 == "toString" {
this.set_named_property(
"toString",
env.create_function_from_closure("toString", move |ctx: CallContext| {
Self::call_method(&ctx, &"toString".to_string())
}),
)?;
this.set_named_property(
"toStringSync",
env.create_function_from_closure("toStringSync", move |ctx: CallContext| {
Self::call_method(&ctx, &"toString".to_string())
}),
)?;
this.set_named_property(
"toStringAsync",
env.create_function_from_closure("toStringAsync", move |ctx: CallContext| {
Self::call_method_async(&ctx, &"toString".to_string())
}),
)?;
continue;
}
let name = method.0.clone();
let name_cpy = name.clone();
let name_async = name.clone() + proxy.config.async_suffix.unwrap_or_empty();
let name_sync = name.clone() + proxy.config.sync_suffix.unwrap_or_empty();
this.set_named_property(
name_sync.clone().as_str(),
env.create_function_from_closure(
name_sync.clone().as_str(),
move |ctx: CallContext| -> napi::Result<JsUnknown> {
Self::call_method(&ctx, &name_cpy)
},
)?,
)?;
this.set_named_property(
name_async.clone().as_str(),
env.create_function_from_closure(
name_async.as_str(),
move |ctx: CallContext| -> napi::Result<JsObject> {
Self::call_method_async(&ctx, &name)
},
)?,
)?;
}
this.define_properties(
(&proxy.fields)
.into_iter()
.map(|(name, field)| -> napi::Result<Property> {
let name = name.clone();
let name_cpy = name.clone();
let mut property = Property::new(name.clone().as_str())?
.with_property_attributes(PropertyAttributes::Enumerable)
.with_getter_closure(move |env, this| {
let proxy_obj: JsObject =
this.get_named_property(CLASS_PROXY_PROPERTY)?;
let instance_obj: JsObject =
this.get_named_property(OBJECT_PROPERTY)?;
let proxy: &Arc<JavaClassProxy> = env.unwrap(&proxy_obj)?;
let obj: &GlobalJavaObject = env.unwrap(&instance_obj)?;
let field = proxy
.get_field_by_name(name.clone().as_str())
.map_napi_err()?;
let res = field.get(obj).map_napi_err()?;
let j_env = proxy.vm.attach_thread().map_napi_err()?;
res.to_napi_value(&j_env, &env).map_napi_err()
});
if !field.is_final() {
property = property.with_setter_closure(move |env, this, value| {
let proxy_obj: JsObject =
this.get_named_property(CLASS_PROXY_PROPERTY)?;
let instance_obj: JsObject =
this.get_named_property(OBJECT_PROPERTY)?;
let proxy: &Arc<JavaClassProxy> = env.unwrap(&proxy_obj)?;
let obj: &GlobalJavaObject = env.unwrap(&instance_obj)?;
let field =
proxy.get_field_by_name(name_cpy.as_str()).map_napi_err()?;
let field_type = field.get_type();
let j_env = proxy.vm.attach_thread().map_napi_err()?;
let val = field_type
.convert_to_java_value(&j_env, &env, value)
.map_napi_err()?;
field.set(obj, val).map_napi_err()
});
}
Ok(property)
})
.collect::<napi::Result<Vec<_>>>()?
.as_ref(),
)?;
if !proxy.methods.contains_key("instanceOf") {
this.set_named_property(
"instanceOf",
env.create_function_from_closure(
"instanceOf",
|ctx: CallContext| -> napi::Result<JsBoolean> {
let proxy = Self::get_class_proxy(&ctx, false)?;
let env = proxy.vm.attach_thread().map_napi_err()?;
let res = Java::_is_instance_of(env, ctx.env, ctx.this()?, ctx.get(0)?)?;
ctx.env.get_boolean(res)
},
)?,
)?;
}
Ok(())
}
fn get_class_proxy<'a>(
ctx: &'a CallContext,
is_static: bool,
) -> napi::Result<&'a Arc<JavaClassProxy>> {
let this: JsObject = if is_static {
ctx.this::<JsFunction>()?.coerce_to_object()?
} else {
ctx.this()?
};
let proxy_obj: JsObject = this.get_named_property(CLASS_PROXY_PROPERTY)?;
Ok(ctx.env.unwrap(&proxy_obj)?)
}
fn get_object<'a>(ctx: &'a CallContext) -> napi::Result<&'a GlobalJavaObject> {
let this: JsObject = ctx.this()?;
let object_obj: JsObject = this.get_named_property(OBJECT_PROPERTY)?;
Ok(ctx.env.unwrap(&object_obj)?)
}
fn call_static_method(ctx: &CallContext, name: &String) -> napi::Result<JsUnknown> {
let proxy = Self::get_class_proxy(ctx, true)?;
let method = proxy
.find_matching_method(ctx, name, true, false)
.or_else(|_| proxy.find_matching_method(ctx, name, true, true))
.map_napi_err()?;
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(ctx, method.parameter_types(), &env)?;
let args_ref = call_results_to_args(&args);
let res = method.call_static(args_ref.as_slice()).map_napi_err()?;
res.to_napi_value(&env, ctx.env).map_napi_err()
}
fn call_static_method_async(ctx: &CallContext, name: &String) -> napi::Result<JsObject> {
let proxy = Self::get_class_proxy(ctx, true)?.clone();
let method = proxy
.find_matching_method(ctx, name, true, false)
.or_else(|_| proxy.find_matching_method(ctx, name, true, true))
.map_napi_err()?
.clone();
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(ctx, method.parameter_types(), &env)?;
ctx.env.execute_tokio_future(
futures::future::lazy(move |_| {
let args_ref = call_results_to_args(&args);
method.call_static(args_ref.as_slice()).map_napi_err()
}),
move |&mut env, res| {
let j_env = proxy.vm.attach_thread().map_napi_err()?;
res.to_napi_value(&j_env, &env).map_napi_err()
},
)
}
fn call_method(ctx: &CallContext, name: &String) -> napi::Result<JsUnknown> {
let proxy = Self::get_class_proxy(ctx, false)?;
let method = proxy
.find_matching_method(ctx, name, false, false)
.or_else(|_| proxy.find_matching_method(ctx, name, false, true))
.map_napi_err()?;
let obj = Self::get_object(ctx)?;
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(ctx, method.parameter_types(), &env)?;
let result = if proxy.config.run_event_loop_when_interface_proxy_is_active
&& interface_proxy_exists()
{
// If the call context contains an interface proxy, we need to call the method
// on a different thread as calling it on the same thread may cause a deadlock.
// Additionally, we need to run the event loop to allow the javascript thread to
// run the callback.
let cloned_obj = obj.clone();
let cloned_method = method.clone();
// Load the uv_run function from the uv library
load_napi_library();
let handle = thread::spawn(move || -> napi::Result<JavaCallResult> {
let args_ref = call_results_to_args(&args);
cloned_method
.call(&cloned_obj, args_ref.as_slice())
.map_napi_err()
});
while !handle.is_finished() {
unsafe {
uv_run(ctx.env.get_uv_event_loop()?, uv_run_mode::UV_RUN_NOWAIT);
}
thread::sleep(Duration::from_millis(10));
}
handle
.join()
.map_err(|_| NapiError::from("Failed to join thread").into_napi())??
} else {
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(ctx, method.parameter_types(), &env)?;
let args_ref = call_results_to_args(&args);
method.call(&obj, args_ref.as_slice()).map_napi_err()?
};
result.to_napi_value(&env, ctx.env).map_napi_err()
}
fn call_method_async(ctx: &CallContext, name: &String) -> napi::Result<JsObject> {
let proxy = Self::get_class_proxy(ctx, false)?.clone();
let method = proxy
.find_matching_method(ctx, name, false, false)
.or_else(|_| proxy.find_matching_method(ctx, name, false, true))
.map_napi_err()?
.clone();
let obj = Self::get_object(ctx)?.clone();
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(ctx, method.parameter_types(), &env)?;
ctx.env.execute_tokio_future(
futures::future::lazy(move |_| {
let args_ref = call_results_to_args(&args);
Ok(method.call(&obj, args_ref.as_slice()).map_napi_err()?)
}),
move |&mut env, res| {
let j_env = proxy.vm.attach_thread().map_napi_err()?;
res.to_napi_value(&j_env, &env).map_napi_err()
},
)
}
fn add_custom_inspect(env: &Env, this: &mut JsObject) -> Option<()> {
let custom = env
.get_global()
.ok()?
.get_named_property::<JsObject>("Symbol")
.ok()?
.get_named_property::<JsFunction>("for")
.ok()?
.call(
None,
&[env.create_string("nodejs.util.inspect.custom").ok()?],
)
.ok()?;
this.set_property(
custom,
env.create_function_from_closure(
"custom",
|ctx: CallContext| -> napi::Result<JsUnknown> {
let proxy = Self::get_class_proxy(&ctx, false)?;
let method = proxy
.methods
.get("toString")
.ok_or(napi::Error::from_reason("Method toString not found"))?
.iter()
.find(|m| m.parameter_types().len() == 0)
.ok_or(napi::Error::from_reason("Method toString not found"))?;
let obj = Self::get_object(&ctx)?;
let env = proxy.vm.attach_thread().map_napi_err()?;
let res = method.call(&obj, &[]).map_napi_err()?;
res.to_napi_value(&env, &ctx.env).map_napi_err()
},
)
.ok()?,
)
.ok()
}
}
#[js_function(255usize)]
fn constructor(ctx: CallContext) -> napi::Result<JsUnknown> {
let new_target_func = ctx.get_new_target::<JsFunction>();
if new_target_func.is_err() {
return Err(napi::Error::new(Status::Unknown, "Could not get the new target function, did you forget to add the 'new' keyword before this constructor call?".to_string()));
}
let new_target: JsObject = new_target_func.unwrap().coerce_to_object()?;
let mut this: JsObject = ctx.this()?;
let proxy_obj: JsObject = new_target.get_named_property(CLASS_PROXY_PROPERTY)?;
let proxy: &Arc<JavaClassProxy> = ctx.env.unwrap(&proxy_obj)?;
let constructor = proxy
.find_matching_constructor(&ctx, false)
.or_else(|_| proxy.find_matching_constructor(&ctx, true))
.map_napi_err()?;
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(&ctx, constructor.parameter_types(), &env)?;
let args_ref = call_results_to_args(&args);
let instance = constructor
.new_instance(args_ref.as_slice())
.map_napi_err()?;
this.set_named_property(CLASS_PROXY_PROPERTY, proxy_obj)?;
JavaClassInstance::add_class_methods(ctx.env, &mut this, proxy, instance)?;
Ok(ctx.env.get_undefined()?.into_unknown())
}
#[js_function(255usize)]
fn new_instance(ctx: CallContext) -> napi::Result<JsObject> {
let proxy = JavaClassInstance::get_class_proxy(&ctx, true)?.clone();
let constructor = proxy
.find_matching_constructor(&ctx, false)
.or_else(|_| proxy.find_matching_constructor(&ctx, true))
.map_napi_err()?
.clone();
let env = proxy.vm.attach_thread().map_napi_err()?;
let args = call_context_to_java_args(&ctx, constructor.parameter_types(), &env)?;
ctx.env.execute_tokio_future(
future::lazy(move |_| {
let args_ref = call_results_to_args(&args);
constructor.new_instance(args_ref.as_slice()).map_napi_err()
}),
move |env, instance| JavaClassInstance::from_existing(proxy.clone(), env, instance),
)
}
#[js_function(0usize)]
fn get_class_field(ctx: CallContext) -> napi::Result<JsObject> {
let cls: JsFunction = ctx.this()?;
let proxy_obj: JsObject = cls
.coerce_to_object()?
.get_named_property(CLASS_PROXY_PROPERTY)?;
let proxy: &Arc<JavaClassProxy> = ctx.env.unwrap(&proxy_obj)?;
let j_env = proxy.vm.attach_thread().map_napi_err()?;
let class = GlobalJavaClass::by_name(proxy.class_name.as_str(), &j_env).map_napi_err()?;
let res = JavaCallResult::Object {
object: class.into_object(),
signature: JavaType::new("java.lang.Class".to_string(), false),
};
res.to_napi_value(&j_env, &ctx.env)
.map_napi_err()?
.coerce_to_object()
}