码迷,mamicode.com
首页 > 编程语言 > 详细

Java Main参数解析(Args4j)

时间:2018-11-18 00:42:42      阅读:560      评论:0      收藏:0      [点我收藏+]

标签:alias   date   argument   实现   生成   meta   mail   邮箱   action   

最近实现一个工具,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}")
}
}

Java Main参数解析(Args4j)

标签:alias   date   argument   实现   生成   meta   mail   邮箱   action   

原文地址:https://www.cnblogs.com/barrywxx/p/9976543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!