`

Show Your ToolBox——锋利的groovy

 
阅读更多

在工作中使用groovy做了很多辅助工具,这里以代码形式发出来,和喜欢groovy的童鞋们交流下

 

1. 文件操作类

1.1 清除.svn文件夹

import static groovy.io.FileType.*

new File('.').eachFileRecurse(DIRECTORIES, ~/^\.svn$/){
	it.delete()
}
 

 

1.2 在一堆jar中找一个class

 

import java.util.Enumeration
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream

def findJarFile(File zipFile, String target){
	ZipFile zip = new ZipFile(zipFile)
	ZipEntry entry = null
	Enumeration<? extends ZipEntry> en = zip.entries()
	while (en.hasMoreElements()) {
		entry = en.nextElement()
		if (entry.isDirectory()) {
			continue
		}

		if(entry.name.endsWith(target)){
			println zipFile.name
			println entry
		}
	}
	zip.close()
}

String target = 'TESTMY.class'
new File('D:/lib').eachFile{
	if(it.name.endsWith('.jar'))
		findJarFile(it, target)
}

 

 

1.3 从mvn repository下载一个jar到groovy.conf的path下()

import groovy.grape.Grape

String dir_lib = System.getProperty('user.home').replaceAll("\\\\", '/') + 
	'/.groovy/lib/'
List mvn = [
	'org.apache.poi', 
	'poi', 
	'3.7'
]
Grape.grab(group:mvn[0], 
	module:mvn[1], version:mvn[2])

String jar_path = System.getProperty('user.home').replaceAll("\\\\", '/') + 
	'/.groovy/grapes/' + mvn[0] + '/' + mvn[1] + '/jars/' + mvn[1] + '-' + mvn[2] + '.jar'

def ant = new AntBuilder()
ant.copy file : jar_path, todir : dir_lib
 

1.4 比较文件夹下的文件不同

String path1 = 'D:/soft/eclipse/plugins/org.apache.ant_1.7.0.v200803061910/lib'

String path2 = 'C:/ANT_HOME/Apache-Ant-1.7.0/lib'

List ll = new File(path1).listFiles().collect{it.name}
List ll2 = new File(path2).listFiles().grep{it.name.endsWith('.jar')}.collect{it.name}

def ant = new AntBuilder()
(ll2 - ll).each{
	ant.copy todir : path1, file : path2 + '/' + it
}
 

1.5 下载一个url到本地文件(爬漫画弄个多线程,很给力的)

 

long begin = System.currentTimeMillis()
String url = 'http://**host.com/***'
new File('output.xml') << new URL(url).text
println System.currentTimeMillis() - begin

 

 

2. 用一些第三方库

2.1 jxl

import jxl.*

String path = "my.xls"
int begin_row = 1
List cols = 'a'..'l'
List ll = []

File file = new File(path)
Workbook wb =  Workbook.getWorkbook(file)
def sheet = wb.sheets[0]

for(i in begin_row..<sheet.rows){
	Map item = [:]
	cols.eachWithIndex{cc, j ->
		Cell cell = sheet.getCell(j, i)
		String content = cell.getContents()
		if(content == null)
			content = ''

		item[cc] = content
	}
	if(item[cols[0]])
		ll << item
}

// excel -> 到一个二位列表了ll,然后你就可以随心所欲了

  2.2 email

import java.security.Security;

import javax.mail.* 

final String POP3Host = '***'
final String userName = 'xx'
final String pwd = 'xxx'

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider())
def prop = System.getProperties()
prop.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
prop.setProperty("mail.pop3.socketFactory.fallback", "false")
prop.put("mail.pop3.host", POP3Host)
prop.put("mail.imap.starttls.enable", "true")
prop.put("mail.debug", "true")
prop.setProperty("mail.pop3.port ", "995")
prop.setProperty("mail.pop3.socketFactory.port", "995")

def auth = [
	getPasswordAuthentication : {
		new PasswordAuthentication(userName, pwd)
	}
] as Authenticator
def s = Session.getDefaultInstance(prop, auth)
def store = s.getStore("pop3")  
store.connect(POP3Host, userName, pwd) 

Folder folder = store.getFolder("Inbox")  
folder.open(Folder.READ_ONLY) 

FetchProfile profile = new FetchProfile()  
profile.add(FetchProfile.Item.ENVELOPE) 
Message[] arr = folder.getMessages()
folder.fetch(arr, profile) 

println "收件箱的邮件数:" + arr.length  

folder.close(false) 
store.close()

 

2.3 css压缩

def ant = new AntBuilder()

String dir = 'cssjs'

ant.taskdef name: 'yuicompress', 
	classname: 'com.yahoo.platform.yui.compressor.YUICompressTask'

ant.yuicompress linebreak: 300, warn: 'false', munge: 'yes', 
	preserveallsemicolons: 'true', outputfolder: dir, {
		fileset dir: dir, {
			include name: '*.css'
		}
	}

  2.4 执行下fastjson方法

import com.alibaba.fastjson.JSON

import com.alibaba.fastjson.parser.Feature
import com.alibaba.fastjson.serializer.SerializerFeature

List ll = [[test: 'test']]
def sll = [] as SerializerFeature[]
def fll = [] as Feature[]

def bytes = JSON.toJSONBytes(ll, sll)

println JSON.parse(bytes, fll)

  2.5 jftp

import net.sf.jftp.net.* 
import net.sf.jftp.config.Settings

import org.apache.commons.io.IOUtils
   
String host = "xx"
int port = 22
String user = "xx"
String pwd = "xx"

String file = "/xx.txt"

Settings.bufferSize = 16384  
def con = new FtpConnection(host, port, "<default>")
con.setConnectionHandler(new ConnectionHandler()) 
con.login(user, pwd) 
           
InputStream is = con.getDownloadInputStream(file) 
IOUtils.copy(is, new FileOutputStream(new File(file)))
 

3. 文本分析类——这块就用起来比较多了,数据源可以是文本,excel,db,下面只贴一个我最近做的一个分析友盟(umeng.com)自定义事件的一个数据分析的代码(业务场景是ios的一个应用做一个发送、接收的动作,分析下一天中这些动作的错误情况),我贴这段代码没有实际参考价值,只能表明groovy可以做很多很多的事儿

import groovy.sql.Sql

final String format = 'yyyy-MM-dd'
final List versions = ['2.1.9', '2.2.0', 
	'2.2.1', '2.2.2', '2.2.3']
final List datRange = Date.parse(format, '2012-07-07')..Date.parse(format, '2012-07-09')
def pat = /,,,/

// 去掉第一行,取一天的数据和一个版本的数据
def ll = []
new File('umeng').eachFile{ff ->
	ll += ff.readLines()[1..-1]
}

// 中文字符对齐
def padRightGbk = {str, num ->
	return str
//	return str.padRight(num - str.bytes.size() + str.size())
}

def getLinesTarget = {dat, version ->
	def rll = ll.grep{
		it.contains(version)
	}

	if(dat)
		rll = rll.grep{it.startsWith(dat)}
	return rll
}

def printStat = {lines, version ->
	// 发送成功率统计
	def sendLl = lines.grep{
		def arr = it.split(pat)
		// 参数值
		String result = arr[2]
		return result.contains('上传开始') || 
			result.contains('上传结束')
	}.collect{
		def arr = it.split(pat)

		String dat = arr[0]
		
		// 参数值
		String result = arr[2]
		String reportId = result.split(' ')[0]
		String sendTimes = arr[4]

		String type = 'end'
		if(result.endsWith('上传开始'))
			type = 'start'

		boolean flag = false
		String typeEnd = 'endOk'

		// 发送成功,有结束返回且不是网络超时
		if(result.contains('上传结束')){
			if(result.endsWith('上传结束')){
				typeEnd = 'endOk'
				flag = true
			}else{
				if(result.contains('网络超时')){
					typeEnd = 'endTimeout'
				}else{
					typeEnd = 'endFail'
				}
			}
		}

		return [reportId: reportId, type: type, flag: flag, typeEnd: typeEnd, 
			sendTimes: Double.valueOf(sendTimes), dat: dat]
	}

	// ID列表
	def reportIdLl = sendLl.clone().collect{it.reportId}.unique().sort()
	def sendResultLl = reportIdLl.collect{reportId ->
		def llSub = sendLl.grep{it.reportId == reportId}
		// 最终发送成功的标示
		boolean isOk = llSub.any{'end' == it.type && it.flag}

		def startLl = llSub.grep{'start' == it.type}
		def endLlOk = llSub.grep{'end' == it.type && 'endOk' == it.typeEnd}
		def endLlFail = llSub.grep{'end' == it.type && 'endFail' == it.typeEnd}
		def endLlTimeout = llSub.grep{'end' == it.type && 'endTimeout' == it.typeEnd}

		int startSendTimes = 0
		if(startLl){
			startSendTimes = startLl.sum{it.sendTimes ?: 0}
		}

		int endSendTimesOk = 0
		if(endLlOk){
			endSendTimesOk = endLlOk.sum{it.sendTimes ?: 0}
		}

		int endSendTimesFail = 0
		if(endLlFail){
			endSendTimesFail = endLlFail.sum{it.sendTimes ?: 0}
		}

		int endSendTimesTimeout = 0
		if(endLlTimeout){
			endSendTimesTimeout = endLlTimeout.sum{it.sendTimes ?: 0}
		}

		return [isOk: isOk, reportId: reportId, 
			startNum: startLl.size(), 
			endNumOk: endLlOk.size(), 
			endNumFail: endLlFail.size(), 
			endNumTimeout: endLlTimeout.size(), 
			startSendTimes: startSendTimes, 
			endSendTimesOk: endSendTimesOk,
			endSendTimesFail: endSendTimesFail, 
			endSendTimesTimeout: endSendTimesTimeout, 
			dat: llSub ? llSub[0]['dat'] : '',
			version: version
			]
	}

	// 把分析出来的结果放到数据库里以利用sql进行分析
	if(sendResultLl){
		def p = [
		  url:'jdbc:h2:tcp://localhost/data/all/crashreport', 
		  u:'sa', 
		  p:'', 
		  driver:'org.h2.Driver'
		]
		def db = Sql.newInstance(p.url, p.u, p.p, p.driver)

		try {
			db.execute('''
			create table if not exists t_send_stat(
				is_ok boolean,
				report_id varchar, 
				
				start_num int,
				end_num_ok int,
				end_num_fail int,
				end_num_timeout int,
				
				start_times int,
				end_times_ok int,
				end_times_fail int,
				end_times_timeout int,

				dat date, 
				version varchar
			);
			'''
			)
			sendResultLl.each{
				db.executeInsert("""
				insert into t_send_stat values(
					?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
				)
				""",
				[it.isOk, it.reportId, 
					it.startNum, 
					it.endNumOk,
					it.endNumFail,
					it.endNumTimeout,
					it.startSendTimes,
					it.endSendTimesOk,
					it.endSendTimesFail,
					it.endSendTimesTimeout,
					it.dat,
					it.version])
			}
		}finally {
		    db.close()
		}
	}
	//def rows = new File('reportSendDept.txt').readLines().collect{
	//	def arr = it.split(pat)
	//	[REPORT_ID: arr[1], COMPANY_CODE: arr[-1]]
	//	// substring(0, 3)
	//}
	//sendResultLl.each{
	//	def item = rows.find{row -> row['REPORT_ID'] == it.reportId}
	//	it.dept = item ? item['COMPANY_CODE'] : '???'
	//}
	/*
	CREATE CACHED TABLE T_SEND_STAT(
		FLAG BOOL,
		REPORT_ID VARCHAR(20),
		NUM_START INT,
		NUM_END_OK INT,
		NUM_END_FAIL INT,
		TIMES_START INT,
		TIMES_END_OK INT,
		TIMES_END_FAIL INT,
		DEPT VARCHAR(10)
	);

	insert into T_SEND_STAT select csvread('data/reportSendDept.txt');
	*/

	// 总数
	int numAll = sendResultLl.size()
	if(!numAll)
		return

	// 发送总数
	int numOk = sendResultLl.grep{it.isOk}.size()
	int numFail = numAll - numOk

	// 无返回结果的发送
	int numFailWithNoErrorEnd = sendResultLl.grep{
		!it.isOk && it.endNumError == 0
	}.size()

	final int padNum = 30
//	print padRightGbk('总数', padNum) + ',' + numAll + ','
//	print padRightGbk('发送成功总数', padNum) + ',' + numOk + ','
//	print padRightGbk('发送失败总数', padNum) + ',' + numFail + '(其中无返回信息' + numFailWithNoErrorEnd + ')' + ','
//	print padRightGbk('发送成功率', padNum) + ',' + (numOk / numAll) + ','

	println '总数,发送成功总数,发送失败总数,其中无返回信息,发送成功率'
	print numAll
	print ','
	print numOk
	print ','
	print numFail
	print ','
	print numFailWithNoErrorEnd
	print ','
	print (numOk / numAll)
	print ','
	println ''

	// 计算消息数
	int startNum = sendResultLl.collect{it.startSendTimes ?: 1}.sum()

	// ****** ****** ****** ****** ****** ****** ****** ****** ******
	// ****** ****** ****** ****** ****** ****** ****** ****** ******
	// ****** ****** ****** ****** ****** ****** ****** ****** ******
	// 更新、发送时长统计
	def sendTimeLl = lines.grep{
		def arr = it.split(pat)
		// 参数
		String key = arr[1]
		return key in ['更新耗时', '上传耗时']
	}.collect{
		def arr = it.split(pat)

		String type = arr[1] == '上传耗时' ? 'up' : 'down'
		String secStr = arr[2]
		if(secStr.contains(':'))
			secStr = secStr.split(':')[1]

		return [type: type, sec: Double.valueOf(secStr), 
			sendTimes: Double.valueOf(arr[4])]
	}

	println '单个刷新总数,平均刷新时间,超7s次数,发送平均时长,超3分钟次数'
	if(sendTimeLl){
		def sendTimeLlDown = sendTimeLl.grep{'down' == it.type}
		if(sendTimeLlDown){
//			print padRightGbk('单个刷新总数', padNum) + ',' + sendTimeLlDown.sum{it.sendTimes ?: 0} + ','
//			print padRightGbk('平均刷新时间', padNum) + ',' + (sendTimeLlDown.sum{it.sec * it.sendTimes} / sendTimeLlDown.sum{it.sendTimes}) + ','
//			print padRightGbk('超7s次数', padNum) + ',' + sendTimeLlDown.grep{it.sec > 7}.size() + ','

			print sendTimeLlDown.sum{it.sendTimes ?: 0}
			print ','
			print (sendTimeLlDown.sum{it.sec * it.sendTimes} / sendTimeLlDown.sum{it.sendTimes})
			print ','
			print sendTimeLlDown.grep{it.sec > 7}.sum{it.sendTimes}
			print ','
		}else{
			print '??,??,??,'
		}

		def sendTimeLlUp = sendTimeLl.grep{'up' == it.type}
		if(sendTimeLlUp){
			print sendTimeLlUp.sum{it.sec * it.sendTimes} / sendTimeLlUp.sum{it.sendTimes}
			print ','
			print sendTimeLlUp.grep{it.sec > 3 * 60}.sum{it.sendTimes} ?: 0
			print ','
		}else{
			print '??,??,'
		}
	}
	println ''
}

def parseStat = {lines ->
	lines.grep{it.contains('上传开始')}.grep{
		def arr = it.split(pat)
		arr[4] != '1.0'
	}.each{
		println it
	}
}

for(version in versions){
	for(dat in datRange){
		String datStr = dat.format(format)
		println datStr + ',' + version.padRight(20)
		List lines = getLinesTarget(datStr, version)
		printStat(lines, version)
	}
}

 

下面一段是根据table ddl(oracle)生成一些项目框架需要的文件(ibatis之类的,abator等工具太不局限了,自己写想怎么生成就怎么生成,顺便推荐大家用用国人的smarty4j,很8错)

 

import xx.Tpl

String dir = './'
String tpl_dir = dir + 'tpl/'

String output_dir = dir + 'output/'
String scriptfile = 'dbscript.sql'
String ns = 'quotation'

File f = new File(dir, scriptfile)

final String begin = 'create table'
final String end = ');'

// 把分析出的表和字段信息保存到这个List中
List dto_ll = []

// 根据ORACLE字段类型对应Java类型
def get_type = {str ->
	if(str.contains('NUMBER'))
		return 'BigDecimal'
	switch (str) {
	    case ~/CHAR/:
	        return 'String'
	    case ~/DATE/:
	        return 'Date'
	    case ~/NUMBER/:
	        return 'BigDecimal'
	    default:
	        return 'String'
	}
}

// 大小写转换到驼峰格式
def get_name = {str ->
	String r = str.toLowerCase().split('_').collect{it.capitalize()}.join('')
	return r[0].toLowerCase() + r[1..-1]
}

// 设置表主键
def add_table_pk = {table, cols ->
	for(item in dto_ll){
		if(item.name.equalsIgnoreCase(table)){
			cols.split(/,/).collect{it.trim()}.each{
				for(col in item.cols){
					if(col.src_name.equalsIgnoreCase(it))
						col.is_pk = true
				}
			}
		}
	}
}

// 添加表注释
def add_table_comment = {table, comment ->
	for(item in dto_ll){
		if(item.name.equalsIgnoreCase(table)){
			item.comment = comment.replaceAll(/\r\n/, ' ')
		}
	}
}

// 添加表字段注释
def add_comment = {table, col, comment ->
	for(item in dto_ll){
		if(item.name.equalsIgnoreCase(table)){
			for(it in item.cols){
				if(it.name == get_name(col)){
					it.comment = comment.replaceAll(/\r\n/, ' ')
				}
			}
		}
	}
}

// 分析表和字段
def parse = { str ->
	def mat = str =~ /(?s)create table ([^\(]+) +\((.+)\);/
	if(!mat)
		return

	String table_name = mat[0][1].toLowerCase().trim()
	String columns = mat[0][2]

	Map item = [name: table_name, 
		clazz: get_name(table_name).capitalize(), cols : []]
	columns.split(',').each{
		def arr = it.split(/\s+/)
		if(arr.size() > 1){
			item.cols << [src_name: arr[0], name: get_name(arr[0]), type: get_type(arr[1])]
		}
	}
	dto_ll << item
}

// 每一行遍历SQL文件,先分析表和字段
StringBuffer buffer = new StringBuffer()
boolean is_begin = false
boolean is_end = true
f.eachLine{line ->
	line = line.trim()
	if(line){
		line = line.replace(/\s+/, ' ')
		if(is_end && line.startsWith(begin)){
			is_begin = true
			is_end = false
		}
		if(is_begin && line.endsWith(end)){
			buffer << line

			is_end = true
			is_begin = false

			parse(buffer.toString())
			buffer.delete(0, buffer.size())
		}

		if(is_begin && !is_end)
			buffer << line
	}
}

// 分析注释(字段)
def mat = f.text =~ /(?s)comment on column ([^;]+) is([^;]+);/
mat.each{
	String table_col = it[1].trim()
	String comment = it[2].replaceAll(/\'/, '').trim()
	
	def arr = it[1].split(/\./)
	String table = arr[0]
	String col = arr[1]

	add_comment(table, col, comment)
}
// 分析注释(表)
def mat2 = f.text =~ /(?s)comment on table ([^;]+) is([^;]+);/
mat2.each{
	String table = it[1].trim()
	String comment = it[2].replaceAll(/\'/, '').trim()
	
	add_table_comment(table, comment)
}

// 分析主外健
def mat3 = f.text =~ /(?s)alter table ([^ ]+)[^;]+primary key \(([^\)]+)\)/
mat3.each{
	String table = it[1].trim()
	String primary_key_cols = it[2].trim()

	add_table_pk(table, primary_key_cols)
}

// 现在已经获取到DDL的信息
// 先创建必要的文件夹
def ant = new AntBuilder()
ant.mkdir dir : output_dir
ant.mkdir dir : output_dir + 'dto'
ant.mkdir dir : output_dir + 'sql'
ant.mkdir dir : output_dir + 'xml'
ant.mkdir dir : output_dir + 'dao'
ant.mkdir dir : output_dir + 'daoImpl'
ant.mkdir dir : output_dir + 'service'
ant.mkdir dir : output_dir + 'serviceImpl'
ant.mkdir dir : output_dir + 'action'
ant.mkdir dir : output_dir + 'test'
ant.mkdir dir : output_dir + 'mock'

//dto_ll.each{
//	println it
//}

final String pkg = 'com.***.' + ns
Tpl.init(tpl_dir, 'gbk')

if(args){
	if(args[0] == 'add'){
		// 生成insert语句
		if(args.size() != 2){
			println '请输入表名!'
		}else{
			String table = args[1]
			for(item in dto_ll){
				if(item.name.equalsIgnoreCase(table)){
					String cols_str = item.cols*.src_name.join(', ')
					String cols_str2 = item.cols*.name.collect{"#" + it + "#"}.join(', ')
					println "insert into ${item.name} (${cols_str}) values (${cols_str2})"
					break
				}
			}
		}
	}else if(args[0] == 'update'){
		// 生成update语句
		if(args.size() != 2){
			println '请输入表名!'
		}else{
			String table = args[1]
			for(item in dto_ll){
				if(item.name.equalsIgnoreCase(table)){
					String cols_str = item.cols.collect{it.src_name + " = #" + it.name + "#"}.join(', ')
					println "update ${item.name} set ${cols_str} where ***"
					break
				}
			}
		}
	}else if(args[0] == 'mock'){
		// 生成dto mock对象
		def out = new FileWriter(new File(new File(output_dir + 'mock'), 
			'DTOMock.java'))
		int half = dto_ll.size() / 2 as int
		Tpl.out([pkg: pkg, clazz: 'Mock', ll: dto_ll[0..half]], 'Mock.java', out)
		def out2 = new FileWriter(new File(new File(output_dir + 'mock'), 
			'DTOMock2.java'))
		Tpl.out([pkg: pkg, clazz: 'Mock2', ll: dto_ll[half + 1..-1]], 'Mock.java', out2)

		println 'Done DTO Mock'
	}else if(args[0] == 'deploy'){
		final String to_dir = 'D:/CCShare/epcis_ahs_dev3.0.0/epcis_ahs/ahs_j2ee/src/'
		String pkg_dir = pkg.replaceAll(/\./, '/')

		// Copy Java
		['/dto' : output_dir + 'dto', 
			'/integration/dao' : output_dir + 'dao', 
			'/integration/dao/ibatis' : output_dir + 'daoImpl', 
			'/biz/service' : output_dir + 'service', 
			'/biz/service/impl' : output_dir + 'serviceImpl', 
			].each{k, v ->
			String dir_to = to_dir + 'java/' + pkg_dir + k
			ant.copy todir : dir_to, {
				fileset dir : v
			}
		}

		// Copy Sql
		// Copy Bean Xml
		ant.copy todir : to_dir + 'config/biz', {
			fileset dir : output_dir + 'sql'
			fileset dir : output_dir + 'xml'
		}		
		println 'Done Deploy'
	}else if(args[0] == 'deploy_clear'){
		final String to_dir = 'D:/CCShare/epcis_ahs_dev3.0.0/epcis_ahs/ahs_j2ee/src/'
		String pkg_dir = pkg.replaceAll(/\./, '/')

		// Delete Java
		['/dto' : output_dir + 'dto', 
			'/integration/dao' : output_dir + 'dao', 
			'/integration/dao/ibatis' : output_dir + 'daoImpl', 
			'/biz/service' : output_dir + 'service', 
			'/biz/service/impl' : output_dir + 'serviceImpl', 
			].each{k, v ->
			String dir_to = to_dir + 'java/' + pkg_dir + k
			ant.delete dir : dir_to
		}

		println 'Clear Deploy'
	}
}else{
	// -- 输出生成DTO Java文件
	// 父类
	final String parent_clazz = 'BaseDTO'
	// 父类的包名
	final String parent_clazz_pkg = 'com.xxx.dto'
	def params = [pkg: pkg]
	params.parent_clazz = parent_clazz
	params.parent_clazz_pkg = parent_clazz_pkg
	dto_ll.each{
		String clazz = get_name(it.name).capitalize()
		params.clazz = clazz
		params.cols = it.cols
		params.has_date = it.cols.any{col -> col.type == 'Date'}
		params.has_bigdecimal = it.cols.any{col -> col.type == 'BigDecimal'}
		params.comment = it.comment

		def out = new FileWriter(new File(new File(output_dir + 'dto'), 
			clazz + 'DTO.java'))
		Tpl.out(params, 'Dto.java', out)

		println 'Done DTO For ' + clazz
	}

	// -- 输出生成Sql Mapping文件
	def params_ll = []
	dto_ll.each{item ->
		def one = [:]
		
		String clazz = get_name(item.name)
		one.clazz = clazz.capitalize()
		one.clazz2 = clazz
		one.comment = item.comment
		one.pk_col = item.cols.grep{it.is_pk}*.name.join(',')

		String cols_str = item.cols*.src_name.join(', ')
		String cols_str2 = item.cols*.name.collect{"#" + it + "#"}.join(', ')
		one.insert_sql = "insert into ${item.name} (${cols_str}) values (${cols_str2})"

		String cols_str3 = item.cols.grep{!it.is_pk}.collect{it.src_name + " = #" + it.name + "#"}.join(', ')
		String cols_str4 = item.cols.grep{it.is_pk}.collect{it.src_name + " = #" + it.name + "#"}.join(' and ')
		one.update_sql = "update ${item.name} set ${cols_str3} where ${cols_str4}"
		String cols_str44 = item.cols.grep{it.is_pk}.collect{it.src_name + " = #value#"}.join(' and ')
		one.delete_sql = "delete from ${item.name} where ${cols_str44}"

		String cols_str5 = item.cols.collect{it.src_name + " " + it.name}.join(', ')
		one.select_sql = "select ${cols_str5} from ${item.name} where 1 = 1 and ${cols_str4}"

		params_ll << one
	}
	def out = new FileWriter(new File(new File(output_dir + 'sql'), "sqlmap-mapping-${ns}.xml"))
	Tpl.out([namespace: ns.capitalize(), pkg: pkg, ll: params_ll], 
		'sql-mapping.xml', out)
	println 'Done Sql'

	// -- 输出dao/serivce
	params_ll.each{
		def params_sub = [pkg: pkg] + it
		def out1 = new FileWriter(new File(new File(output_dir + 'dao'), it.clazz + 'DAO.java'))
		Tpl.out(params_sub, 'IDao.java', out1)

		def out2 = new FileWriter(new File(new File(output_dir + 'daoImpl'), it.clazz + 'IbatisDAO.java'))
		Tpl.out(params_sub, 'Dao.java', out2)
		println 'Done DAO For ' + it.clazz

		def out3 = new FileWriter(new File(new File(output_dir + 'service'), it.clazz + 'Service.java'))
		Tpl.out(params_sub, 'IService.java', out3)
		def out4 = new FileWriter(new File(new File(output_dir + 'serviceImpl'), it.clazz + 'ServiceImpl.java'))
		Tpl.out(params_sub, 'Service.java', out4)
		println 'Done Service For ' + it.clazz
	}

	// -- 输出bean定义
	def out2 = new FileWriter(new File(new File(output_dir + 'xml'), "biz-context-${ns}.xml"))
	Tpl.out([namespace: ns.capitalize(), pkg: pkg, ll: params_ll], 
		'bean.xml', out2)
	println 'Done Bean'

//	ant.zip basedir : dir, destfile : dir + '../my.zip'
}
 

4. 一些算法和无聊写的小程序

模拟下双色球中奖的概率

 

def range = 1..33

int len = 7
List his = [
	[num: 10000, result: [3,5,16,18,23,24,15]], 
]

def rand = new Random()

def play = {
	int cc = 0
	List ll = []
	while(1){
		int one = rand.nextInt(range.size()) + 1
		if(one in ll){
		}else{
			ll << one
		}

		if(ll.size() == len && his.any{it.result == ll}){
			def target = his.find{it.result == ll}

			println cc
			println target.num
			println cc / target.num
			println target

			cc = 0
			ll.removeAll()

			break
		}

		if(ll.size() > len){
			ll.removeAll()
		}

		cc++
	}
}

play()

 

附件是一个简单的数字图像识别的程序——很简单的笔画匹配思路,很弱智的,大家也可以看看

 

 

这些是我零零散散找到的最近写过的groovy脚本——很多只是用到了简单的groovy语言的语法和api,不过很有意思而且确实能给自己带来工作的方便,喜欢groovy的童鞋们,一起继续支持啦

 

 

还有就是建议不要使用eclipse和groovy的插件——不给力的,找个简单的文本编辑器,vim/notepad++/editplus之类的,弄个宏运行bat,更快捷些

  • img.rar (7.6 KB)
  • 下载次数: 11
分享到:
评论
1 楼 悲剧了 2012-08-11  

相关推荐

    SolidWorks.2007.标准件库toolbox——1

    《SolidWorks 2007 标准件库toolbox详解》 SolidWorks是一款广泛应用于机械设计领域的三维CAD软件,以其直观易用的界面和强大的功能深受设计师们的喜爱。在进行机械设计时,标准件的使用不可或缺,这既提高了设计...

    toolbox——sparsity

    toolbox implements several algorithms to compute sparse expansion in redundant dictionaries and to solve inverse problems with sparse regularization

    MATLAB工具箱速查表-matlab toolbox quick refenerce-快速检索-关键词查找

    MATLAB工具箱速查表-matlab toolbox quick refenerce-快速检索-关键词查找 ...Matlab Main Toolbox——matlab 主工具箱 Control System Toolbox——控制系统工具箱 Communication Toolbox——通讯工具箱 Financ...

    Frequency Domain System Identification Toolbox

    Frequency Domain System Identification Toolbox——For Use with MATLAB

    MATLAB语言工具箱——TOOLBOX实用指南

    MATLAB语言工具箱——TOOLBOX实用指南

    Toolbox DVD 828D.zip

    《SINUMERIK 828D TOOLBOX——西门子PLC编程与设备监控利器》 在工业自动化领域,西门子SINUMERIK系列是知名的数控系统之一,而828D型号更是其中的佼佼者。本篇将深入探讨“SINUMERIK 828D TOOLBOX”这一工具包,它...

    Matlab——SVM向量机Toolbox.zip

    在Matlab——SVM向量机Toolbox工具箱中,你可以找到示例代码和数据集,这些资源可以帮助初学者快速上手。例如,你可以尝试使用线性核和RBF核解决二分类问题,比较它们的性能差异。同时,通过调整`BoxConstraint`(C...

    整数规划的Matlab实现-IntegerPrograming.zip

    # 整数规划的Matlab实现 ## 求解方法 * 分支定界法——可求解完全或混合整数线性规划 ...* OPTI toolbox ——其中部分求解器可以求解混合整数非线性规划MINP * 其他未使用的CPLEX、IPSOLVE、MOSEK、SCIP、SEDUMI

    Time-Frequency Toolbox (TFTB) tutorial——[pudao整理书签版]

    根据给定的文件信息,本文将详细解读《Time-Frequency Toolbox (TFTB) tutorial——[pudao整理书签版]》中介绍的内容。TFTB 是一个用于MATLAB的时频分析工具箱,它是由法国国家科学研究中心(CNRS)和美国莱斯大学的...

    webmaster-toolbox 站长工具

    《全面解析:Webmaster Toolbox——站长工具箱》 在互联网世界中,网站的运营与管理是一项复杂而细致的工作,而“Webmaster Toolbox”(站长工具箱)就是为了解决这一问题而诞生的重要辅助工具。它集多种功能于一体...

    Crestron Toolbox工具箱

    Crestron调试工具——Toolbox版本2.42。下载后,第四步安装此程序

    optimization_toolbox_OptimizationToolbox_

    《MATLAB优化工具箱——实现高效计算优化的利器》 MATLAB优化工具箱(Optimization Toolbox)是MATLAB软件环境中的一套强大工具,专为解决各种优化问题而设计。它包含了一系列函数,能够处理线性、非线性、二次、...

    TOOLBOX_calib.zip_TOOLBOX_calib

    标题中的"TOOLBOX_calib.zip_TOOLBOX_calib"指的是一个名为"TOOLBOX_calib"的压缩包文件,该文件可能包含了与图像标定相关的MATLAB工具箱和测试图像。MATLAB是一款强大的数学计算软件,广泛应用于工程、科研等领域,...

    matlab-mapping toolbox-提取自r2019b

    《MATLAB Mapping Toolbox详解——基于R2019b版本》 MATLAB Mapping Toolbox是MATLAB软件中的一个重要扩展工具箱,专为地球科学、航空航天、地理信息系统(GIS)以及地图制图领域的用户设计。该工具箱包含了丰富的...

    Matlab-Symbolic-Math-Toolbox.rar_Math Toolbox_matlab symbolic ma

    《Matlab符号数学工具箱——探索复杂数学运算的利器》 Matlab的Symbolic Math Toolbox(符号数学工具箱)是进行高级数学计算和符号运算的重要工具。它为用户提供了处理和分析复杂数学问题的能力,无需关注数值计算...

    Antenna_Toolbox.rar_Antenna_Toolbox_antenna_antenna matlab_matla

    《Antenna Toolbox在MATLAB中的应用与探索》 Antenna Toolbox是MATLAB软件的一个扩展工具箱,专为天线设计、分析以及电磁场仿真提供了一系列强大的功能。它结合了数学计算的强大能力与天线工程的专业知识,使得研究...

    西门子840DSL的TOOLBOX

    西门子840DSL的TOOLBOX是一个强大的软件工具集,主要用于840DSL数控系统的编程、诊断和维护工作。这款工具对于理解和操作西门子840DSL控制系统至关重要,因为它提供了全面的功能来支持从最初的系统配置到日常运行的...

Global site tag (gtag.js) - Google Analytics