Friday, February 14, 2020

Switch versi Java di macOS Catalina

Tertarik dengan service Azure Function rilisan Microsoft, langsung dicoba bikin hello world-nya Azure Function menggunakan Java dengan IDE IntelliJ IDEA.

Dengan mengikuti langkah-langkah yang ada di documentation Microsoft, akhirnya sukses men-deploy serverless web app ke portal Azure Function. Setelah dites, app-nya berjalan normal. Tetapi ketika dicoba test di local environment, web app ini tak memberikan respon normal alias error.

[02/14/2020 18:45:42] Worker failed to function id 354c4307-6b98-450f-9537-1b661153d88a.
[02/14/2020 18:45:42] Result: Failure
[02/14/2020 18:45:42] Exception: ClassCastException: class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader (jdk.internal.loader.ClassLoaders$AppClassLoader and java.net.URLClassLoader are in module java.base of loader 'bootstrap')
[02/14/2020 18:45:42] Stack: java.lang.ClassCastException: class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader (jdk.internal.loader.ClassLoaders$AppClassLoader and java.net.URLClassLoader are in module java.base of loader 'bootstrap')


Setelah Googling beberapa saat, akhirnya ketemu jawabannya:
Azure Function baru support Java 8, sementara default JDK di macOS Catalina adalah JDK 11. Jadi, default Java harus di-switch dari JDK 11 ke JDK 8.

Di macOS Catalina ada 3 versi Java yang sudah terinstall:


MacBook-Pro:~ myusername$ /usr/libexec/java_home -V
Matching Java Virtual Machines (3):
    11.0.5, x86_64: "Java SE 11.0.5" /Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home
    1.8.0_242, x86_64: "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
    1.8.0_241, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home


Switch JAVA_HOME ke versi JDK 8:
pertama buka file .bash_profile dengan command nano .bash_profile
Lalu copy-paste command berikut di file .bash_profile:


# Setting default JDK to version 1.8.0_241
export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home'


Setelah itu execute command source .bash_profile
Cek hasilnya:


MacBook-Pro:~ myusername$ java -version
java version "1.8.0_241"
Java(TM) SE Runtime Environment (build 1.8.0_241-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.241-b07, mixed mode)
MacBook-Pro:~ myusername$ javac -version
javac 1.8.0_241


Ingat, pastikan juga kalau versi JDK di IDE IntelliJ IDEA juga sudah diset JDK 8!
Dengan begini, akhirnya web app Azure Funtion bisa berjalan malus normal di local environment

No comments: