当前位置: 移动技术网 > IT编程>开发语言>Java > 简介Java程序的Shell脚本包装

简介Java程序的Shell脚本包装

2019年07月22日  | 移动技术网IT编程  | 我要评论

在许多java工程中,经常会看到带有程序自定义参数调用java命令的包装shell脚本。例如,
 

$ant_home/bin/ant, $groovy_home/bin/groovy

,甚至在我们的timemachine scheduler程序中也能见到
 

$timemachine_home/bin/scheduler.sh

编写这些包装脚本很无聊而且容易出错。大多数的问题来自为程序设置正确的classpath。如果你正在为一个公司开发内部项目的话,那么你有可能远离纠结的路径以及环境变量问题。但是对于开源项目,人们需要使包装更加灵活和通用。大多数甚至提供了.bat版本。windows dos确实是个野蛮且被限制的终端而不能很好的满足你项目脚本需求。因此,我常鼓励别人尽量还是多使用cygwi。至少它具备一个真实的bash shell。其他常见的问题就是这些包装很快就会失去控制而且在你的项目各处都会出现很多冗余脚本。

run-java包装脚本介绍

如果你看到 $timemachine_home/bin/scheduler.sh 的代码,你会看到它其实是在同目录下循环调用run-java脚本。
 

dir=$(dirname $0)
scheduler_home=$dir/..
$dir/run-java -dscheduler.home="$scheduler_home" timemachine.scheduler.tool.schedulerserver "$@"

正如你看到的,我们的 run-java 可以使用 -d 选项,不仅这样,它同样也能使用 -cp 选项!而且,你还能在main class后面指定这些选项!这样能够使得run-java被其他的脚本包装,并且仍旧能够添加额外的系统属性以及classpath。

例如,timemachine 附带了 groovy 库,所以你可以简单的像这样调用
 

groovy:$timemachine_home/bin/run-java groovy.ui.groovymain test.groovy

,而不用再次下载整个分支。

你可以很方便地在任何目录下使用,它确认自己的目录然后可以自动加载lib目录下的任何jar包。现在如果你想要附加更多的jar包来运行groovy的话,可以如下使用 -cp 选项:
 

$timemachine_home/bin/run-java -cp "$home/apps/my-app/lib/*" groovy.ui.groovymain test.groovy
通常如果你设置java classpath不够小心时会经常导致错误,但是使用 run-java 可以预先运行一次:
 
run_java_dry=1 $timemachine_home/bin/run-java -cp "$home/apps/my-app/lib/*" groovy.ui.groovymain test.groovy

你只需在命令提示行中运行上面一整行代码即可。它将输出完整的附带所有选项和参数的java命令。

run-script还包含很多其它的选项,你可以通过查看其注释了解。当前的脚本能够在任何的linux bash和windows cygwin中运行。


在开发中通过maven使用 run-java

根据上面提到的示例,假设项目发布结构如下:

