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
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
// Copyright 2018 astonbitecode
//
// 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.

use std::{fs, mem};
use std::cell::RefCell;
use std::ops::Drop;
use std::os::raw::c_void;
use std::ptr;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Mutex;
use std::path::Path;

use jni_sys::{
    self,
    JavaVM,
    JavaVMInitArgs,
    JavaVMOption,
    jboolean,
    jclass,
    jint,
    jmethodID,
    JNI_EDETACHED,
    JNI_EEXIST,
    JNI_EINVAL,
    JNI_ENOMEM,
    JNI_ERR,
    JNI_EVERSION,
    JNI_FALSE,
    JNI_OK,
    JNI_TRUE,
    JNI_VERSION_1_8,
    JNIEnv,
    jobject,
    jobjectArray,
    jobjectRefType,
    jsize,
    jstring,
};
use libc::c_char;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json;

use crate::api_tweaks as tweaks;
use crate::errors;
use crate::utils;

use super::logger::{debug, error, info, warn};

// Initialize the environment
include!(concat!(env!("OUT_DIR"), "/j4rs_init.rs"));

type JniGetMethodId = unsafe extern "system" fn(*mut *const jni_sys::JNINativeInterface_, *mut jni_sys::_jobject, *const c_char, *const c_char) -> *mut jni_sys::_jmethodID;
type JniGetStaticMethodId = unsafe extern "system" fn(*mut *const jni_sys::JNINativeInterface_, *mut jni_sys::_jobject, *const c_char, *const c_char) -> *mut jni_sys::_jmethodID;
#[allow(non_snake_case)]
type JniNewObject = unsafe extern "C" fn(env: *mut JNIEnv, clazz: jclass, methodID: jmethodID, ...) -> jobject;
type JniNewStringUTF = unsafe extern "system" fn(env: *mut JNIEnv, utf: *const c_char) -> jstring;
#[allow(non_snake_case)]
type JniGetStringUTFChars = unsafe extern "system" fn(env: *mut JNIEnv, str: jstring, isCopy: *mut jboolean) -> *const c_char;
#[allow(non_snake_case)]
type JniCallObjectMethod = unsafe extern "C" fn(env: *mut JNIEnv, obj: jobject, methodID: jmethodID, ...) -> jobject;
#[allow(non_snake_case)]
type JniCallVoidMethod = unsafe extern "C" fn(env: *mut JNIEnv, obj: jobject, methodID: jmethodID, ...);
type JniCallStaticObjectMethod = unsafe extern "C" fn(env: *mut JNIEnv, obj: jobject, methodID: jmethodID, ...) -> jobject;
type JniNewObjectArray = unsafe extern "system" fn(env: *mut JNIEnv, len: jsize, clazz: jclass, init: jobject) -> jobjectArray;
type JniSetObjectArrayElement = unsafe extern "system" fn(*mut *const jni_sys::JNINativeInterface_, *mut jni_sys::_jobject, i32, *mut jni_sys::_jobject);
type JniExceptionCheck = unsafe extern "system" fn(_: *mut JNIEnv) -> jboolean;
type JniExceptionDescribe = unsafe extern "system" fn(_: *mut JNIEnv);
type JniExceptionClear = unsafe extern "system" fn(_: *mut JNIEnv);
type JniDeleteLocalRef = unsafe extern "system" fn(_: *mut JNIEnv, _: jobject) -> ();
type JniDeleteGlobalRef = unsafe extern "system" fn(_: *mut JNIEnv, _: jobject) -> ();
type JniNewGlobalRef = unsafe extern "system" fn(_: *mut JNIEnv, _: jobject) -> jobject;
pub type Callback = fn(Jvm, Instance) -> ();

const RUST: &'static str = "rust";
const JAVA: &'static str = "java";
const INST_CLASS_NAME: &'static str = "org/astonbitecode/j4rs/api/instantiation/NativeInstantiationImpl";
const INVO_IFACE_NAME: &'static str = "org/astonbitecode/j4rs/api/NativeInvocation";
const UNKNOWN_FOR_RUST: &'static str = "known_in_java_world";
const J4RS_ARRAY: &'static str = "org.astonbitecode.j4rs.api.dtos.Array";

lazy_static! {
    // Synchronize the creation of Jvm
    static ref MUTEX: Mutex<bool> = Mutex::new(false);
}

thread_local! {
    static JNI_ENV: RefCell<Option<*mut JNIEnv>> = RefCell::new(None);
    static ACTIVE_JVMS: RefCell<i32> = RefCell::new(0);
}

fn add_active_jvm() {
    ACTIVE_JVMS.with(|active_jvms| {
        let active_number = {
            *active_jvms.borrow() + 1
        };
        *active_jvms.borrow_mut() = active_number;
    });
}

fn remove_active_jvm() -> i32 {
    ACTIVE_JVMS.with(|active_jvms| {
        let active_number = {
            *active_jvms.borrow() - 1
        };
        *active_jvms.borrow_mut() = active_number;
        active_number
    })
}

fn set_thread_local_env(jni_env_opt: Option<*mut JNIEnv>) {
    JNI_ENV.with(|existing_jni_env_opt| {
        *existing_jni_env_opt.borrow_mut() = jni_env_opt;
    });
}

fn get_thread_local_env_opt() -> Option<*mut JNIEnv> {
    JNI_ENV.with(|existing_jni_env_opt| {
        match *existing_jni_env_opt.borrow() {
            Some(env) => Some(env.clone()),
            None => None,
        }
    })
}

fn get_thread_local_env() -> errors::Result<*mut JNIEnv> {
    match get_thread_local_env_opt() {
        Some(env) => Ok(env.clone()),
        None => Err(errors::J4RsError::JavaError(format!("Could not find the JNIEnv in the thread local"))),
    }
}

/// Holds the assets for the JVM
#[derive(Clone)]
pub struct Jvm {
    jni_env: *mut JNIEnv,
    jni_get_method_id: JniGetMethodId,
    jni_get_static_method_id: JniGetStaticMethodId,
    jni_new_object: JniNewObject,
    jni_new_string_utf: JniNewStringUTF,
    jni_get_string_utf_chars: JniGetStringUTFChars,
    jni_call_object_method: JniCallObjectMethod,
    jni_call_void_method: JniCallVoidMethod,
    jni_call_static_object_method: JniCallStaticObjectMethod,
    jni_new_onject_array: JniNewObjectArray,
    jni_set_object_array_element: JniSetObjectArrayElement,
    jni_exception_check: JniExceptionCheck,
    jni_exception_describe: JniExceptionDescribe,
    jni_exception_clear: JniExceptionClear,
    jni_delete_local_ref: JniDeleteLocalRef,
    jni_delete_global_ref: JniDeleteGlobalRef,
    jni_new_global_ref: JniNewGlobalRef,
    /// This is the factory class. It creates instances using reflection. Currently the `NativeInstantiationImpl`.
    factory_class: jclass,
    /// The constructor method of the `NativeInstantiationImpl`.
    factory_constructor_method: jmethodID,
    /// The method id of the `instantiate` method of the `NativeInvocation`.
    factory_instantiate_method: jmethodID,
    /// The method id of the `createForStatic` method of the `NativeInvocation`.
    factory_create_for_static_method: jmethodID,
    /// The `NativeInvocation` class.
    native_invocation_class: jclass,
    /// The Java class for the `InvocationArg`.
    invocation_arg_class: jclass,
    detach_thread_on_drop: bool,
}

