当前位置:   article > 正文

MacOS安装反编译工具JD-GUI以及解决无法打开的问题_mac jd-gui

mac jd-gui

目录

一.下载地址

二.安装

三.问题

四.解决办法

1.显示包内容

2.找到Contents/MacOS/universalJavaApplicationStub.sh

3.修改sh文件

4.保存后再次打开即可


一.下载地址

Java Decompiler

二.安装

将下载下来的 jd-gui-osx-1.6.6.tar 解压,然后将 JD-GUI.app 文件拷贝到 Applications 应用程序目录里面

三.问题

打开jd-gui提示找不到jdk,想都不用想,一定不是没有安装jdk或者没有配置环境变量,除非你是真的没有安装

四.解决办法

1.显示包内容

2.找到Contents/MacOS/universalJavaApplicationStub.sh

3.修改sh文件

内容修改为下面的即可

  1. #!/bin/bash
  2. ##################################################################################
  3. # #
  4. # universalJavaApplicationStub #
  5. # #
  6. # A BASH based JavaApplicationStub for Java Apps on Mac OS X #
  7. # that works with both Apple's and Oracle's plist format. #
  8. # #
  9. # Inspired by Ian Roberts stackoverflow answer #
  10. # at http://stackoverflow.com/a/17546508/1128689 #
  11. # #
  12. # @author Tobias Fischer #
  13. # @url https://github.com/tofi86/universalJavaApplicationStub #
  14. # @date 2023-02-04 #
  15. # @version 3.3.0 #
  16. # #
  17. ##################################################################################
  18. # #
  19. # The MIT License (MIT) #
  20. # #
  21. # Copyright (c) 2014-2023 Tobias Fischer #
  22. # #
  23. # Permission is hereby granted, free of charge, to any person obtaining a copy #
  24. # of this software and associated documentation files (the "Software"), to deal #
  25. # in the Software without restriction, including without limitation the rights #
  26. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
  27. # copies of the Software, and to permit persons to whom the Software is #
  28. # furnished to do so, subject to the following conditions: #
  29. # #
  30. # The above copyright notice and this permission notice shall be included in all #
  31. # copies or substantial portions of the Software. #
  32. # #
  33. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
  34. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
  35. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
  36. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
  37. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
  38. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #
  39. # SOFTWARE. #
  40. # #
  41. ##################################################################################
  42. # function 'stub_logger()'
  43. #
  44. # A logger which logs to the macOS Console.app using the 'syslog' command
  45. #
  46. # @param1 the log message
  47. # @return void
  48. ################################################################################
  49. function stub_logger() {
  50. syslog -s -k \
  51. Facility com.apple.console \
  52. Level Notice \
  53. Sender "$(basename "$0")" \
  54. Message "[$$][${CFBundleName:-$(basename "$0")}] $1"
  55. }
  56. # set the directory abspath of the current
  57. # shell script with symlinks being resolved
  58. ############################################
  59. PRG=$0
  60. while [ -h "$PRG" ]; do
  61. ls=$(ls -ld "$PRG")
  62. link=$(expr "$ls" : '^.*-> \(.*\)$' 2>/dev/null)
  63. if expr "$link" : '^/' 2> /dev/null >/dev/null; then
  64. PRG="$link"
  65. else
  66. PRG="$(dirname "$PRG")/$link"
  67. fi
  68. done
  69. PROGDIR=$(dirname "$PRG")
  70. stub_logger "[StubDir] $PROGDIR"
  71. # set files and folders
  72. ############################################
  73. # the absolute path of the app package
  74. cd "$PROGDIR"/../../ || exit 11
  75. AppPackageFolder=$(pwd)
  76. # the base path of the app package
  77. cd .. || exit 12
  78. AppPackageRoot=$(pwd)
  79. # set Apple's Java folder
  80. AppleJavaFolder="${AppPackageFolder}"/Contents/Resources/Java
  81. # set Apple's Resources folder
  82. AppleResourcesFolder="${AppPackageFolder}"/Contents/Resources
  83. # set Oracle's Java folder
  84. OracleJavaFolder="${AppPackageFolder}"/Contents/Java
  85. # set Oracle's Resources folder
  86. OracleResourcesFolder="${AppPackageFolder}"/Contents/Resources
  87. # set path to Info.plist in bundle
  88. InfoPlistFile="${AppPackageFolder}"/Contents/Info.plist
  89. # set the default JVM Version to a null string
  90. JVMVersion=""
  91. JVMMaxVersion=""
  92. # function 'plist_get()'
  93. #
  94. # read a specific Plist key with 'PlistBuddy' utility
  95. #
  96. # @param1 the Plist key with leading colon ':'
  97. # @return the value as String or Array
  98. ################################################################################
  99. plist_get(){
  100. /usr/libexec/PlistBuddy -c "print $1" "${InfoPlistFile}" 2> /dev/null
  101. }
  102. # function 'plist_get_java()'
  103. #
  104. # read a specific Plist key with 'PlistBuddy' utility
  105. # in the 'Java' or 'JavaX' dictionary (<dict>)
  106. #
  107. # @param1 the Plist :Java(X):Key with leading colon ':'
  108. # @return the value as String or Array
  109. ################################################################################
  110. plist_get_java(){
  111. plist_get ${JavaKey:-":Java"}$1
  112. }
  113. # read Info.plist and extract JVM options
  114. ############################################
  115. # read the program name from CFBundleName
  116. CFBundleName=$(plist_get ':CFBundleName')
  117. # read the icon file name
  118. CFBundleIconFile=$(plist_get ':CFBundleIconFile')
  119. # check Info.plist for Apple style Java keys -> if key :Java is present, parse in apple mode
  120. /usr/libexec/PlistBuddy -c "print :Java" "${InfoPlistFile}" > /dev/null 2>&1
  121. exitcode=$?
  122. JavaKey=":Java"
  123. # if no :Java key is present, check Info.plist for universalJavaApplication style JavaX keys -> if key :JavaX is present, parse in apple mode
  124. if [ $exitcode -ne 0 ]; then
  125. /usr/libexec/PlistBuddy -c "print :JavaX" "${InfoPlistFile}" > /dev/null 2>&1
  126. exitcode=$?
  127. JavaKey=":JavaX"
  128. fi
  129. # read 'Info.plist' file in Apple style if exit code returns 0 (true, ':Java' key is present)
  130. if [ $exitcode -eq 0 ]; then
  131. stub_logger "[PlistStyle] Apple"
  132. # set Java and Resources folder
  133. JavaFolder="${AppleJavaFolder}"
  134. ResourcesFolder="${AppleResourcesFolder}"
  135. # set expandable variables
  136. APP_ROOT="${AppPackageFolder}"
  137. APP_PACKAGE="${AppPackageFolder}"
  138. JAVAROOT="${AppleJavaFolder}"
  139. USER_HOME="$HOME"
  140. # read the Java WorkingDirectory
  141. JVMWorkDir=$(plist_get_java ':WorkingDirectory' | xargs)
  142. # set Working Directory based upon PList value
  143. if [[ ! -z ${JVMWorkDir} ]]; then
  144. WorkingDirectory="${JVMWorkDir}"
  145. else
  146. # AppPackageRoot is the standard WorkingDirectory when the script is started
  147. WorkingDirectory="${AppPackageRoot}"
  148. fi
  149. # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME
  150. WorkingDirectory=$(eval echo "${WorkingDirectory}")
  151. # read the MainClass name
  152. JVMMainClass="$(plist_get_java ':MainClass')"
  153. # read the SplashFile name
  154. JVMSplashFile=$(plist_get_java ':SplashFile')
  155. # read the JVM Properties as an array and retain spaces
  156. IFS=$'\t\n'
  157. JVMOptions=($(xargs -n1 <<<$(plist_get_java ':Properties' | grep " =" | sed 's/^ */-D/g' | sed -E 's/ = (.*)$/="\1"/g')))
  158. unset IFS
  159. # post processing of the array follows further below...
  160. # read the ClassPath in either Array or String style
  161. JVMClassPath_RAW=$(plist_get_java ':ClassPath' | xargs)
  162. if [[ $JVMClassPath_RAW == *Array* ]] ; then
  163. JVMClassPath=.$(plist_get_java ':ClassPath' | grep " " | sed 's/^ */:/g' | tr -d '\n' | xargs)
  164. else
  165. JVMClassPath=${JVMClassPath_RAW}
  166. fi
  167. # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME
  168. JVMClassPath=$(eval echo "${JVMClassPath}")
  169. # read the JVM Options in either Array or String style
  170. JVMDefaultOptions_RAW=$(plist_get_java ':VMOptions' | xargs)
  171. if [[ $JVMDefaultOptions_RAW == *Array* ]] ; then
  172. JVMDefaultOptions=$(plist_get_java ':VMOptions' | grep " " | sed 's/^ */ /g' | tr -d '\n' | xargs)
  173. else
  174. JVMDefaultOptions=${JVMDefaultOptions_RAW}
  175. fi
  176. # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME (#84)
  177. JVMDefaultOptions=$(eval echo "${JVMDefaultOptions}")
  178. # read StartOnMainThread and add as -XstartOnFirstThread
  179. JVMStartOnMainThread=$(plist_get_java ':StartOnMainThread')
  180. if [ "${JVMStartOnMainThread}" == "true" ]; then
  181. JVMDefaultOptions+=" -XstartOnFirstThread"
  182. fi
  183. # read the JVM Arguments in either Array or String style (#76) and retain spaces
  184. IFS=$'\t\n'
  185. MainArgs_RAW=$(plist_get_java ':Arguments' | xargs)
  186. if [[ $MainArgs_RAW == *Array* ]] ; then
  187. MainArgs=($(xargs -n1 <<<$(plist_get_java ':Arguments' | tr -d '\n' | sed -E 's/Array \{ *(.*) *\}/\1/g' | sed 's/ */ /g')))
  188. else
  189. MainArgs=($(xargs -n1 <<<$(plist_get_java ':Arguments')))
  190. fi
  191. unset IFS
  192. # post processing of the array follows further below...
  193. # read the Java version we want to find
  194. JVMVersion=$(plist_get_java ':JVMVersion' | xargs)
  195. # post processing of the version string follows below...
  196. # read 'Info.plist' file in Oracle style
  197. else
  198. stub_logger "[PlistStyle] Oracle"
  199. # set Working Directory and Java and Resources folder
  200. JavaFolder="${OracleJavaFolder}"
  201. ResourcesFolder="${OracleResourcesFolder}"
  202. WorkingDirectory="${OracleJavaFolder}"
  203. # set expandable variables
  204. APP_ROOT="${AppPackageFolder}"
  205. APP_PACKAGE="${AppPackageFolder}"
  206. JAVAROOT="${OracleJavaFolder}"
  207. USER_HOME="$HOME"
  208. # read the MainClass name
  209. JVMMainClass="$(plist_get ':JVMMainClassName')"
  210. # read the SplashFile name
  211. JVMSplashFile=$(plist_get ':JVMSplashFile')
  212. # read the JVM Options as an array and retain spaces
  213. IFS=$'\t\n'
  214. JVMOptions=($(plist_get ':JVMOptions' | grep " " | sed 's/^ *//g'))
  215. unset IFS
  216. # post processing of the array follows further below...
  217. # read the ClassPath in either Array or String style
  218. JVMClassPath_RAW=$(plist_get ':JVMClassPath')
  219. if [[ $JVMClassPath_RAW == *Array* ]] ; then
  220. JVMClassPath=.$(plist_get ':JVMClassPath' | grep " " | sed 's/^ */:/g' | tr -d '\n' | xargs)
  221. # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME
  222. JVMClassPath=$(eval echo "${JVMClassPath}")
  223. elif [[ ! -z ${JVMClassPath_RAW} ]] ; then
  224. JVMClassPath=${JVMClassPath_RAW}
  225. # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME
  226. JVMClassPath=$(eval echo "${JVMClassPath}")
  227. else
  228. #default: fallback to OracleJavaFolder
  229. JVMClassPath="${JavaFolder}/*"
  230. # Do NOT expand the default 'AppName.app/Contents/Java/*' classpath (#42)
  231. fi
  232. # read the JVM Default Options by parsing the :JVMDefaultOptions <dict>
  233. # and pulling all <string> values starting with a dash (-)
  234. JVMDefaultOptions=$(plist_get ':JVMDefaultOptions' | grep -o " \-.*" | tr -d '\n' | xargs)
  235. # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME (#99)
  236. JVMDefaultOptions=$(eval echo "${JVMDefaultOptions}")
  237. # read the Main Arguments from JVMArguments key as an array and retain spaces (see #46 for naming details)
  238. IFS=$'\t\n'
  239. MainArgs=($(xargs -n1 <<<$(plist_get ':JVMArguments' | tr -d '\n' | sed -E 's/Array \{ *(.*) *\}/\1/g' | sed 's/ */ /g')))
  240. unset IFS
  241. # post processing of the array follows further below...
  242. # read the Java version we want to find
  243. JVMVersion=$(plist_get ':JVMVersion' | xargs)
  244. # post processing of the version string follows below...
  245. fi
  246. # (#75) check for undefined icons or icon names without .icns extension and prepare
  247. # an osascript statement for those cases when the icon can be shown in the dialog
  248. DialogWithIcon=""
  249. if [ ! -z ${CFBundleIconFile} ]; then
  250. if [[ ${CFBundleIconFile} == *.icns ]] && [[ -f "${ResourcesFolder}/${CFBundleIconFile}" ]] ; then
  251. DialogWithIcon=" with icon path to resource \"${CFBundleIconFile}\" in bundle (path to me)"
  252. elif [[ ${CFBundleIconFile} != *.icns ]] && [[ -f "${ResourcesFolder}/${CFBundleIconFile}.icns" ]] ; then
  253. CFBundleIconFile+=".icns"
  254. DialogWithIcon=" with icon path to resource \"${CFBundleIconFile}\" in bundle (path to me)"
  255. fi
  256. fi
  257. # JVMVersion: post processing and optional splitting
  258. if [[ ${JVMVersion} == *";"* ]]; then
  259. minMaxArray=(${JVMVersion//;/ })
  260. JVMVersion=${minMaxArray[0]//+}
  261. JVMMaxVersion=${minMaxArray[1]//+}
  262. fi
  263. stub_logger "[JavaRequirement] JVM minimum version: ${JVMVersion}"
  264. stub_logger "[JavaRequirement] JVM maximum version: ${JVMMaxVersion}"
  265. # MainArgs: expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME
  266. MainArgsArr=()
  267. for i in "${MainArgs[@]}"
  268. do
  269. MainArgsArr+=("$(eval echo "$i")")
  270. done
  271. # JVMOptions: expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME
  272. JVMOptionsArr=()
  273. for i in "${JVMOptions[@]}"
  274. do
  275. JVMOptionsArr+=("$(eval echo "$i")")
  276. done
  277. # internationalized messages
  278. ############################################
  279. # supported languages / available translations
  280. stubLanguages=("de" "en" "es" "fr" "pt-BR" "zh")
  281. # read user preferred languages as defined in macOS System Preferences (#101)
  282. stub_logger '[LanguageSearch] Checking preferred languages in macOS System Preferences...'
  283. appleLanguages=($(defaults read -g AppleLanguages | grep '\s"' | tr -d ',' | xargs))
  284. stub_logger "[LanguageSearch] ... found [${appleLanguages[*]}]"
  285. language=""
  286. for i in "${appleLanguages[@]}"
  287. do
  288. langValue="${i%-*}"
  289. if [[ " ${stubLanguages[*]} " =~ " ${i} " ]]; then
  290. stub_logger "[LanguageSearch] ... selected '$i' as the default language for the launcher stub"
  291. language=${i}
  292. break
  293. elif [[ " ${stubLanguages[*]} " =~ " ${langValue} " ]]; then
  294. stub_logger "[LanguageSearch] ... selected '$langValue' (from '$i') as the default language for the launcher stub"
  295. language=${langValue}
  296. break
  297. fi
  298. done
  299. if [ -z "${language}" ]; then
  300. language="en"
  301. stub_logger "[LanguageSearch] ... selected fallback 'en' as the default language for the launcher stub"
  302. fi
  303. stub_logger "[Language] $language"
  304. case "${language}" in
  305. # French
  306. fr)
  307. MSG_ERROR_LAUNCHING="ERREUR au lancement de '${CFBundleName}'."
  308. MSG_MISSING_MAINCLASS="'MainClass' n'est pas spécifié.\nL'application Java ne peut pas être lancée."
  309. MSG_JVMVERSION_REQ_INVALID="La syntaxe de la version de Java demandée est invalide: %s\nVeuillez contacter le développeur de l'application."
  310. MSG_NO_SUITABLE_JAVA="La version de Java installée sur votre système ne convient pas.\nCe programme nécessite Java %s"
  311. MSG_JAVA_VERSION_OR_LATER="ou ultérieur"
  312. MSG_JAVA_VERSION_LATEST="(dernière mise à jour)"
  313. MSG_JAVA_VERSION_MAX="à %s"
  314. MSG_NO_SUITABLE_JAVA_CHECK="Merci de bien vouloir installer la version de Java requise."
  315. MSG_INSTALL_JAVA="Java doit être installé sur votre système.\nRendez-vous sur java.com et suivez les instructions d'installation..."
  316. MSG_LATER="Plus tard"
  317. MSG_VISIT_JAVA_DOT_COM="Java by Oracle"
  318. MSG_VISIT_ADOPTIUM="Java by Adoptium"
  319. ;;
  320. # German
  321. de)
  322. MSG_ERROR_LAUNCHING="FEHLER beim Starten von '${CFBundleName}'."
  323. MSG_MISSING_MAINCLASS="Die 'MainClass' ist nicht spezifiziert!\nDie Java-Anwendung kann nicht gestartet werden!"
  324. MSG_JVMVERSION_REQ_INVALID="Die Syntax der angeforderten Java-Version ist ungültig: %s\nBitte kontaktieren Sie den Entwickler der App."
  325. MSG_NO_SUITABLE_JAVA="Es wurde keine passende Java-Version auf Ihrem System gefunden!\nDieses Programm benötigt Java %s"
  326. MSG_JAVA_VERSION_OR_LATER="oder neuer"
  327. MSG_JAVA_VERSION_LATEST="(neuste Unterversion)"
  328. MSG_JAVA_VERSION_MAX="bis %s"
  329. MSG_NO_SUITABLE_JAVA_CHECK="Stellen Sie sicher, dass die angeforderte Java-Version installiert ist."
  330. MSG_INSTALL_JAVA="Auf Ihrem System muss die 'Java'-Software installiert sein.\nBesuchen Sie java.com für weitere Installationshinweise."
  331. MSG_LATER="Später"
  332. MSG_VISIT_JAVA_DOT_COM="Java von Oracle"
  333. MSG_VISIT_ADOPTIUM="Java von Adoptium"
  334. ;;
  335. # Simplified Chinese
  336. zh)
  337. MSG_ERROR_LAUNCHING="无法启动 '${CFBundleName}'."
  338. MSG_MISSING_MAINCLASS="没有指定 'MainClass'!\nJava程序无法启动!"
  339. MSG_JVMVERSION_REQ_INVALID="Java版本参数语法错误: %s\n请联系该应用的开发者。"
  340. MSG_NO_SUITABLE_JAVA="没有在系统中找到合适的Java版本!\n必须安装Java %s才能够使用该程序!"
  341. MSG_JAVA_VERSION_OR_LATER="及以上版本"
  342. MSG_JAVA_VERSION_LATEST="(最新版本)"
  343. MSG_JAVA_VERSION_MAX="最高为 %s"
  344. MSG_NO_SUITABLE_JAVA_CHECK="请确保系统中安装了所需的Java版本"
  345. MSG_INSTALL_JAVA="你需要在Mac中安装Java运行环境!\n访问 java.com 了解如何安装。"
  346. MSG_LATER="稍后"
  347. MSG_VISIT_JAVA_DOT_COM="Java by Oracle"
  348. MSG_VISIT_ADOPTIUM="Java by Adoptium"
  349. ;;
  350. # Spanish
  351. es)
  352. MSG_ERROR_LAUNCHING="ERROR iniciando '${CFBundleName}'."
  353. MSG_MISSING_MAINCLASS="¡'MainClass' no especificada!\n¡La aplicación Java no puede iniciarse!"
  354. MSG_JVMVERSION_REQ_INVALID="La sintaxis de la versión Java requerida no es válida: %s\nPor favor, contacte con el desarrollador de la aplicación."
  355. MSG_NO_SUITABLE_JAVA="¡No se encontró una versión de Java adecuada en su sistema!\nEste programa requiere Java %s"
  356. MSG_JAVA_VERSION_OR_LATER="o posterior"
  357. MSG_JAVA_VERSION_LATEST="(ultima actualización)"
  358. MSG_JAVA_VERSION_MAX="superior a %s"
  359. MSG_NO_SUITABLE_JAVA_CHECK="Asegúrese de instalar la versión Java requerida."
  360. MSG_INSTALL_JAVA="¡Necesita tener JAVA instalado en su Mac!\nVisite java.com para consultar las instrucciones para su instalación..."
  361. MSG_LATER="Más tarde"
  362. MSG_VISIT_JAVA_DOT_COM="Java de Oracle"
  363. MSG_VISIT_ADOPTIUM="Java de Adoptium"
  364. ;;
  365. # Brazilian Portuguese
  366. pt-BR)
  367. MSG_ERROR_LAUNCHING="ERRO iniciando '${CFBundleName}'."
  368. MSG_MISSING_MAINCLASS="'MainClass' não foi definida!\nA aplicação java não poderá ser iniciada!"
  369. MSG_JVMVERSION_REQ_INVALID="A sintaxe da versão Java requerida não é valida: %s\nPor favor contacte o desenvolvedor dessa aplicação."
  370. MSG_NO_SUITABLE_JAVA="Não foi encontrado uma versão Java compatível no seu sistema!\nEsta aplicação precisa do Java %s"
  371. MSG_JAVA_VERSION_OR_LATER="ou maior"
  372. MSG_JAVA_VERSION_LATEST="(última atualização)"
  373. MSG_JAVA_VERSION_MAX="máxima %s"
  374. MSG_NO_SUITABLE_JAVA_CHECK="Verifique se instalou a versão Java necessária."
  375. MSG_INSTALL_JAVA="Você precisa instalar o JAVA no seu Mac!\nPor favor, visite java.com para instruções de instalação..."
  376. MSG_LATER="Depois"
  377. MSG_VISIT_JAVA_DOT_COM="Java por Oracle"
  378. MSG_VISIT_ADOPTIUM="Java por Adoptium"
  379. ;;
  380. # English | default
  381. en|*)
  382. MSG_ERROR_LAUNCHING="ERROR launching '${CFBundleName}'."
  383. MSG_MISSING_MAINCLASS="'MainClass' isn't specified!\nJava application cannot be started!"
  384. MSG_JVMVERSION_REQ_INVALID="The syntax of the required Java version is invalid: %s\nPlease contact the App developer."
  385. MSG_NO_SUITABLE_JAVA="No suitable Java version found on your system!\nThis program requires Java %s"
  386. MSG_JAVA_VERSION_OR_LATER="or later"
  387. MSG_JAVA_VERSION_LATEST="(latest update)"
  388. MSG_JAVA_VERSION_MAX="up to %s"
  389. MSG_NO_SUITABLE_JAVA_CHECK="Make sure you install the required Java version."
  390. MSG_INSTALL_JAVA="You need to have JAVA installed on your Mac!\nVisit java.com for installation instructions..."
  391. MSG_LATER="Later"
  392. MSG_VISIT_JAVA_DOT_COM="Java by Oracle"
  393. MSG_VISIT_ADOPTIUM="Java by Adoptium"
  394. ;;
  395. esac
  396. # function 'get_java_version_from_cmd()'
  397. #
  398. # returns Java version string from 'java -version' command
  399. # works for both old (1.8) and new (9) version schema
  400. #
  401. # @param1 path to a java JVM executable
  402. # @return the Java version number as displayed in 'java -version' command
  403. ################################################################################
  404. function get_java_version_from_cmd() {
  405. # second sed command strips " and -ea from the version string
  406. echo $("$1" -version 2>&1 | awk '/version/{print $3}' | sed -E 's/"//g;s/-ea//g')
  407. }
  408. # function 'extract_java_major_version()'
  409. #
  410. # extract Java major version from a version string
  411. #
  412. # @param1 a Java version number ('1.8.0_45') or requirement string ('1.8+')
  413. # @return the major version (e.g. '7', '8' or '9', etc.)
  414. ################################################################################
  415. function extract_java_major_version() {
  416. echo $(echo "$1" | sed -E 's/^1\.//;s/^([0-9]+)(-ea|(\.[0-9_.]{1,7})?)(-b[0-9]+-[0-9]+)?[+*]?$/\1/')
  417. }
  418. # function 'get_comparable_java_version()'
  419. #
  420. # return comparable version for a Java version number or requirement string
  421. #
  422. # @param1 a Java version number ('1.8.0_45') or requirement string ('1.8+')
  423. # @return an 8 digit numeral ('1.8.0_45'->'08000045'; '9.1.13'->'09001013')
  424. ################################################################################
  425. function get_comparable_java_version() {
  426. # cleaning: 1) remove leading '1.'; 2) remove build string (e.g. '-b14-468'); 3) remove 'a-Z' and '-*+' (e.g. '-ea'); 4) replace '_' with '.'
  427. local cleaned=$(echo "$1" | sed -E 's/^1\.//g;s/-b[0-9]+-[0-9]+$//g;s/[a-zA-Z+*\-]//g;s/_/./g')
  428. # splitting at '.' into an array
  429. local arr=( ${cleaned//./ } )
  430. # echo a string with left padded version numbers
  431. echo "$(printf '%02s' ${arr[0]})$(printf '%03s' ${arr[1]})$(printf '%03s' ${arr[2]})"
  432. }
  433. # function 'is_valid_requirement_pattern()'
  434. #
  435. # check whether the Java requirement is a valid requirement pattern
  436. #
  437. # supported requirements are for example:
  438. # - 1.6 requires Java 6 (any update) [1.6, 1.6.0_45, 1.6.0_88]
  439. # - 1.6* requires Java 6 (any update) [1.6, 1.6.0_45, 1.6.0_88]
  440. # - 1.6+ requires Java 6 or higher [1.6, 1.6.0_45, 1.8, 9, etc.]
  441. # - 1.6.0 requires Java 6 (any update) [1.6, 1.6.0_45, 1.6.0_88]
  442. # - 1.6.0_45 requires Java 6u45 [1.6.0_45]
  443. # - 1.6.0_45+ requires Java 6u45 or higher [1.6.0_45, 1.6.0_88, 1.8, etc.]
  444. # - 9 requires Java 9 (any update) [9.0.*, 9.1, 9.3, etc.]
  445. # - 9* requires Java 9 (any update) [9.0.*, 9.1, 9.3, etc.]
  446. # - 9+ requires Java 9 or higher [9.0, 9.1, 10, etc.]
  447. # - 9.1 requires Java 9.1 (any update) [9.1.*, 9.1.2, 9.1.13, etc.]
  448. # - 9.1* requires Java 9.1 (any update) [9.1.*, 9.1.2, 9.1.13, etc.]
  449. # - 9.1+ requires Java 9.1 or higher [9.1, 9.2, 10, etc.]
  450. # - 9.1.3 requires Java 9.1.3 [9.1.3]
  451. # - 9.1.3* requires Java 9.1.3 (any update) [9.1.3]
  452. # - 9.1.3+ requires Java 9.1.3 or higher [9.1.3, 9.1.4, 9.2.*, 10, etc.]
  453. # - 10-ea requires Java 10 (early access release)
  454. #
  455. # unsupported requirement patterns are for example:
  456. # - 1.2, 1.3, 1.9 Java 2, 3 are not supported
  457. # - 1.9 Java 9 introduced a new versioning scheme
  458. # - 6u45 known versioning syntax, but unsupported
  459. # - 9-ea*, 9-ea+ early access releases paired with */+
  460. # - 9., 9.*, 9.+ version ending with a .
  461. # - 9.1., 9.1.*, 9.1.+ version ending with a .
  462. # - 9.3.5.6 4 part version number is unsupported
  463. #
  464. # @param1 a Java requirement string ('1.8+')
  465. # @return boolean exit code: 0 (is valid), 1 (is not valid)
  466. ################################################################################
  467. function is_valid_requirement_pattern() {
  468. local java_req=$1
  469. java8pattern='1\.[4-8](\.[0-9]+)?(\.0_[0-9]+)?[*+]?'
  470. java9pattern='(9|1[0-9])(-ea|[*+]|(\.[0-9]+){1,2}[*+]?)?'
  471. # test matches either old Java versioning scheme (up to 1.8) or new scheme (starting with 9)
  472. if [[ ${java_req} =~ ^(${java8pattern}|${java9pattern})$ ]]; then
  473. return 0
  474. else
  475. return 1
  476. fi
  477. }
  478. # determine which JVM to use
  479. ############################################
  480. # default Apple JRE plugin path (< 1.6)
  481. apple_jre_plugin="/Library/Java/Home/bin/java"
  482. apple_jre_version=$(get_java_version_from_cmd "${apple_jre_plugin}")
  483. # default Oracle JRE plugin path (>= 1.7)
  484. oracle_jre_plugin="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java"
  485. oracle_jre_version=$(get_java_version_from_cmd "${oracle_jre_plugin}")
  486. # first check system variable "$JAVA_HOME" -> has precedence over any other System JVM
  487. stub_logger '[JavaSearch] Checking for $JAVA_HOME ...'
  488. if [ -n "$JAVA_HOME" ] ; then
  489. stub_logger "[JavaSearch] ... found JAVA_HOME with value $JAVA_HOME"
  490. # PR 26: Allow specifying "$JAVA_HOME" relative to "$AppPackageFolder"
  491. # which allows for bundling a custom version of Java inside your app!
  492. if [[ $JAVA_HOME == /* ]] ; then
  493. # if "$JAVA_HOME" starts with a Slash it's an absolute path
  494. JAVACMD="$JAVA_HOME/bin/java"
  495. stub_logger "[JavaSearch] ... parsing JAVA_HOME as absolute path to the executable '$JAVACMD'"
  496. else
  497. # otherwise it's a relative path to "$AppPackageFolder"
  498. JAVACMD="$AppPackageFolder/$JAVA_HOME/bin/java"
  499. stub_logger "[JavaSearch] ... parsing JAVA_HOME as relative path inside the App bundle to the executable '$JAVACMD'"
  500. fi
  501. JAVACMD_version=$(get_comparable_java_version $(get_java_version_from_cmd "${JAVACMD}"))
  502. else
  503. stub_logger "[JavaSearch] ... haven't found JAVA_HOME"
  504. fi
  505. # check for any other or a specific Java version
  506. # also if $JAVA_HOME exists but isn't executable
  507. if [ -z "${JAVACMD}" ] || [ ! -x "${JAVACMD}" ] ; then
  508. # add a warning in the syslog if JAVA_HOME is not executable or not found (#100)
  509. if [ -n "$JAVA_HOME" ] ; then
  510. stub_logger "[JavaSearch] ... but no 'java' executable was found at the JAVA_HOME location!"
  511. fi
  512. stub_logger "[JavaSearch] Searching for JavaVirtualMachines on the system ..."
  513. # reset variables
  514. JAVACMD=""
  515. JAVACMD_version=""
  516. # first check whether JVMVersion string is a valid requirement string
  517. if [ ! -z "${JVMVersion}" ] && ! is_valid_requirement_pattern ${JVMVersion} ; then
  518. MSG_JVMVERSION_REQ_INVALID_EXPANDED=$(printf "${MSG_JVMVERSION_REQ_INVALID}" "${JVMVersion}")
  519. # log exit cause
  520. stub_logger "[EXIT 4] ${MSG_JVMVERSION_REQ_INVALID_EXPANDED}"
  521. # display error message with AppleScript
  522. osascript -e "tell application \"System Events\" to display dialog \"${MSG_ERROR_LAUNCHING}\n\n${MSG_JVMVERSION_REQ_INVALID_EXPANDED}\" with title \"${CFBundleName}\" buttons {\" OK \"} default button 1${DialogWithIcon}"
  523. # exit with error
  524. exit 4
  525. fi
  526. # then check whether JVMMaxVersion string is a valid requirement string
  527. if [ ! -z "${JVMMaxVersion}" ] && ! is_valid_requirement_pattern ${JVMMaxVersion} ; then
  528. MSG_JVMVERSION_REQ_INVALID_EXPANDED=$(printf "${MSG_JVMVERSION_REQ_INVALID}" "${JVMMaxVersion}")
  529. # log exit cause
  530. stub_logger "[EXIT 5] ${MSG_JVMVERSION_REQ_INVALID_EXPANDED}"
  531. # display error message with AppleScript
  532. osascript -e "tell application \"System Events\" to display dialog \"${MSG_ERROR_LAUNCHING}\n\n${MSG_JVMVERSION_REQ_INVALID_EXPANDED}\" with title \"${CFBundleName}\" buttons {\" OK \"} default button 1${DialogWithIcon}"
  533. # exit with error
  534. exit 5
  535. fi
  536. # find installed JavaVirtualMachines (JDK + JRE)
  537. allJVMs=()
  538. # read JDK's from '/usr/libexec/java_home --xml' command with PlistBuddy and a custom Dict iterator
  539. # idea: https://stackoverflow.com/a/14085460/1128689 and https://scriptingosx.com/2018/07/parsing-dscl-output-in-scripts/
  540. javaXml=$(/usr/libexec/java_home --xml)
  541. javaCounter=$(/usr/libexec/PlistBuddy -c "Print" /dev/stdin <<< $javaXml | grep "Dict" | wc -l | tr -d ' ')
  542. # iterate over all Dict entries
  543. # but only if there are any JVMs at all (#93)
  544. if [ "$javaCounter" -gt "0" ] ; then
  545. for idx in $(seq 0 $((javaCounter - 1)))
  546. do
  547. version=$(/usr/libexec/PlistBuddy -c "print :$idx:JVMVersion" /dev/stdin <<< $javaXml)
  548. path=$(/usr/libexec/PlistBuddy -c "print :$idx:JVMHomePath" /dev/stdin <<< $javaXml)
  549. path+="/bin/java"
  550. allJVMs+=("$version:$path")
  551. done
  552. # unset for loop variables
  553. unset version path
  554. fi
  555. # add SDKMAN! java versions (#95)
  556. if [ -d ~/.sdkman/candidates/java/ ] ; then
  557. for sdkjdk in ~/.sdkman/candidates/java/*/
  558. do
  559. if [[ ${sdkjdk} =~ /current/$ ]] ; then
  560. continue
  561. fi
  562. sdkjdkcmd="${sdkjdk}bin/java"
  563. version=$(get_java_version_from_cmd "${sdkjdkcmd}")
  564. allJVMs+=("$version:$sdkjdkcmd")
  565. done
  566. # unset for loop variables
  567. unset version
  568. fi
  569. # add Apple JRE if available
  570. if [ -x "${apple_jre_plugin}" ] ; then
  571. allJVMs+=("$apple_jre_version:$apple_jre_plugin")
  572. fi
  573. # add Oracle JRE if available
  574. if [ -x "${oracle_jre_plugin}" ] ; then
  575. allJVMs+=("$oracle_jre_version:$oracle_jre_plugin")
  576. fi
  577. # debug output
  578. for i in "${allJVMs[@]}"
  579. do
  580. stub_logger "[JavaSearch] ... found JVM: $i"
  581. done
  582. # determine JVMs matching the min/max version requirement
  583. stub_logger "[JavaSearch] Filtering the result list for JVMs matching the min/max version requirement ..."
  584. minC=$(get_comparable_java_version ${JVMVersion})
  585. maxC=$(get_comparable_java_version ${JVMMaxVersion})
  586. matchingJVMs=()
  587. for i in "${allJVMs[@]}"
  588. do
  589. # split JVM string at ':' delimiter to retain spaces in $path substring
  590. IFS=: arr=($i) ; unset IFS
  591. # [0] JVM version number
  592. ver=${arr[0]}
  593. # comparable JVM version number
  594. comp=$(get_comparable_java_version $ver)
  595. # [1] JVM path
  596. path="${arr[1]}"
  597. # construct string item for adding to the "matchingJVMs" array
  598. item="$comp:$ver:$path"
  599. # pre-requisite: current version number needs to be greater than min version number
  600. if [ "$comp" -ge "$minC" ] ; then
  601. # perform max version checks if max version requirement is present
  602. if [ ! -z ${JVMMaxVersion} ] ; then
  603. # max version requirement ends with '*' modifier
  604. if [[ ${JVMMaxVersion} == *\* ]] ; then
  605. # use the '*' modifier from the max version string as wildcard for a 'starts with' comparison
  606. # and check whether the current version number starts with the max version wildcard string
  607. if [[ ${ver} == ${JVMMaxVersion} ]]; then
  608. matchingJVMs+=("$item")
  609. # or whether the current comparable version is lower than the comparable max version
  610. elif [ "$comp" -le "$maxC" ] ; then
  611. matchingJVMs+=("$item")
  612. fi
  613. # max version requirement ends with '+' modifier -> always add this version if it's greater than $min
  614. # because a max requirement with + modifier doesn't make sense
  615. elif [[ ${JVMMaxVersion} == *+ ]] ; then
  616. matchingJVMs+=("$item")
  617. # matches 6 zeros at the end of the max version string (e.g. for 1.8, 9)
  618. # -> then the max version string should be treated like with a '*' modifier at the end
  619. #elif [[ ${maxC} =~ ^[0-9]{2}0{6}$ ]] && [ "$comp" -le $(( ${maxC#0} + 999 )) ] ; then
  620. # matchingJVMs+=("$item")
  621. # matches 3 zeros at the end of the max version string (e.g. for 9.1, 10.3)
  622. # -> then the max version string should be treated like with a '*' modifier at the end
  623. #elif [[ ${maxC} =~ ^[0-9]{5}0{3}$ ]] && [ "$comp" -le "${maxC}" ] ; then
  624. # matchingJVMs+=("$item")
  625. # matches standard requirements without modifier
  626. elif [ "$comp" -le "$maxC" ]; then
  627. matchingJVMs+=("$item")
  628. fi
  629. # no max version requirement:
  630. # min version requirement ends with '+' modifier
  631. # -> always add the current version because it's greater than $min
  632. elif [[ ${JVMVersion} == *+ ]] ; then
  633. matchingJVMs+=("$item")
  634. # min version requirement ends with '*' modifier
  635. # -> use the '*' modifier from the min version string as wildcard for a 'starts with' comparison
  636. # and check whether the current version number starts with the min version wildcard string
  637. elif [[ ${JVMVersion} == *\* ]] ; then
  638. if [[ ${ver} == ${JVMVersion} ]] ; then
  639. matchingJVMs+=("$item")
  640. fi
  641. # compare the min version against the current version with an additional * wildcard for a 'starts with' comparison
  642. # -> e.g. add 1.8.0_44 when the requirement is 1.8
  643. elif [[ ${ver} == ${JVMVersion}* ]] ; then
  644. matchingJVMs+=("$item")
  645. fi
  646. fi
  647. done
  648. # unset for loop variables
  649. unset arr ver comp path item
  650. # debug output
  651. for i in "${matchingJVMs[@]}"
  652. do
  653. stub_logger "[JavaSearch] ... matches all requirements: $i"
  654. done
  655. # sort the matching JavaVirtualMachines by version number
  656. # https://stackoverflow.com/a/11789688/1128689
  657. IFS=$'\n' matchingJVMs=($(sort -nr <<<"${matchingJVMs[*]}"))
  658. unset IFS
  659. # get the highest matching JVM
  660. for ((i = 0; i < ${#matchingJVMs[@]}; i++));
  661. do
  662. # split JVM string at ':' delimiter to retain spaces in $path substring
  663. IFS=: arr=(${matchingJVMs[$i]}) ; unset IFS
  664. # [0] comparable JVM version number
  665. comp=${arr[0]}
  666. # [1] JVM version number
  667. ver=${arr[1]}
  668. # [2] JVM path
  669. path="${arr[2]}"
  670. # use current value as JAVACMD if it's executable
  671. if [ -x "$path" ] ; then
  672. JAVACMD="$path"
  673. JAVACMD_version=$comp
  674. break
  675. fi
  676. done
  677. # unset for loop variables
  678. unset arr comp ver path
  679. fi
  680. # log the Java Command and the extracted version number
  681. stub_logger "[JavaCommand] '$JAVACMD'"
  682. stub_logger "[JavaVersion] $(get_java_version_from_cmd "${JAVACMD}")${JAVACMD_version:+ / $JAVACMD_version}"
  683. if [ -z "${JAVACMD}" ] || [ ! -x "${JAVACMD}" ] ; then
  684. # different error messages when a specific JVM was required
  685. if [ ! -z "${JVMVersion}" ] ; then
  686. # display human readable java version (#28)
  687. java_version_hr=$(echo ${JVMVersion} | sed -E 's/^1\.([0-9+*]+)$/ \1/g' | sed "s/+/ ${MSG_JAVA_VERSION_OR_LATER}/;s/*/ ${MSG_JAVA_VERSION_LATEST}/")
  688. MSG_NO_SUITABLE_JAVA_EXPANDED=$(printf "${MSG_NO_SUITABLE_JAVA}" "${java_version_hr}").
  689. if [ ! -z "${JVMMaxVersion}" ] ; then
  690. java_version_hr=$(extract_java_major_version ${JVMVersion})
  691. java_version_max_hr=$(echo ${JVMMaxVersion} | sed -E 's/^1\.([0-9+*]+)$/ \1/g' | sed "s/+//;s/*/ ${MSG_JAVA_VERSION_LATEST}/")
  692. MSG_NO_SUITABLE_JAVA_EXPANDED="$(printf "${MSG_NO_SUITABLE_JAVA}" "${java_version_hr}") $(printf "${MSG_JAVA_VERSION_MAX}" "${java_version_max_hr}")"
  693. fi
  694. # log exit cause
  695. stub_logger "[EXIT 3] ${MSG_NO_SUITABLE_JAVA_EXPANDED}"
  696. # display error message with AppleScript
  697. osascript -e "tell application \"System Events\" to display dialog \"${MSG_ERROR_LAUNCHING}\n\n${MSG_NO_SUITABLE_JAVA_EXPANDED}\n${MSG_NO_SUITABLE_JAVA_CHECK}\" with title \"${CFBundleName}\" buttons {\" OK \", \"${MSG_VISIT_JAVA_DOT_COM}\", \"${MSG_VISIT_ADOPTIUM}\"} default button 1${DialogWithIcon}" \
  698. -e "set response to button returned of the result" \
  699. -e "if response is \"${MSG_VISIT_JAVA_DOT_COM}\" then open location \"https://www.java.com/download/\"" \
  700. -e "if response is \"${MSG_VISIT_ADOPTIUM}\" then open location \"https://adoptium.net/releases.html\""
  701. # exit with error
  702. exit 3
  703. else
  704. # log exit cause
  705. stub_logger "[EXIT 1] ${MSG_ERROR_LAUNCHING}"
  706. # display error message with AppleScript
  707. osascript -e "tell application \"System Events\" to display dialog \"${MSG_ERROR_LAUNCHING}\n\n${MSG_INSTALL_JAVA}\" with title \"${CFBundleName}\" buttons {\"${MSG_LATER}\", \"${MSG_VISIT_JAVA_DOT_COM}\", \"${MSG_VISIT_ADOPTIUM}\"} default button 1${DialogWithIcon}" \
  708. -e "set response to button returned of the result" \
  709. -e "if response is \"${MSG_VISIT_JAVA_DOT_COM}\" then open location \"https://www.java.com/download/\"" \
  710. -e "if response is \"${MSG_VISIT_ADOPTIUM}\" then open location \"https://adoptium.net/releases.html\""
  711. # exit with error
  712. exit 1
  713. fi
  714. fi
  715. # MainClass check
  716. ############################################
  717. if [ -z "${JVMMainClass}" ]; then
  718. # log exit cause
  719. stub_logger "[EXIT 2] ${MSG_MISSING_MAINCLASS}"
  720. # display error message with AppleScript
  721. osascript -e "tell application \"System Events\" to display dialog \"${MSG_ERROR_LAUNCHING}\n\n${MSG_MISSING_MAINCLASS}\" with title \"${CFBundleName}\" buttons {\" OK \"} default button 1${DialogWithIcon}"
  722. # exit with error
  723. exit 2
  724. fi
  725. # execute $JAVACMD and do some preparation
  726. ############################################
  727. # enable drag&drop to the dock icon
  728. export CFProcessPath="$0"
  729. # remove Apples ProcessSerialNumber from passthru arguments (#39)
  730. if [[ "$*" == -psn* ]] ; then
  731. ArgsPassthru=()
  732. else
  733. ArgsPassthru=("$@")
  734. fi
  735. # change to Working Directory based upon Apple/Oracle Plist info
  736. cd "${WorkingDirectory}" || exit 13
  737. stub_logger "[WorkingDirectory] ${WorkingDirectory}"
  738. # execute Java and set
  739. # - classpath
  740. # - splash image
  741. # - dock icon
  742. # - app name
  743. # - JVM options / properties (-D)
  744. # - JVM default options (-X)
  745. # - main class
  746. # - main class arguments
  747. # - passthrough arguments from Terminal or Drag'n'Drop to Finder icon
  748. stub_logger "[Exec] \"$JAVACMD\" -cp \"${JVMClassPath}\" ${JVMSplashFile:+ -splash:\"${ResourcesFolder}/${JVMSplashFile}\"} -Xdock:icon=\"${ResourcesFolder}/${CFBundleIconFile}\" -Xdock:name=\"${CFBundleName}\" ${JVMOptionsArr:+$(printf "'%s' " "${JVMOptionsArr[@]}") }${JVMDefaultOptions:+$JVMDefaultOptions }${JVMMainClass}${MainArgsArr:+ $(printf "'%s' " "${MainArgsArr[@]}")}${ArgsPassthru:+ $(printf "'%s' " "${ArgsPassthru[@]}")}"
  749. exec "${JAVACMD}" \
  750. -cp "${JVMClassPath}" \
  751. ${JVMSplashFile:+ -splash:"${ResourcesFolder}/${JVMSplashFile}"} \
  752. -Xdock:icon="${ResourcesFolder}/${CFBundleIconFile}" \
  753. -Xdock:name="${CFBundleName}" \
  754. ${JVMOptionsArr:+"${JVMOptionsArr[@]}" }\
  755. ${JVMDefaultOptions:+$JVMDefaultOptions }\
  756. "${JVMMainClass}"\
  757. ${MainArgsArr:+ "${MainArgsArr[@]}"}\
  758. ${ArgsPassthru:+ "${ArgsPassthru[@]}"}

4.保存后再次打开即可

搞定

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/829475
推荐阅读
相关标签
  

闽ICP备14008679号