$timemachine_home
 +- bin/run-java
 +- lib/*.jar

但是在开发过程中目录会是怎样呢?一个常见的用例便是:你希望能够运行target/classes下最新编译的代码而不是将整个项目打包或者发布。你同样可以在此种情况下使用 run-java 。首先,简单的将 bin/run-java 添加进你的项目,然后运行
 

mvn compile dependency:copy-dependencies

将会在target/dependency下生成所有的jar文件。就只需要做这些。run-java将自动的检测这些目录,并为你的main class创建正确的classpath。

如果你使用eclipse来开发,那么你的target/classes目录将总是在更新的,run-java便能成为你项目开发中的瑰宝。

获取 run-java 包装脚本
 

#!/usr/bin/env bash
#
# copyright 2012 zemian deng
#
# 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.
 
# a wrapper script that run any java6 application in unix/cygwin env.
#
# this script is assumed to be located in an application's "bin" directory. it will
# auto resolve any symbolic link and always run in relative to this application
# directory (which is one parent up from the script.) therefore, this script can be
# run any where in the file system and it will still reference this application
# directory.
#
# this script will by default auto setup a java classpath that picks up any "config"
# and "lib" directories under the application directory. it also will also add a
# any typical maven project output directories such as "target/test-classes",
# "target/classes", and "target/dependency" into classpath. this can be disable by
# setting run_java_no_parse=1.
#
# if the "default parameters" section bellow doesn't match to user's env, then user
# may override these variables in their terminal session or preset them in shell's
# profile startup script. the values of all path should be in cygwin/unix path,
# and this script will auto convert them into windows path where is needed.
#
# user may customize the java classpath by setting run_java_cp, which will prefix to existing
# classpath, or use the "-cp" option, which will postfix to existing classpath.
#
# usage:
# run-java [java_opts] <java_main_class> [-cp /more/classpath] [-dsysprop=value]
#
# example:
# run-java example.hello
# run-java example.hello -dname=world
# run-java org.junit.runner.junitcore example.hellotest -cp "c:\apps\lib\junit4.8.2\*"
#
# created by: zemian deng 03/09/2012
 
# this run script dir (resolve to absolute path)
script_dir=$(cd $(dirname $0) && pwd) # this dir is where this script live.
app_dir=$(cd $script_dir/.. && pwd)  # assume the application dir is one level up from script dir.
 
# default parameters
java_home=${java_home:=/apps/jdk}  # this is the home directory of java development kit.
run_java_cp=${run_java_cp:=$classpath}  # a classpath prefix before -classpath option, default to $classpath
run_java_opts=${run_java_opts:=}   # java options (-xmx512m -xx:maxpermsize=128m etc)
run_java_debug=${run_java_debug:=}   # if not empty, print the full java command line before executing it.
run_java_no_parse=${run_java_no_parse:=} # if not empty, skip the auto parsing of -d and -cp options from script arguments.
run_java_no_autocp=${run_java_no_autocp:=} # if not empty, do not auto setup java classpath
run_java_dry=${run_java_dry:=}    # if not empty, do not exec java command, but just print
 
# os specific support. $var _must_ be set to either true or false.
cygwin=false;
case "`uname`" in
 cygwin*) cygwin=true ;;
esac
 
# define where is the java executable is
java_cmd=java
if [ -d "$java_home" ]; then
  java_cmd="$java_home/bin/java"
fi
 
# auto setup applciation's java classpath (only if they exists)
if [ -z "$run_java_no_autocp" ]; then
  if $cygwin; then
    # provide windows directory conversion
    java_home_win=$(cygpath -aw "$java_home")
    app_dir_win=$(cygpath -aw "$app_dir")
 
    if [ -d "$app_dir_win\config" ]; then run_java_cp="$run_java_cp;$app_dir_win\config" ; fi
    if [ -d "$app_dir_win\target\test-classes" ]; then run_java_cp="$run_java_cp;$app_dir_win\target\test-classes" ; fi
    if [ -d "$app_dir_win\target\classes" ]; then run_java_cp="$run_java_cp;$app_dir_win\target\classes" ; fi
    if [ -d "$app_dir_win\target\dependency" ]; then run_java_cp="$run_java_cp;$app_dir_win\target\dependency\*" ; fi
    if [ -d "$app_dir_win\lib" ]; then run_java_cp="$run_java_cp;$app_dir_win\lib\*" ; fi
  else
    if [ -d "$app_dir/config" ]; then run_java_cp="$run_java_cp:$app_dir/config" ; fi
    if [ -d "$app_dir/target/test-classes" ]; then run_java_cp="$run_java_cp:$app_dir/target/test-classes" ; fi
    if [ -d "$app_dir/target/classes" ]; then run_java_cp="$run_java_cp:$app_dir/target/classes" ; fi
    if [ -d "$app_dir/target/dependency" ]; then run_java_cp="$run_java_cp:$app_dir/target/dependency/*" ; fi
    if [ -d "$app_dir/lib" ]; then run_java_cp="$run_java_cp:$app_dir/lib/*" ; fi
  fi
fi
 
# parse addition "-cp" and "-d" after the java main class from script arguments
# this is done for convenient sake so users do not have to export run_java_cp and run_java_opts
# saparately, but now they can pass into end of this run-java script instead.
# this can be disable by setting run_java_no_parse=1.
if [ -z "$run_java_no_parse" ]; then 
  # prepare variables for parsing
  found_cp=
  declare -a new_args
  idx=0
   
  # parse all arguments and look for "-cp" and "-d"
  for arg in "$@"; do
    if [[ -n $found_cp ]]; then 
      if [ "$os" = "windows_nt" ]; then
        # can't use cygpath here, because cygpath will auto expand "*", which we do not
        # want. user will just have to use os path when specifying "-cp" option.  
        #arg=$(cygpath -w -a $arg)
        run_java_cp="$run_java_cp;$arg"
      else
        run_java_cp="$run_java_cp:$arg"
      fi
      found_cp=
    else
      case $arg in
      '-cp')
        found_cp=1
        ;;
      '-d'*)
        run_java_opts="$run_java_opts $arg"
        ;;
      *)
        new_args[$idx]="$arg"
        let idx=$idx+1
        ;;
      esac
    fi
  done
     
  # display full java command.
  if [ -n "$run_java_debug" ] || [ -n "$run_java_dry" ]; then
    echo "$java_cmd" $run_java_opts -cp "$run_java_cp" "${new_args[@]}"
  fi
   
  # run java main class using parsed variables
  if [ -z "$run_java_dry" ]; then
    "$java_cmd" $run_java_opts -cp "$run_java_cp" "${new_args[@]}"
  fi
else
  # display full java command.
  if [ -n "$run_java_debug" ] || [ -n "$run_java_dry" ]; then
    echo "$java_cmd" $run_java_opts -cp "$run_java_cp" "$@"
  fi
   
  # run java main class
  if [ -z "$run_java_dry" ]; then
    "$java_cmd" $run_java_opts -cp "$run_java_cp" "$@"
  fi
fi

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网