impl Jvm {
    /// Creates a new Jvm.
    pub fn new(jvm_options: &[String], lib_name_to_load: Option<String>) -> errors::Result<Jvm> {
        Self::create_jvm(jvm_options, lib_name_to_load)
    }

    /// Attaches the current thread to an active JavaVM
    pub fn attach_thread() -> errors::Result<Jvm> {
        Self::create_jvm(&Vec::new(), None)
    }

    /// If true, the thread will not be detached when the Jvm is eing dropped.
    /// This is useful when creating a Jvm while on a Thread that is created in the Java world.
    /// When this Jvm is dropped, we don't want to detach the thread from the Java VM.
    ///
    /// It prevents errors like: `attempting to detach while still running code`
    pub fn detach_thread_on_drop(&mut self, detach: bool) {
        self.detach_thread_on_drop = detach;
    }

    /// Creates a new Jvm.
    /// If a JavaVM is already created by the current process, it attempts to attach the current thread to it.
    fn create_jvm(jvm_options: &[String], lib_name_to_load: Option<String>) -> errors::Result<Jvm> {
        debug("Creating a Jvm");
        let mut jvm: *mut JavaVM = ptr::null_mut();
        let mut jni_environment: *mut JNIEnv = ptr::null_mut();

        // Create the Jvm atomically
        let _g = MUTEX.lock().unwrap();

        let result = if let Some(env) = get_thread_local_env_opt() {
            info("A JVM is already created for this thread. Retrieving it...");
            jni_environment = env;

            JNI_OK
        } else {
            let created_vm = Self::get_created_vm();

            let res_int = if created_vm.is_some() {
                debug("A JVM is already created by another thread. Retrieving it...");
                jni_environment = created_vm.unwrap();

                JNI_OK
            } else {
                info("No JVMs exist. Creating a new one...");
                let mut jvm_options_vec: Vec<JavaVMOption> = jvm_options
                    .iter()
                    .map(|opt| {
                        JavaVMOption {
                            optionString: utils::to_java_string(opt),
                            extraInfo: ptr::null_mut() as *mut c_void,
                        }
                    })
                    .collect();

                let mut jvm_arguments = JavaVMInitArgs {
                    version: JNI_VERSION_1_8,
                    nOptions: jvm_options.len() as i32,
                    options: jvm_options_vec.as_mut_ptr(),
                    ignoreUnrecognized: JNI_FALSE,
                };

                tweaks::create_java_vm(
                    &mut jvm,
                    (&mut jni_environment as *mut *mut JNIEnv) as *mut *mut c_void,
                    (&mut jvm_arguments as *mut JavaVMInitArgs) as *mut c_void,
                )
            };

            res_int
        };

        if result != JNI_OK {
            let error_message = match result {
                JNI_EDETACHED => "thread detached from the JVM",
                JNI_EEXIST => "JVM already created",
                JNI_EINVAL => "invalid arguments",
                JNI_ENOMEM => "not enough memory",
                JNI_ERR => "unknown error",
                JNI_EVERSION => "JNI version error",
                _ => "unknown JNI error value",
            };

            Err(errors::J4RsError::JavaError(format!("Could not create the JVM: {}", error_message).to_string()))
        } else {
            let jvm = Self::try_from(jni_environment)?;
            if let Some(libname) = lib_name_to_load {
                // Pass to the Java world the name of the j4rs library.
                debug(&format!("Initializing NativeCallbackSupport with libname {}", libname));
                jvm.invoke_static("org.astonbitecode.j4rs.api.invocation.NativeCallbackToRustChannelSupport",
                                  "initialize",
                                  &vec![InvocationArg::from(libname)])?;
            }

            Ok(jvm)
        }
    }

    pub fn try_from(jni_environment: *mut JNIEnv) -> errors::Result<Jvm> {
        unsafe {
            match ((**jni_environment).GetMethodID,
                   (**jni_environment).GetStaticMethodID,
                   (**jni_environment).NewObject,
                   (**jni_environment).NewStringUTF,
                   (**jni_environment).GetStringUTFChars,
                   (**jni_environment).CallObjectMethod,
                   (**jni_environment).CallVoidMethod,
                   (**jni_environment).CallStaticObjectMethod,
                   (**jni_environment).NewObjectArray,
                   (**jni_environment).SetObjectArrayElement,
                   (**jni_environment).ExceptionCheck,
                   (**jni_environment).ExceptionDescribe,
                   (**jni_environment).ExceptionClear,
                   (**jni_environment).DeleteLocalRef,
                   (**jni_environment).DeleteGlobalRef,
                   (**jni_environment).NewGlobalRef) {
                (Some(gmid), Some(gsmid), Some(no), Some(nsu), Some(gsuc), Some(com), Some(cvm), Some(csom), Some(noa), Some(soae), Some(ec), Some(ed), Some(exclear), Some(dlr), Some(dgr), Some(ngr)) => {
                    // This is the factory class. It creates instances using reflection. Currently the `NativeInstantiationImpl`
                    let factory_class = tweaks::find_class(jni_environment, INST_CLASS_NAME);
                    // The constructor of `NativeInstantiationImpl`
                    let factory_constructor_method = (gmid)(
                        jni_environment,
                        factory_class,
                        utils::to_java_string("<init>"),
                        utils::to_java_string("()V"));
                    // The class of the `InvocationArg`
                    let invocation_arg_class = tweaks::find_class(
                        jni_environment,
                        "org/astonbitecode/j4rs/api/dtos/InvocationArg",
                    );
                    // `NativeInvocation` assets
                    let instantiate_method_signature = format!(
                        "(Ljava/lang/String;[Lorg/astonbitecode/j4rs/api/dtos/InvocationArg;)L{};",
                        INVO_IFACE_NAME);
                    let create_for_static_method_signature = format!(
                        "(Ljava/lang/String;)L{};",
                        INVO_IFACE_NAME);
                    // The method id of the `instantiate` method of the `NativeInvocation`
                    let factory_instantiate_method = (gsmid)(
                        jni_environment,
                        factory_class,
                        utils::to_java_string("instantiate"),
                        utils::to_java_string(&instantiate_method_signature),
                    );
                    // The method id of the `createForStatic` method of the `NativeInvocation`
                    let factory_create_for_static_method = (gsmid)(
                        jni_environment,
                        factory_class,
                        utils::to_java_string("createForStatic"),
                        utils::to_java_string(&create_for_static_method_signature),
                    );
                    // The `NativeInvocation class`
                    let native_invocation_class: jclass = tweaks::find_class(
                        jni_environment,
                        INVO_IFACE_NAME,
                    );

                    if (ec)(jni_environment) == JNI_TRUE {
                        (ed)(jni_environment);
                        (exclear)(jni_environment);
                        Err(errors::J4RsError::JavaError("The VM cannot be started... Please check the logs.".to_string()))
                    } else {
                        let jvm = Jvm {
                            jni_env: jni_environment,
                            jni_get_method_id: gmid,
                            jni_get_static_method_id: gsmid,
                            jni_new_object: no,
                            jni_new_string_utf: nsu,
                            jni_get_string_utf_chars: gsuc,
                            jni_call_object_method: com,
                            jni_call_void_method: cvm,
                            jni_call_static_object_method: csom,
                            jni_new_onject_array: noa,
                            jni_set_object_array_element: soae,
                            jni_exception_check: ec,
                            jni_exception_describe: ed,
                            jni_exception_clear: exclear,
                            jni_delete_local_ref: dlr,
                            jni_delete_global_ref: dgr,
                            jni_new_global_ref: ngr,
                            factory_class: factory_class,
                            factory_constructor_method: factory_constructor_method,
                            factory_instantiate_method: factory_instantiate_method,
                            factory_create_for_static_method: factory_create_for_static_method,
                            native_invocation_class: native_invocation_class,
                            invocation_arg_class: invocation_arg_class,
                            detach_thread_on_drop: true,
                        };

                        if get_thread_local_env_opt().is_none() {
                            set_thread_local_env(Some(jni_environment));
                        }
                        add_active_jvm();

                        Ok(jvm)
                    }
                }
                (_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _) => {
                    Err(errors::J4RsError::JniError(format!("Could not initialize the JVM: Error while trying to retrieve JNI functions.")))
                }
            }
        }
    }

