Groovy recipes for every day!
Today is the File Day !
List my imported packages
Today: I get a list of imported package into my old groovy scripts !
| Code Block |
|---|
//Pattern for groovy script
def p = ~/.*\.groovy/
new File( 'd:\\scripts' ).eachFileMatch(p) {
f ->
// imports list
def imports = []
f.eachLine {
// condition to detect an import instruction
ln -> if ( ln =~ '^import .*' ) {
imports << "${ln - 'import '}"
}
}
// print thmen
if ( ! imports.empty ) {
println f
imports.each{ println " $it" }
}
}
|
Output
| No Format |
|---|
D:\groovy getImports.groovy d:\scripts\testCom.groovy org.codehaus.groovy.scriptom.ActiveXProxy d:\scripts\testDurableSubscriber.groovy javax.jms.*; org.apache.activemq.ActiveMQConnectionFactory; org.apache.activemq.command.ActiveMQTopic; d:\scripts\testJmsBroker.groovy javax.jms.*; org.apache.activemq.ActiveMQConnectionFactory; org.apache.activemq.command.ActiveMQTopic; |
Clean old files
today: Oh jeez! I get on my SysAdmin's nerves, file System /data is full! .. I have to clean all these useless daily reports !
| Code Block |
|---|
def yesterday = ( new Date() ).time - 1000*60*60*24
def cleanThem = { prefix ->
new File('/data/waporwaresystem/reports').eachFileMatch( ~".*${prefix}.*xml" ) { f ->
if ( f.lastModified() <= yesterday ) {
f.delete()
}
}
}
['sales-carambar_', 'stock-scoubidou_', 'stock_freztagad_', 'coffee.vs.tea_stats_'].each( cleanThem )
|
Saved! My SysAdmin loves me, it's sure ![]()
Recursively deleting files and directories.
Today is a recursive day ! We have a bunch of files and directories to delete, let's go!
the Ant way
Don't forget this old java swiss knife...
| Code Block | ||
|---|---|---|
| ||
new AntBuilder().delete(dir: "D:/tmp/test") |
the Groovy Way
| Code Block | ||
|---|---|---|
| ||
// Create a ref for closure
def delClos
// Define closure
delClos = { println "Dir ${it.canonicalPath}";
it.eachDir( delClos );
it.eachFile {
println "File ${it.canonicalPath}";
it.delete()
}
}
// Apply closure
delClos( new File("D:/tmp/test") )
|