zoukankan      html  css  js  c++  java
  • Java Main参数解析(Args4j)

    最近实现一个工具,Main函数会有很多参数,而且参数类型不同,为了统一解析,网上找到三方工具类Args4j,轻松搞定。

    代码实例如下:

    定义解析类:

    import java.io.File
    
    import org.kohsuke.args4j.Option
    import org.slf4j.LoggerFactory
    
    
    /**
      * 数据库报表生成命令行参数定义
      *
      * @author BarryWang create at 2018/6/23 20:21
      * @version 0.0.1
      */
    class ArgOptions {
      val logger= LoggerFactory.getLogger(classOf[ArgOptions])
    
      /**
        * 对象名及查询SQL脚本对,中间用英文分号":"隔开
        */
      val query = new scala.collection.mutable.ListBuffer[(String, String, String)];
      @Option(name = "-q",
              aliases = Array("-query"),
              metaVar = "<db>:<objectName>:<sql>",
              usage = "对象名及查询SQL脚本对,中间用英文分号“:”隔开, 例如database:objectName:sql。(String)")
      def setProperty(property: String): Unit = {
        var arr = property.split(":")
        arr.length match {
          case 3 => query.+=((arr(0), arr(1), arr(2)))
          case _ => logger.info("-query 传入参数格式错误, 正确格式: <db>:<objectName>:<sql>")
        }
      }
    
      /**
        * JXLS Excel模板文件绝对路径
        */
      @Option(name = "-t",
              aliases = Array("-template"),
              metaVar = "<template file>",
              usage = "JXLS Excel模板文件绝对路径, 请参考:http://jxls.sourceforge.net/reference/simple_exporter.html。(File)" )
      var template: File = null
    
      /**
        * Scala脚本文件
        */
      @Option(name = "-s",
              aliases = Array("-script"),
              metaVar = "<scala script file path>",
              usage = "Scala脚本文件, 请参考:http://ammonite.io/#ScalaScripts。(String)")
      var script: String = null
    
      /**
        * 输出Excel文件
        */
      @Option(name = "-o",
              aliases = Array("-output"),
        /* required = true,handler = classOf[StringArrayOptionHandler],*/
              metaVar = "<output excel file>",
              usage = "输出Excel文件绝对路径。(File)")
      var output: String = null
    
      /**
        * 输出Excel文件
        */
      @Option(name = "-m",
        aliases = Array("-mailto"),
        metaVar = "<email>",
        usage = "生成报表发送邮箱,多个使用英文分号“;”分割。(String)")
      var email: String = null
    
    
      /**
        * 邮件主题
        */
      @Option(name = "-sub",
        aliases = Array("-subject"),
        metaVar = "<subject>",
        usage = "邮件主题。(String)")
      var subject: String = null
    }


    引用解析类如下:

    import java.io.File
    import java.util.Date
    
    import com.today.dbreport.action.impl.{GenReportByScriptAction, GenReportBySqlAction, GenReportByTemplateBySqlAction}
    import com.today.dbreport.dto.GenReportParam
    import com.today.dbreport.utils.EmailUtil
    import com.today.service.commons.util.DateTools
    import org.kohsuke.args4j.CmdLineParser
    import org.slf4j.LoggerFactory
    
    import scala.collection.JavaConverters._
    
    /**
      * 生成报表入口
      *
      * @author BarryWang create at 2018/6/1 11:02
      * @version 0.0.1
      */
    object Main {
      val logger= LoggerFactory.getLogger(Main.getClass)
    
      def main(args: Array[String]): Unit = {
        val options = new ArgOptions
        val parser = new CmdLineParser(options)
        // print usage
        parser.printUsage(System.out)
        parser.parseArgument(args.toList.asJava)
    
        //输出文件或发送邮件必填一个
        if(options.output == null && options.email == null){
          println("请传入参数-output 或 -mailto其中之一")
          return
        }
    
        //生成报表地址
        var utf8Output = ""
        if (options.output != null) {
            utf8Output = new String(options.output.getBytes("UTF-8"), "UTF-8")
        } else {//本地临时文件
          val currentTime = DateTools.format(new Date(), "yyyyMMddHHmmssSSS")
          val outDir = s"${System.getProperty("user.dir")}${File.separator}output"
          var outputDir = new File(outDir)
          if(!outputDir.exists()){
            outputDir.mkdirs()
          }
          utf8Output = s"${outDir}${File.separator}${currentTime}.xlsx"
        }
        //带有Scala脚本
        if (options.script != null) {
          var templateOptional: Option[File] = None
          if (options.template != null) {
            templateOptional = Some(options.template)
          }
          val scriptOptional = Some(options.script)
          var mailtoOptional: Option[String] = None
          if (options.email != null) {
            mailtoOptional = Some(options.email)
          }
          val genReportParam = new GenReportParam(options.query, utf8Output, templateOptional, scriptOptional, mailtoOptional)
          //sql + script + jxls template
          //script + jxls tempalte
          new GenReportByScriptAction(genReportParam).execute
        } else {//无Scala脚本
          var templateOptional: Option[File] = None
          if (options.template != null){
            templateOptional = Some(options.template)
          }
          var scriptOptional : Option[String] = None
          if(options.script != null){
            scriptOptional = Some(options.script)
          }
    
          var mailtoOptional: Option[String] = None
          if (options.email != null){
            mailtoOptional = Some(options.email)
          }
    
          val genReportParam = new GenReportParam(options.query, utf8Output, templateOptional, scriptOptional, mailtoOptional)
          if (options.template != null) { //sql* + jxls template
            new GenReportByTemplateBySqlAction(genReportParam).execute
          } else { //no template + sql
            new GenReportBySqlAction(genReportParam).execute
          }
        }
    
        println(s"报表生成成功${utf8Output}!")
        //发送邮件
        if (options.email != null) {
          var subject = "报表工具生成报表"
          if(options.subject != null){
            subject = options.subject
          }
          EmailUtil.sendEmail(options.email.trim, subject, "生成报表请参考附件", utf8Output)
          println("邮件发送成功,请邮件附件下载相关报表!")
          //邮件发送成功, 删除本地临时文件
          if (options.output == null) {
            new File(utf8Output).deleteOnExit()
          }
        }
        logger.info(s"报表生成成功${utf8Output}")
      }
    }
    
    
    运行main函数会展示如下提示:
     -f (-from) <from>                     : 邮件发送者。(String)
     -m (-mailto) <email>                  : 生成报表发送邮箱,多个使用英文分号“;”分割。(String)
     -o (-output) <output excel file>      : 输出Excel文件绝对路径。(File)
     -q (-query) <db>:<objectName>:<sql>   : 对象名及查询SQL脚本对,中间用英文分号“:”隔开,
                                             例如database:objectName:sql。(String)
     -s (-script) <scala script file path> : Scala脚本文件, 请参考:http://ammonite.io/#Scal
                                             aScripts。(String)
     -sub (-subject) <subject>             : 邮件主题。(String)
     -t (-template) <template file>        : JXLS Excel模板文件绝对路径, 请参考:http://jxls.sou
                                             rceforge.net/reference/simple_exporter.
                                             html。(File)
    请传入参数-output 或 -mailto其中之一
    

      

    是不是就看起来很直观了!

  • 相关阅读:
    原子操作--sync/atomic的用法
    基础的排序算法以及查找算法
    (三)MySQL终极篇
    (二)MySQL中级篇
    数据库表添加索引对性能的影响
    事务的四大特性以及事务的隔离级别
    int 和Integer
    数据库三范式
    Java反射
    获取Class实例的三种方式
  • 原文地址:https://www.cnblogs.com/barrywxx/p/9976543.html
Copyright © 2011-2022 走看看