    /// Creates an `Instance` of the class `class_name`, passing an array of `InvocationArg`s to construct the instance.
    pub fn create_instance(&self, class_name: &str, inv_args: &[InvocationArg]) -> errors::Result<Instance> {
        debug(&format!("Instantiating class {} using {} arguments", class_name, inv_args.len()));
        unsafe {
            // Factory invocation - first argument: create a jstring to pass as argument for the class_name
            let class_name_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(class_name),
            );
            // Factory invocation - rest of the arguments: Create a new objectarray of class InvocationArg
            let size = inv_args.len() as i32;
            let array_ptr = (self.jni_new_onject_array)(
                self.jni_env,
                size,
                self.invocation_arg_class,
                ptr::null_mut(),
            );
            // Factory invocation - rest of the arguments: populate the array
            for i in 0..size {
                // Create an InvocationArg Java Object
                let inv_arg_java = inv_args[i as usize].as_java_ptr(self);
                // Set it in the array
                (self.jni_set_object_array_element)(
                    self.jni_env,
                    array_ptr,
                    i,
                    inv_arg_java,
                );
            }
            // Call the method of the factory that instantiates a new class of `class_name`.
            // This returns a NativeInvocation that acts like a proxy to the Java world.
            let native_invocation_instance = (self.jni_call_static_object_method)(
                self.jni_env,
                self.factory_class,
                self.factory_instantiate_method,
                class_name_jstring,
                array_ptr,
            );

            let native_invocation_global_instance = create_global_ref_from_local_ref(native_invocation_instance, self.jni_env)?;

            // Create and return the Instance
            self.do_return(Instance {
                jinstance: native_invocation_global_instance,
                class_name: class_name.to_string(),
            })
        }
    }

    /// Invokes the method `method_name` of a created `Instance`, passing an array of `InvocationArg`s. It returns an `Instance` as the result of the invocation.
    pub fn invoke(&self, instance: &Instance, method_name: &str, inv_args: &[InvocationArg]) -> errors::Result<Instance> {
        debug(&format!("Invoking method {} of class {} using {} arguments", method_name, instance.class_name, inv_args.len()));
        unsafe {
            let invoke_method_signature = format!(
                "(Ljava/lang/String;[Lorg/astonbitecode/j4rs/api/dtos/InvocationArg;)L{};",
                INVO_IFACE_NAME);
            // Get the method ID for the `NativeInvocation.invoke`
            let invoke_method = (self.jni_get_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("invoke"),
                utils::to_java_string(invoke_method_signature.as_ref()),
            );

            // First argument: create a jstring to pass as argument for the method_name
            let method_name_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(method_name),
            );
            // Rest of the arguments: Create a new objectarray of class InvocationArg
            let size = inv_args.len() as i32;
            let array_ptr = (self.jni_new_onject_array)(
                self.jni_env,
                size,
                self.invocation_arg_class,
                ptr::null_mut(),
            );
            // Rest of the arguments: populate the array
            for i in 0..size {
                // Create an InvocationArg Java Object
                let inv_arg_java = inv_args[i as usize].as_java_ptr(self);
                // Set it in the array
                (self.jni_set_object_array_element)(
                    self.jni_env,
                    array_ptr,
                    i,
                    inv_arg_java,
                );
            }

            // Call the method of the instance
            let native_invocation_instance = (self.jni_call_object_method)(
                self.jni_env,
                instance.jinstance,
                invoke_method,
                method_name_jstring,
                array_ptr,
            );

            let native_invocation_global_instance = create_global_ref_from_local_ref(native_invocation_instance, self.jni_env)?;

            // Create and return the Instance
            self.do_return(Instance {
                jinstance: native_invocation_global_instance,
                class_name: UNKNOWN_FOR_RUST.to_string(),
            })
        }
    }


    /// Invokes asynchronously the method `method_name` of a created `Instance`, passing an array of `InvocationArg`s.
    /// It returns void and the `Instance` of the result of the async invocation will come in the defined callback.
    #[deprecated(since = "0.2.0", note = "please use `invoke_to_channel` instead")]
    pub fn invoke_async(&self, instance: &Instance, method_name: &str, inv_args: &[InvocationArg], callback: super::Callback) -> errors::Result<()> {
        debug(&format!("Asynchronously invoking method {} of class {} using {} arguments", method_name, instance.class_name, inv_args.len()));
        unsafe {
            let invoke_method_signature = "(JLjava/lang/String;[Lorg/astonbitecode/j4rs/api/dtos/InvocationArg;)V";
            // Get the method ID for the `NativeInvocation.invokeAsync`
            let invoke_method = (self.jni_get_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("invokeAsync"),
                utils::to_java_string(invoke_method_signature),
            );

            // First argument: the address of the callback function
            let address_string = format!("{:p}", callback as *const ());
            let address = i64::from_str_radix(&address_string[2..], 16).unwrap();
            // Second argument: create a jstring to pass as argument for the method_name
            let method_name_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(method_name),
            );
            // Rest of the arguments: Create a new objectarray of class InvocationArg
            let size = inv_args.len() as i32;
            let array_ptr = (self.jni_new_onject_array)(
                self.jni_env,
                size,
                self.invocation_arg_class,
                ptr::null_mut(),
            );
            // Rest of the arguments: populate the array
            for i in 0..size {
                // Create an InvocationArg Java Object
                let inv_arg_java = inv_args[i as usize].as_java_ptr(self);
                // Set it in the array
                (self.jni_set_object_array_element)(
                    self.jni_env,
                    array_ptr,
                    i,
                    inv_arg_java,
                );
            }

            // Call the method of the instance
            let _ = (self.jni_call_object_method)(
                self.jni_env,
                instance.jinstance,
                invoke_method,
                address,
                method_name_jstring,
                array_ptr,
            );

            // Create and return the Instance
            self.do_return(())
        }
    }

    /// Invokes the method `method_name` of a created `Instance`, passing an array of `InvocationArg`s.
    /// It returns a Result of `InstanceReceiver` that may be used to get an underlying `Receiver<Instance>`. The result of the invocation will come via this Receiver.
    pub fn invoke_to_channel(&self, instance: &Instance, method_name: &str, inv_args: &[InvocationArg]) -> errors::Result<InstanceReceiver> {
        debug(&format!("Invoking method {} of class {} using {} arguments. The result of the invocation will come via an InstanceReceiver", method_name, instance.class_name, inv_args.len()));
        unsafe {
            let invoke_method_signature = "(JLjava/lang/String;[Lorg/astonbitecode/j4rs/api/dtos/InvocationArg;)V";
            // Get the method ID for the `NativeInvocation.invokeToChannel`
            let invoke_method = (self.jni_get_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("invokeToChannel"),
                utils::to_java_string(invoke_method_signature),
            );

            // Create the channel
            let (sender, rx) = channel();
            let tx = Box::new(sender);
            // First argument: the address of the channel Sender
            let raw_ptr = Box::into_raw(tx);
            // Find the address of tx
            let address_string = format!("{:p}", raw_ptr);
            let address = i64::from_str_radix(&address_string[2..], 16).unwrap();

            // Second argument: create a jstring to pass as argument for the method_name
            let method_name_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(method_name),
            );
            // Rest of the arguments: Create a new objectarray of class InvocationArg
            let size = inv_args.len() as i32;
            let array_ptr = (self.jni_new_onject_array)(
                self.jni_env,
                size,
                self.invocation_arg_class,
                ptr::null_mut(),
            );
            // Rest of the arguments: populate the array
            for i in 0..size {
                // Create an InvocationArg Java Object
                let inv_arg_java = inv_args[i as usize].as_java_ptr(self);
                // Set it in the array
                (self.jni_set_object_array_element)(
                    self.jni_env,
                    array_ptr,
                    i,
                    inv_arg_java,
                );
            }

            // Call the method of the instance
            let _ = (self.jni_call_void_method)(
                self.jni_env,
                instance.jinstance,
                invoke_method,
                address,
                method_name_jstring,
                array_ptr,
            );

            // Create and return the Instance
            self.do_return(InstanceReceiver::new(rx, address))
        }
    }

    pub fn init_callback_channel(&self, instance: &Instance) -> errors::Result<InstanceReceiver> {
        debug(&format!("Initializing callback channel"));
        unsafe {
            let invoke_method_signature = "(J)V";
            // Get the method ID for the `NativeInvocation.initializeCallbackChannel`
            let invoke_method = (self.jni_get_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("initializeCallbackChannel"),
                utils::to_java_string(invoke_method_signature),
            );

            // Create the channel
            let (sender, rx) = channel();
            let tx = Box::new(sender);
            // First argument: the address of the channel Sender
            let raw_ptr = Box::into_raw(tx);
            // Find the address of tx
            let address_string = format!("{:p}", raw_ptr);
            let address = i64::from_str_radix(&address_string[2..], 16).unwrap();

            // Call the method of the instance
            let _ = (self.jni_call_void_method)(
                self.jni_env,
                instance.jinstance,
                invoke_method,
                address,
            );

            // Create and return the Instance
            self.do_return(InstanceReceiver::new(rx, address))
        }
    }

    /// Invokes the static method `method_name` of the class `class_name`, passing an array of `InvocationArg`s. It returns an `Instance` as the result of the invocation.
    pub fn invoke_static(&self, class_name: &str, method_name: &str, inv_args: &[InvocationArg]) -> errors::Result<Instance> {
        debug(&format!("Invoking static method {} of class {} using {} arguments", method_name, class_name, inv_args.len()));
        unsafe {
            // Factory invocation - first argument: create a jstring to pass as argument for the class_name
            let class_name_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(class_name),
            );
            // Call the method of the factory that creates a NativeInvocation for static calls to methods of class `class_name`.
            // This returns a NativeInvocation that acts like a proxy to the Java world.
            let native_invocation_instance = (self.jni_call_static_object_method)(
                self.jni_env,
                self.factory_class,
                self.factory_create_for_static_method,
                class_name_jstring,
            );

            // The invokeStatic method signature
            let invoke_static_method_signature = format!(
                "(Ljava/lang/String;[Lorg/astonbitecode/j4rs/api/dtos/InvocationArg;)L{};",
                INVO_IFACE_NAME);
            // Get the method ID for the `NativeInvocation.invokeStatic`
            let invoke_static_method = (self.jni_get_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("invokeStatic"),
                utils::to_java_string(invoke_static_method_signature.as_ref()),
            );

            // First argument: create a jstring to pass as argument for the method_name
            let method_name_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(method_name),
            );
            // Rest of the arguments: Create a new objectarray of class InvocationArg
            let size = inv_args.len() as i32;
            let array_ptr = (self.jni_new_onject_array)(
                self.jni_env,
                size,
                self.invocation_arg_class,
                ptr::null_mut(),
            );
            // Rest of the arguments: populate the array
            for i in 0..size {
                // Create an InvocationArg Java Object
                let inv_arg_java = inv_args[i as usize].as_java_ptr(self);
                // Set it in the array
                (self.jni_set_object_array_element)(
                    self.jni_env,
                    array_ptr,
                    i,
                    inv_arg_java,
                );
            }
            // Call the method of the instance
            let native_invocation_instance = (self.jni_call_object_method)(
                self.jni_env,
                native_invocation_instance,
                invoke_static_method,
                method_name_jstring,
                array_ptr,
            );

            let native_invocation_global_instance = create_global_ref_from_local_ref(native_invocation_instance, self.jni_env)?;

            // Create and return the Instance
            self.do_return(Instance::from(native_invocation_global_instance)?)
        }
    }

    /// Creates a clone of the provided Instance
    pub fn clone_instance(&self, instance: &Instance) -> errors::Result<Instance> {
        unsafe {
            // First argument is the jobject that is inside the instance

            // The clone method signature
            let clone_method_signature = format!(
                "(L{};)L{};",
                INVO_IFACE_NAME,
                INVO_IFACE_NAME);

            // Get the method ID for the `NativeInvocation.cast`
            let cast_static_method = (self.jni_get_static_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("cloneInstance"),
                utils::to_java_string(clone_method_signature.as_ref()),
            );

            // Call the clone method
            let native_invocation_instance = (self.jni_call_static_object_method)(
                self.jni_env,
                self.native_invocation_class,
                cast_static_method,
                instance.jinstance,
            );

            // Create and return the Instance
            self.do_return(Instance::from(native_invocation_instance)?)
        }
    }

    /// Invokes the static method `method_name` of the class `class_name`, passing an array of `InvocationArg`s. It returns an `Instance` as the result of the invocation.
    pub fn cast(&self, from_instance: &Instance, to_class: &str) -> errors::Result<Instance> {
        debug(&format!("Casting to class {}", to_class));
        unsafe {
            // First argument is the jobject that is inside the from_instance
            // Second argument: create a jstring to pass as argument for the to_class
            let to_class_jstring: jstring = (self.jni_new_string_utf)(
                self.jni_env,
                utils::to_java_string(to_class),
            );

            // The cast method signature
            let cast_method_signature = format!(
                "(L{};Ljava/lang/String;)L{};",
                INVO_IFACE_NAME,
                INVO_IFACE_NAME);

            // Get the method ID for the `NativeInvocation.cast`
            let cast_static_method = (self.jni_get_static_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("cast"),
                utils::to_java_string(cast_method_signature.as_ref()),
            );

            // Call the cast method
            let native_invocation_instance = (self.jni_call_static_object_method)(
                self.jni_env,
                self.native_invocation_class,
                cast_static_method,
                from_instance.jinstance,
                to_class_jstring,
            );

            // Create and return the Instance
            self.do_return(Instance::from(native_invocation_instance)?)
        }
    }

    /// Returns the Rust representation of the provided instance
    pub fn to_rust<T>(&self, instance: Instance) -> errors::Result<T> where T: DeserializeOwned {
        unsafe {
            debug("to_rust called");
            // The getJson method signature
            let get_json_method_signature = "()Ljava/lang/String;";

            // Get the method ID for the `NativeInvocation.getJson`
            let get_json_method = (self.jni_get_method_id)(
                self.jni_env,
                self.native_invocation_class,
                utils::to_java_string("getJson"),
                utils::to_java_string(get_json_method_signature.as_ref()),
            );

            debug("Invoking the getJson method");
            // Call the getJson method
            let json_instance = (self.jni_call_object_method)(
                self.jni_env,
                instance.jinstance,
                get_json_method,
            );
            let _ = self.do_return("")?;
            debug("Transforming jstring to rust String");
            let json = self.to_rust_string(json_instance as jstring)?;
            self.do_return(serde_json::from_str(&json)?)
        }
    }

    fn do_return<T>(&self, to_return: T) -> errors::Result<T> {
        unsafe {
            if (self.jni_exception_check)(self.jni_env) == JNI_TRUE {
                (self.jni_exception_describe)(self.jni_env);
                (self.jni_exception_clear)(self.jni_env);
                Err(errors::J4RsError::JavaError("An Exception was thrown by Java... Please check the logs or the console.".to_string()))
            } else {
                Ok(to_return)
            }
        }
    }

    // Retrieves a JNIEnv in the case that a JVM is already created even from another thread.
    fn get_created_vm() -> Option<*mut JNIEnv> {
        unsafe {
            // Get the number of the already created VMs. This is most probably 1, but we retrieve the number just in case...
            let mut created_vms_size: jsize = 0;
            tweaks::get_created_java_vms(&mut Vec::new(), 0, &mut created_vms_size);

            if created_vms_size == 0 {
                None
            } else {
                debug(&format!("Retrieving the first of {} created JVMs", created_vms_size));
                // Get the created VM
                let mut buffer: Vec<*mut JavaVM> = Vec::new();
                for _ in 0..created_vms_size { buffer.push(ptr::null_mut()); }

                let retjint = tweaks::get_created_java_vms(&mut buffer, created_vms_size, &mut created_vms_size);
                if retjint == JNI_OK {
                    match (**buffer[0]).AttachCurrentThread {
                        Some(act) => {
                            let mut jni_environment: *mut JNIEnv = ptr::null_mut();
                            (act)(
                                buffer[0],
                                (&mut jni_environment as *mut *mut JNIEnv) as *mut *mut c_void,
                                ptr::null_mut(),
                            );
                            Some(jni_environment)
                        }
                        None => {
                            error("Cannot attach the thread to the JVM");
                            None
                        }
                    }
                } else {
                    error(&format!("Error while retrieving the created JVMs: {}", retjint));
                    None
                }
            }
        }
    }

    fn detach_current_thread(&self) {
        unsafe {
            // Get the number of the already created VMs. This is most probably 1, but we retrieve the number just in case...
            let mut created_vms_size: jsize = 0;
            tweaks::get_created_java_vms(&mut Vec::new(), 0, &mut created_vms_size);

            if created_vms_size > 0 {
                // Get the created VM
                let mut buffer: Vec<*mut JavaVM> = Vec::new();
                for _ in 0..created_vms_size { buffer.push(ptr::null_mut()); }

                let retjint = tweaks::get_created_java_vms(&mut buffer, created_vms_size, &mut created_vms_size);
                if retjint == JNI_OK {
                    match (**buffer[0]).DetachCurrentThread {
                        Some(dct) => {
                            (dct)(buffer[0]);
                        }
                        None => {
                            warn("Cannot detach the thread from the JVM");
                        }
                    }
                } else {
                    warn(&format!("Error while retrieving the created JVMs: {}", retjint));
                }
            }
        }
    }

    pub fn to_rust_string(&self, java_string: jstring) -> errors::Result<String> {
        unsafe {
            let s = (self.jni_get_string_utf_chars)(
                self.jni_env,
                java_string,
                ptr::null_mut(),
            );
            let rust_string = utils::to_rust_string(s);
            self.do_return(rust_string)
        }
    }
}

