Friday, May 13, 2022

Script to start/stop java service


#!/bin/bash

JAVA_HOME=/opt/jdk-17
BASEDIR=/opt/myjava-server
PID="$BASEDIR"/myjava-server.pid
LOG="$BASEDIR"/logs/myjava-server.log
REPO="$BASEDIR"/lib
JARPATH="$REPO"/myajava-server.jar
MAINCLASS=com.test.java.MyJavaServer
RUNCMD="$JAVACMD $JAVA_OPTS --add-opens java.base/java.lang=ALL-UNNAMED -classpath $JARPATH $MAINCLASS $@"


# If a specific java binary isn't specified search for the standard 'java' binary
if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD=`which java`
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly." 1>&2
  echo "  We cannot execute $JAVACMD" 1>&2
  exit 1
fi



case "$1" in
start)
   exec $RUNCMD > "$LOG" 2>&1 &
   echo $!>"$PID"
   ;;
stop)
   kill `cat "$PID"`
   rm "$PID"
   ;;
restart)
   $0 stop
   $0 start
   ;;
status)
   if [ -e "$PID" ]; then
      echo server is running, pid=`cat "$PID"`
   else
      echo server is NOT running
      exit 1
   fi
   ;;
*)
   echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0