Java Launcher scripts for multiple platforms

Source: Internet
Author: User
Tags goto posix

Often, too long commands are annoying for services, and people need simple operations and support complex functions, especially for Java-developed services.
A more complex jar service starts with Java and commands the following

Java-xms512m-xmx512m-jar fuck.jar–config Config.server-port 10086

In fact, the host command format for many virtual machine languages is similar.
Our analysis can be known for virtual machine-based languages, the command line is basically HOST+VM run parameters + Execute file path + input parameters.
Of course, if there are fewer parameters, we don't have to write a launcher script to manage the service.

The commands that the launcher script needs to provide are at least:
1. Start
2. Stop
3. Restart
4. Status
5. Help

Realize

On Linux systems, startup scripts should be simple, not overly dependent, and in general, Shell scripting is recommended, in fact many of the software's launcher on Linux use the shell language. Android Studio,brackets Codebox, and even Chrome Firefox has a shell script launcher.
Early in Windows, some software used CMD to write the launcher, but the function of CMD is weak, Microsoft timely launched the Powershell,powershell is very powerful, even better than the shell, so the use of PowerShell to write the launcher, and write a CMD-assisted script to start PowerShell.

@echo offif not exist "%~dp0launcher.ps1" goto NotFoundPowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ‘‘; [System.Threading.Thread]::CurrentThread.CurrentUICulture = ‘‘;& ‘%~dp0launcher.ps1‘ %*"goto :EOF:NotFoundecho Not Found launcher.ps1 in %~dp0,Please reset your launcherPAUSE
Read the configuration file

Choosing the right profile simplifies the operation, and complex configuration files are difficult to implement for simple shell scripts. I launcher the configuration file into two categories, one is the JVM parameters, that is, the "-xms512m-xmx512m" above the format of the file is read by the line, the beginning of the existence of the ' # ' character is discarded.
The other is the Ini-style-based configuration file, mainly the path of the JDK, the path of the jar package that needs to be run, and the redirection settings, which are migrated to the Windows and POSIX sections due to the differences in the file systems of Windows and Linux.

Bash parsing INI file:



function GetPrivateProfileString(){if [ ! -f $1 ] || [ $# -ne 3 ];thenreturn 1fiblockname=$2fieldname=$3begin_block=0end_block=0cat $1 | while read linedoif [ "X$line" = "X[$blockname]" ];thenbegin_block=1continuefiif [ $begin_block -eq 1 ];thenend_block=$(echo $line | awk ‘BEGIN{ret=0} /^\[.*\]$/{ret=1} END{print ret}‘)if [ $end_block -eq 1 ];then#echo "end block"breakfineed_ignore=$(echo $line | awk ‘BEGIN{ret=0} /^#/{ret=1} /^$/{ret=1} END{print ret}‘)if [ $need_ignore -eq 1 ];then#echo "ignored line:" $linecontinuefifield=$(echo $line | awk -F= ‘{gsub(" |\t","",$1); print $1}‘)#####Fix Me We Support Space Valuevalue=$(echo $line | awk -F= ‘{gsub("","",$2); print $2}‘)#echo "‘$field‘:‘$value‘"if [ "X$fieldname" = "X$field" ];then#echo "result value:‘$result‘"echo $valuebreakfifidonereturn 0}

PowerShell parsing INI file:


Function Parser-IniFile{ param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter Your Ini File Path")] [ValidateNotNullorEmpty()] [String]$File ) $ini = @{} $section = "NO_SECTION" $ini[$section] = @{} switch -regex -file $File { "^\[(.+)\]$" { $section = $matches[1].Trim() $ini[$section] = @{} } "^\s*([^#].+?)\s*=\s*(.*)" { $name,$value = $matches[1..2] # skip comments that start with semicolon: if (!($name.StartsWith(";"))) { $ini[$section][$name] = $value.Trim() } } } $ini}

Detection of JDK

Looking at the Java path, typically, the launcher script reads the Java_home key value of the POSIX (Windows) section from Launcher.cfg, if there is no java_home variable to read the java_home of the environment variable, if there is a Java _home, but the actual path does not exist, or there is no java_home, then the path from the lookup java. The Java_home setting can still choose the JDK correctly when there are multiple jdk. Without conflict.

jdkenv=$(GetPrivateProfileString launcher.cfg Posix JAVA_HOME)javabin=`which java`if [ -f "$jdkenv/bin/java" ]; thenjavabin="$jdkenv/bin/java"fi

The Get-javase function is designed to support querying JDK installations from the registry. So I wrote a function separately.



Function Get-JavaSE{ $jdk=$env:JAVA_HOME #This is regedit search java return $jdk}$JdkRawEnv=$IniAttr["Windows"]["JAVA_HOME"]$JavaEnv="$env:JAVA_HOME"IF($JdkRawEnv -eq $null){ $JavaEnv=Get-JavaSE}else{ $JavaEnv=$JdkRawEnv}

Management of processes

First say Powershell,powershell is object-oriented, we can easily get into the object of the city.
We use start-process to start a process. In this cmdlet we add-passthru to get a process object


$ProcessObj= Start-Process -FilePath "${JavaExe}" -PassThru -Argumentlist "${VMOptions} -jar ${PrefixDir}\${AppPackage} $Parameters" -RedirectStandardOutput "${StdoutFile}" -RedirectStandardError "${StdErrorFile}" -WindowStyle Hidden

$PROCESSOBJ can get the ID of the process, the mirror name of the process, and the resource usage of the process.
Of course, process objects are also available in get-process.
Use Get-process to get a process that is better if you have a process ID. Throws an exception if no process with ID exists

$Obj=Get-Process -Id $javaid

To end a process requires stop-process just enter the-id Id.
For Linux, there are file system/proc, also can realize the function of PowerShell. Determine if the process exists to detect whether/PROC/ID exists, and you can check/proc/id/status to see what the resource occupies.
We are in the directory where the launcher script is located (usually the directory where the jar package is located) when the Java process starts successfully, we write the PID to Launcher.lock.pid to use the ID of the Launcher.lock.pid store when it needs to be stopped and restarted.
The PID can be read with get-content in PowerShell. In Linux, you can use cat.

Eventually

The above code has been managed to [email protected]
Project: Servicelauncher Use the MIT protocol to welcome pull Request.

Java Launcher scripts for multiple platforms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.