impl Drop for Jvm {
    fn drop(&mut self) {
        if remove_active_jvm() <= 0 {
            if self.detach_thread_on_drop {
                debug("Detaching thread from the JVM");
                self.detach_current_thread();
            }
            set_thread_local_env(None);
        }
    }
}

/// A builder for Jvm
pub struct JvmBuilder<'a> {
    classpath_entries: Vec<ClasspathEntry<'a>>,
    java_opts: Vec<JavaOpt<'a>>,
    no_implicit_classpath: bool,
    detach_thread_on_drop: bool,
    lib_name_opt: Option<String>,
    skip_setting_native_lib: bool,
}

impl<'a> JvmBuilder<'a> {
    /// Creates a new JvmBuilder.
    pub fn new<'b>() -> JvmBuilder<'b> {
        JvmBuilder {
            classpath_entries: Vec::new(),
            java_opts: Vec::new(),
            no_implicit_classpath: false,
            detach_thread_on_drop: true,
            lib_name_opt: None,
            skip_setting_native_lib: false,
        }
    }

    /// Adds a classpath entry.
    pub fn classpath_entry(&'a mut self, cp_entry: ClasspathEntry<'a>) -> &'a mut JvmBuilder {
        self.classpath_entries.push(cp_entry);
        self
    }

    /// Adds classpath entries.
    pub fn classpath_entries(&'a mut self, cp_entries: Vec<ClasspathEntry<'a>>) -> &'a mut JvmBuilder {
        for cp_entry in cp_entries {
            self.classpath_entries.push(cp_entry);
        }
        self
    }

    /// Adds a Java option.
    pub fn java_opt(&'a mut self, opt: JavaOpt<'a>) -> &'a mut JvmBuilder {
        self.java_opts.push(opt);
        self
    }

    /// Adds Java options.
    pub fn java_opts(&'a mut self, opts: Vec<JavaOpt<'a>>) -> &'a mut JvmBuilder {
        for opt in opts {
            self.java_opts.push(opt);
        }
        self
    }

    /// By default, the created `Jvm`s include an implicit classpath entry that includes the j4rs jar.
    /// When `with_no_implicit_classpath()` is called, this classpath will not be added to the Jvm.
    pub fn with_no_implicit_classpath(&'a mut self) -> &'a mut JvmBuilder {
        self.no_implicit_classpath = true;
        self
    }

    /// When a Jvm goes out of scope and is being dropped, its current thread is being detached from the Java VM.
    /// A Jvm that is created with `detach_thread_on_drop(false)` will not detach the thread when being dropped.
    ///
    /// This is useful when in the Java world a native method is called and in the native code someone needs to create a j4rs Jvm.
    /// Id that Jvm detaches its current thread when being dropped, there will be problems for the Java world code to continue executing.
    pub fn detach_thread_on_drop(&'a mut self, detach_thread_on_drop: bool) -> &'a mut JvmBuilder {
        self.detach_thread_on_drop = detach_thread_on_drop;
        self
    }

    /// In the case that the j4rs is statically linked to some other library, the Java world (j4rs.jar) needs to load that
    /// library instead of the default one.
    ///
    /// This function defines the native library name to load.
    pub fn with_native_lib_name(&'a mut self, lib_name: &str) -> &'a mut JvmBuilder {
        self.lib_name_opt = Some(lib_name.to_string());
        self
    }

    /// Instructs the builder not to instruct the Java world j4rs code not to load the native library.
    /// (most probably because it is already loaded)
    pub fn skip_setting_native_lib(&'a mut self) -> &'a mut JvmBuilder {
        self.skip_setting_native_lib = true;
        self
    }

    /// Creates a Jvm
    pub fn build(&self) -> errors::Result<Jvm> {
        let classpath = if self.no_implicit_classpath {
            self.classpath_entries
                .iter()
                .fold(
                    ".".to_string(),
                    |all, elem| {
                        format!("{}{}{}", all, utils::classpath_sep(), elem.to_string())
                    })
        } else {
            // The default classpath contains the j4rs
            let jar_file_name = format!("j4rs-{}-jar-with-dependencies.jar", j4rs_version());
            let mut default_classpath_entry = std::env::current_exe()?;
            default_classpath_entry.pop();
            default_classpath_entry.push("jassets");
            default_classpath_entry.push(jar_file_name.clone());
            // Create a default classpath entry for the tests
            let mut tests_classpath_entry = std::env::current_exe()?;
            tests_classpath_entry.pop();
            tests_classpath_entry.pop();
            tests_classpath_entry.push("jassets");
            tests_classpath_entry.push(jar_file_name);

            let last_resort_classpath = format!("./jassets/j4rs-{}-jar-with-dependencies.jar", j4rs_version());
            let default_class_path = format!("-Djava.class.path={}{}{}",
                                             default_classpath_entry
                                                 .to_str()
                                                 .unwrap_or(&last_resort_classpath),
                                             utils::classpath_sep(),
                                             tests_classpath_entry
                                                 .to_str()
                                                 .unwrap_or(&last_resort_classpath));

            self.classpath_entries
                .iter()
                .fold(
                    default_class_path,
                    |all, elem| {
                        format!("{}{}{}", all, utils::classpath_sep(), elem.to_string())
                    })
        };
        info(&format!("Setting classpath to {}", classpath));

        // Populate the JVM Options
        let mut jvm_options = if self.no_implicit_classpath {
            vec![classpath]
        } else {
            let default_library_path = utils::java_library_path()?;
            info(&format!("Setting library path to {}", default_library_path));
            vec![classpath, default_library_path]
        };
        self.java_opts.clone().into_iter().for_each(|opt| jvm_options.push(opt.to_string()));

        let deps_dir = utils::deps_dir()?;
        // Pass to the Java world the name of the j4rs library.
        let lib_name_opt = if self.lib_name_opt.is_none() && !self.skip_setting_native_lib {
            let found_libs: Vec<String> = if Path::new(&deps_dir).exists() {
                fs::read_dir(deps_dir)?
                    .filter(|entry| {
                        entry.is_ok()
                    })
                    .filter(|entry| {
                        let entry = entry.as_ref().unwrap();
                        let file_name = entry.file_name();
                        let file_name = file_name.to_str().unwrap();
                        file_name.contains("j4rs") && (
                            file_name.contains(".so") ||
                                file_name.contains(".dll") ||
                                file_name.contains(".dylib"))
                    })
                    .map(|entry| entry.
                        unwrap().
                        file_name().
                        to_str().
                        unwrap().
                        to_owned())
                    .collect()
            } else {
                // If deps dir is not found, fallback to default naming in order for the library to be searched in the default
                // library locations of the system.
                let default_lib_name = if cfg!(windows) {
                    "l4rs.dll".to_string()
                } else {
                    "libj4rs.so".to_string()
                };
                info(&format!("Deps directory not found. Setting the library name to search to default: {}", default_lib_name));
                vec![default_lib_name]
            };

            let lib_name_opt = if found_libs.len() > 0 {
                let a_lib = found_libs[0].clone().replace("lib", "");

                let dot_splitted: Vec<&str> = a_lib.split(".").collect();
                let name = dot_splitted[0].to_string();
                info(&format!("Passing to the Java world the name of the library to load: {}", name));
                Some(name)
            } else {
                None
            };
            lib_name_opt
        } else if self.lib_name_opt.is_some() && !self.skip_setting_native_lib {
            let name = self.lib_name_opt.clone();
            info(&format!("Passing to the Java world the name of the library to load: {}", name.as_ref().unwrap()));
            name
        } else {
            None
        };

        Jvm::new(&jvm_options, lib_name_opt)
            .and_then(|mut jvm| {
                if !self.detach_thread_on_drop {
                    jvm.detach_thread_on_drop(false);
                }
                Ok(jvm)
            })
    }

    /// Creates a Jvm, similar with an already created j4rs Jvm.
    ///
    /// _Note: The already created Jvm is a j4rs Jvm, not a Java VM._
    pub fn already_initialized() -> errors::Result<Jvm> {
        Jvm::new(&Vec::new(), None)
    }
}

/// Struct that carries an argument that is used for method invocations in Java.
#[derive(Serialize)]
pub enum InvocationArg {
    /// An arg that is created in the Java world.
    Java {
        instance: Instance,
        class_name: String,
        arg_from: String,
    },
    // An arg that is created in the Rust world.
    Rust {
        json: String,
        class_name: String,
        arg_from: String,
    },
}

impl InvocationArg {
    /// Creates a InvocationArg::Rust.
    /// This is default for the Args that are created from the Rust code.
    pub fn new<T: ?Sized>(arg: &T, class_name: &str) -> InvocationArg
        where T: Serialize
    {
        let json = serde_json::to_string(arg).unwrap();
        InvocationArg::from((json.as_ref(), class_name))
    }

    /// Creates a `jobject` from this InvocationArg.
    pub fn as_java_ptr(&self, jvm: &Jvm) -> jobject {
        match self {
            _s @ &InvocationArg::Java { .. } => self.jobject_from_java(jvm),
            _s @ &InvocationArg::Rust { .. } => self.jobject_from_rust(jvm),
        }
    }

    fn jobject_from_rust(&self, jvm: &Jvm) -> jobject {
        unsafe {
            // The constructor of `InvocationArg` for Rust created args
            let inv_arg_rust_constructor_method = (jvm.jni_get_method_id)(
                jvm.jni_env,
                jvm.invocation_arg_class,
                utils::to_java_string("<init>"),
                utils::to_java_string("(Ljava/lang/String;Ljava/lang/String;)V"));

            let (class_name, json) = match self {
                _s @ &InvocationArg::Java { .. } => panic!("Called jobject_from_rust for an InvocationArg that is created by Java. Please consider opening a bug to the developers."),
                &InvocationArg::Rust { ref class_name, ref json, .. } => {
                    debug(&format!("Creating jobject from Rust for class {}", class_name));
                    (class_name.to_owned(), json.to_owned())
                }
            };

            debug(&format!("Calling the InvocationArg constructor with '{}'", class_name));
            let inv_arg_instance = (jvm.jni_new_object)(
                jvm.jni_env,
                jvm.invocation_arg_class,
                inv_arg_rust_constructor_method,
                // First argument: class_name
                (jvm.jni_new_string_utf)(
                    jvm.jni_env,
                    utils::to_java_string(class_name.as_ref()),
                ),
                // Second argument: json
                (jvm.jni_new_string_utf)(
                    jvm.jni_env,
                    utils::to_java_string(json.as_ref()),
                ),
            );

            inv_arg_instance
        }
    }

    fn jobject_from_java(&self, jvm: &Jvm) -> jobject {
        unsafe {
            let signature = format!("(Ljava/lang/String;L{};)V", INVO_IFACE_NAME);
            // The constructor of `InvocationArg` for Java created args
            let inv_arg_java_constructor_method = (jvm.jni_get_method_id)(
                jvm.jni_env,
                jvm.invocation_arg_class,
                utils::to_java_string("<init>"),
                utils::to_java_string(&signature));

            let (class_name, jinstance) = match self {
                _s @ &InvocationArg::Rust { .. } => panic!("Called jobject_from_java for an InvocationArg that is created by Rust. Please consider opening a bug to the developers."),
                &InvocationArg::Java { ref class_name, ref instance, .. } => {
                    debug(&format!("Creating jobject from Java for class {}", class_name));
                    (class_name.to_owned(), instance.jinstance)
                }
            };

            debug(&format!("Calling the InvocationArg constructor for class '{}'", class_name));

            let inv_arg_instance = (jvm.jni_new_object)(
                jvm.jni_env,
                jvm.invocation_arg_class,
                inv_arg_java_constructor_method,
                // First argument: class_name
                (jvm.jni_new_string_utf)(
                    jvm.jni_env,
                    utils::to_java_string(class_name.as_ref()),
                ),
                // Second argument: NativeInvocation instance
                jinstance,
            );

            inv_arg_instance
        }
    }
}

//impl Drop for InvocationArg {
//    fn drop(&mut self) {
////        delete_java_ref(self.jni_env, self.jinstance);
//    }
//}

impl<'a> From<(&'a str, &'a str)> for InvocationArg {
    fn from(tup: (&'a str, &'a str)) -> InvocationArg {
        InvocationArg::Rust {
            json: tup.0.to_string(),
            class_name: tup.1.to_string(),
            arg_from: RUST.to_string(),
        }
    }
}

impl From<Instance> for InvocationArg {
    fn from(instance: Instance) -> InvocationArg {
        let class_name = instance.class_name.to_owned();

        InvocationArg::Java {
            instance: instance,
            class_name: class_name,
            arg_from: JAVA.to_string(),
        }
    }
}

impl From<String> for InvocationArg {
    fn from(s: String) -> InvocationArg {
        InvocationArg::new(&s, "java.lang.String")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [String], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [String], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl<'a> From<&'a str> for InvocationArg {
    fn from(s: &str) -> InvocationArg {
        InvocationArg::new(s, "java.lang.String")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [&'a str], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [&'a str], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<bool> for InvocationArg {
    fn from(b: bool) -> InvocationArg {
        InvocationArg::new(&b, "java.lang.Boolean")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [bool], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [bool], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<i8> for InvocationArg {
    fn from(b: i8) -> InvocationArg {
        InvocationArg::new(&b, "java.lang.Byte")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [i8], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [i8], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<char> for InvocationArg {
    fn from(c: char) -> InvocationArg {
        InvocationArg::new(&c, "java.lang.Character")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [char], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [char], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<i16> for InvocationArg {
    fn from(i: i16) -> InvocationArg {
        InvocationArg::new(&i, "java.lang.Short")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [i16], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [i16], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<i32> for InvocationArg {
    fn from(i: i32) -> InvocationArg {
        InvocationArg::new(&i, "java.lang.Integer")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [i32], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [i32], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<i64> for InvocationArg {
    fn from(l: i64) -> InvocationArg {
        InvocationArg::new(&l, "java.lang.Long")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [i64], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [i64], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<f32> for InvocationArg {
    fn from(f: f32) -> InvocationArg {
        InvocationArg::new(&f, "java.lang.Float")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [f32], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [f32], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<f64> for InvocationArg {
    fn from(f: f64) -> InvocationArg {
        InvocationArg::new(&f, "java.lang.Double")
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b> From<(&'a [f64], &'b Jvm)> for InvocationArg {
    fn from(vec_t_tup: (&'a [f64], &'b Jvm)) -> InvocationArg {
        let (vec, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|&elem| InvocationArg::from(elem)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

// TODO: Use try_from when it becomes stable (Use ParseError in case of error)
impl<'a, 'b, T> From<(&'a [T], &'a str, &'b Jvm)> for InvocationArg where T: Serialize {
    fn from(vec_t_tup: (&'a [T], &'a str, &'b Jvm)) -> InvocationArg {
        let (vec, elements_class_name, jvm) = vec_t_tup;
        let args: Vec<InvocationArg> = vec.iter().map(|elem| InvocationArg::new(elem, elements_class_name)).collect();
        let wrapper_arg = InvocationArg::new(&args, J4RS_ARRAY);
        let res = jvm.invoke_static("java.util.Arrays", "asList", vec![wrapper_arg].as_slice());
        InvocationArg::from(res.unwrap())
    }
}

impl From<()> for InvocationArg {
    fn from(_: ()) -> InvocationArg {
        InvocationArg::new(&(), "void")
    }
}

impl<'a> From<&'a String> for InvocationArg {
    fn from(s: &String) -> InvocationArg {
        InvocationArg::new(s, "java.lang.String")
    }
}

impl<'a> From<&'a bool> for InvocationArg {
    fn from(b: &bool) -> InvocationArg {
        InvocationArg::new(b, "java.lang.Boolean")
    }
}

impl<'a> From<&'a i8> for InvocationArg {
    fn from(b: &i8) -> InvocationArg {
        InvocationArg::new(b, "java.lang.Byte")
    }
}

impl<'a> From<&'a char> for InvocationArg {
    fn from(c: &char) -> InvocationArg {
        InvocationArg::new(c, "java.lang.Character")
    }
}

impl<'a> From<&'a i16> for InvocationArg {
    fn from(i: &i16) -> InvocationArg {
        InvocationArg::new(i, "java.lang.Short")
    }
}

impl<'a> From<&'a i32> for InvocationArg {
    fn from(i: &i32) -> InvocationArg {
        InvocationArg::new(i, "java.lang.Integer")
    }
}

impl<'a> From<&'a i64> for InvocationArg {
    fn from(l: &i64) -> InvocationArg {
        InvocationArg::new(l, "java.lang.Long")
    }
}

impl<'a> From<&'a f32> for InvocationArg {
    fn from(f: &f32) -> InvocationArg {
        InvocationArg::new(f, "java.lang.Float")
    }
}

impl<'a> From<&'a f64> for InvocationArg {
    fn from(f: &f64) -> InvocationArg {
        InvocationArg::new(f, "java.lang.Double")
    }
}

/// A receiver for Java Instances.
///
/// It keeps a channel Receiver to get callback Instances from the Java world
/// and the address of a Box<Sender<Instance>> Box in the heap. This Box is used by Java to communicate
/// asynchronously Instances to Rust.
///
/// On Drop, the InstanceReceiver removes the Box from the heap.
pub struct InstanceReceiver {
    rx: Box<Receiver<Instance>>,
    tx_address: i64,
}

impl InstanceReceiver {
    fn new(rx: Receiver<Instance>, tx_address: i64) -> InstanceReceiver {
        InstanceReceiver {
            rx: Box::new(rx),
            tx_address,
        }
    }

    pub fn rx(&self) -> &Receiver<Instance> {
        &self.rx
    }
}

impl Drop for InstanceReceiver {
    fn drop(&mut self) {
        debug("Dropping an InstanceReceiver");
        let p = self.tx_address as *mut Sender<Instance>;
        unsafe {
            let tx = Box::from_raw(p);
            mem::drop(tx);
        }
    }
}

/// A Java instance
#[derive(Serialize)]
pub struct Instance {
    /// The name of the class of this instance
    class_name: String,
    /// The JNI jobject that manipulates this instance.
    ///
    /// This object is an instance of `org/astonbitecode/j4rs/api/NativeInvocation`
    #[serde(skip)]
    jinstance: jobject,
}

impl Instance {
    /// Returns the class name of this instance
    pub fn class_name(&self) -> &str {
        self.class_name.as_ref()
    }

    /// Consumes the Instance and returns its jobject
    pub fn java_object(self) -> jobject {
        self.jinstance
    }

    pub fn from(obj: jobject) -> errors::Result<Instance> {
        let _jvm = get_thread_local_env().map_err(|_| {
            Jvm::attach_thread()
        });

        let global = create_global_ref_from_local_ref(obj, get_thread_local_env()?)?;
        Ok(Instance {
            jinstance: global,
            class_name: UNKNOWN_FOR_RUST.to_string(),
        })
    }

    /// Creates a weak reference of this Instance.
    fn _weak_ref(&self) -> errors::Result<Instance> {
        Ok(Instance {
            class_name: self.class_name.clone(),
            jinstance: _create_weak_global_ref_from_global_ref(self.jinstance.clone(), get_thread_local_env()?)?,
        })
    }
}

impl Drop for Instance {
    fn drop(&mut self) {
        debug(&format!("Dropping an instance of {}", self.class_name));
        if let Some(j_env) = get_thread_local_env_opt() {
            delete_java_ref(j_env, self.jinstance);
        }
    }
}

unsafe impl Send for Instance {}

pub(crate) fn create_global_ref_from_local_ref(local_ref: jobject, jni_env: *mut JNIEnv) -> errors::Result<jobject> {
    unsafe {
        match ((**jni_env).NewGlobalRef,
               (**jni_env).DeleteLocalRef,
               (**jni_env).ExceptionCheck,
               (**jni_env).ExceptionDescribe,
               (**jni_env).ExceptionClear,
               (**jni_env).GetObjectRefType) {
            (Some(ngr), Some(dlr), Some(exc), Some(exd), Some(exclear), Some(gort)) => {
                // Create the global ref
                let global = ngr(
                    jni_env,
                    local_ref,
                );
                // If local ref, delete it
                if gort(jni_env, local_ref) as jint == jobjectRefType::JNILocalRefType as jint {
                    dlr(
                        jni_env,
                        local_ref,
                    );
                }
                // Exception check
                if (exc)(jni_env) == JNI_TRUE {
                    (exd)(jni_env);
                    (exclear)(jni_env);
                    Err(errors::J4RsError::JavaError("An Exception was thrown by Java while creating global ref... Please check the logs or the console.".to_string()))
                } else {
                    Ok(global)
                }
            }
            (_, _, _, _, _, _) => {
                Err(errors::J4RsError::JavaError("Could retrieve the native functions to create a global ref. This may lead to memory leaks".to_string()))
            }
        }
    }
}

fn _create_weak_global_ref_from_global_ref(global_ref: jobject, jni_env: *mut JNIEnv) -> errors::Result<jobject> {
    unsafe {
        match ((**jni_env).NewWeakGlobalRef,
               (**jni_env).ExceptionCheck,
               (**jni_env).ExceptionDescribe,
               (**jni_env).ExceptionClear) {
            (Some(nwgr), Some(exc), Some(exd), Some(exclear)) => {
                // Create the weak global ref
                let global = nwgr(
                    jni_env,
                    global_ref,
                );
                // Exception check
                if (exc)(jni_env) == JNI_TRUE {
                    (exd)(jni_env);
                    (exclear)(jni_env);
                    Err(errors::J4RsError::JavaError("An Exception was thrown by Java while creating a weak global ref... Please check the logs or the console.".to_string()))
                } else {
                    Ok(global)
                }
            }
            (_, _, _, _) => {
                Err(errors::J4RsError::JavaError("Could retrieve the native functions to create a weak global ref.".to_string()))
            }
        }
    }
}

/// Deletes the java ref from the memory
fn delete_java_ref(jni_env: *mut JNIEnv, jinstance: jobject) {
    unsafe {
        match ((**jni_env).DeleteGlobalRef,
               (**jni_env).ExceptionCheck,
               (**jni_env).ExceptionDescribe,
               (**jni_env).ExceptionClear) {
            (Some(dlr), Some(exc), Some(exd), Some(exclear)) => {
                dlr(
                    jni_env,
                    jinstance,
                );
                if (exc)(jni_env) == JNI_TRUE {
                    (exd)(jni_env);
                    (exclear)(jni_env);
                    error("An Exception was thrown by Java... Please check the logs or the console.");
                }
            }
            (_, _, _, _) => {
                error("Could retrieve the native functions to drop the Java ref. This may lead to memory leaks");
            }
        }
    }
}

/// A classpath entry.
#[derive(Debug, Clone)]
pub struct ClasspathEntry<'a> (&'a str);

impl<'a> ClasspathEntry<'a> {
    pub fn new(classpath_entry: &str) -> ClasspathEntry {
        ClasspathEntry(classpath_entry)
    }
}

impl<'a> ToString for ClasspathEntry<'a> {
    fn to_string(&self) -> String {
        self.0.to_string()
    }
}

/// A Java Option.
#[derive(Debug, Clone)]
pub struct JavaOpt<'a> (&'a str);

impl<'a> JavaOpt<'a> {
    pub fn new(java_opt: &str) -> JavaOpt {
        JavaOpt(java_opt)
    }
}

impl<'a> ToString for JavaOpt<'a> {
    fn to_string(&self) -> String {
        self.0.to_string()
    }
}

#[cfg(test)]
mod api_unit_tests {
    use serde_json;

    use super::{InvocationArg, JvmBuilder};

    #[test]
    fn jvm_builder() {
        let res = JvmBuilder::new().build();
        assert!(res.is_ok());
        let one_more_res = JvmBuilder::already_initialized();
        assert!(one_more_res.is_ok());
    }

    #[test]
    fn new_invocation_arg() {
        let _ = InvocationArg::new("something", "somethingelse");

        let gr = GuiResponse::ProvidedPassword { password: "passs".to_string(), number: 1 };
        let json = serde_json::to_string(&gr).unwrap();
        println!("{:?}", json);
        let res: Result<GuiResponse, _> = serde_json::from_str(&json);
        println!("{:?}", res);
    }

    #[derive(Serialize, Deserialize, Debug)]
    enum GuiResponse {
        ProvidedPassword { password: String, number: usize }
    }

    #[test]
    fn from_primitive_types() {
        validate_type(InvocationArg::from("str"), "java.lang.String");
        validate_type(InvocationArg::from("str".to_string()), "java.lang.String");
        validate_type(InvocationArg::from(true), "java.lang.Boolean");
        validate_type(InvocationArg::from(1_i8), "java.lang.Byte");
        validate_type(InvocationArg::from('c'), "java.lang.Character");
        validate_type(InvocationArg::from(1_i16), "java.lang.Short");
        validate_type(InvocationArg::from(1_i64), "java.lang.Long");
        validate_type(InvocationArg::from(0.1_f32), "java.lang.Float");
        validate_type(InvocationArg::from(0.1_f64), "java.lang.Double");
        validate_type(InvocationArg::from(()), "void");

        validate_type(InvocationArg::from(&"str".to_string()), "java.lang.String");
        validate_type(InvocationArg::from(&true), "java.lang.Boolean");
        validate_type(InvocationArg::from(&1_i8), "java.lang.Byte");
        validate_type(InvocationArg::from(&'c'), "java.lang.Character");
        validate_type(InvocationArg::from(&1_i16), "java.lang.Short");
        validate_type(InvocationArg::from(&1_i64), "java.lang.Long");
        validate_type(InvocationArg::from(&0.1_f32), "java.lang.Float");
        validate_type(InvocationArg::from(&0.1_f64), "java.lang.Double");
    }

    fn validate_type(ia: InvocationArg, class: &str) {
        let b = match ia {
            _s @ InvocationArg::Java { .. } => false,
            InvocationArg::Rust { class_name, json: _, .. } => {
                class == class_name
            }
        };
        assert!(b);
    }
}