Skip to content

Instantly share code, notes, and snippets.

@saltnlight5
Created September 20, 2012 14:22
Show Gist options
  • Save saltnlight5/3756240 to your computer and use it in GitHub Desktop.
Save saltnlight5/3756240 to your computer and use it in GitHub Desktop.
Groovy Script Examples
// groovy -cp $HOME/.m2/repository/com/h2database/h2/1.3.166/h2-1.3.166.jar groovySql
// http://groovy.codehaus.org/Tutorial+6+-+Groovy+SQL
// Grab will not load the driver! but at least we can trigger it to download it and then use groovy -cp option to run this script.
// @Grab('com.h2database:h2:1.3.166')
import groovy.sql.Sql
sql = Sql.newInstance(
'jdbc:h2:~/test',
'sa',
'',
'org.h2.Driver')
sql.eachRow('select * from USER') {
println "${it.id}, ${it.firstName}"
}
@Grab(group='com.fasterxml.jackson.core', module='jackson-databind', version='2.0.6')
import com.fasterxml.jackson.databind.*
class User {
String name
}
user = new User()
user.name = "Zemian"
mapper = new ObjectMapper()
// TODO: why when I enable this line, the println below will not work?
mapper.writeValue(System.out, user)
println()
user2 = mapper.readValue('{"name":"Zemian"}', User.class)
println("user2 " + user2)
// groovy -cp $HOME/.m2/repository/com/h2database/h2/1.3.166/h2-1.3.166.jar jdbdc
// Grab will not load the driver! but at least we can trigger it to download it and then use groovy -cp option to run this script.
//@Grab('com.h2database:h2:1.3.166')
jdbc_url = "jdbc:h2:~/test"
username = "sa"
password = ""
driver = "org.h2.Driver"
Class.forName(driver)
conn = java.sql.DriverManager.getConnection(jdbc_url, username, password)
print conn
conn.close()
// Print an text entry element inside a jar file. Default o the manifest file.
// @author: Zemian Deng 20120709
file = new File(args[0])
name = args.length > 1 ? args[1] : "META-INF/MANIFEST.MF"
jarfile = new java.util.jar.JarFile(file)
entry = jarfile.getEntry(name)
istream = jarfile.getInputStream(entry)
istream.eachLine{ println(it) }
istream.close()
//import groovy.json.*
//import java.security.*
println(new groovy.json.JsonBuilder(java.security.Security.providers).toPrettyString())
/** Walk a dir that excludes all matching conditions, and then let fileHandler to process the files. */
def walk(File file, List excludeDirs, List excludeFileExts, Closure fileHandler) {
if (file.isDirectory()) {
normalizedPath = file.path.replaceAll("\\\\", "/")
if (!excludeDirs.find{ dir -> normalizedPath =~ dir })
file.eachFile{ subFile -> walk(subFile, excludeDirs, excludeFileExts, fileHandler) }
} else if (file.isFile()) {
if (!excludeFileExts.find{ ext -> file.name.endsWith(ext) })
fileHandler(file)
}
}
// Main script
// - Go into a directory and find all files that has 'Copyright (c)' text in header.
dir = args[0]
excludeDirs = ['\\./hg', '^\\./target']
excludeFileExts = ['.orig']
walk(new File(dir), excludeDirs, excludeFileExts) { file ->
file.withReader() { reader ->
while((line = reader.readLine()) != null) {
matcher = (line =~ /Copyright \(c\)/)
if (matcher) {
println([matcher, file])
break
}
}
}
}
// Script to covert timezone hours
// Usage: tz.groovy 10:00 PST EST
time = args.length > 0 ? args[0] : "10:00"
fromTz = args.length > 1 ? args[1] : "IST" // India Standard Time
toTz = args.length > 2 ? args[2] : "EST" // US Estern Standard Time
df = new java.text.SimpleDateFormat("HH:mm zzz")
d1 = df.parse("$time $fromTz")
df.setTimeZone(TimeZone.getTimeZone(toTz))
println(df.format(d1))
// http://mrhaki.blogspot.com/2009/10/groovy-goodness-groovlets-as.html
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*
@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.14')
def startJetty() {
def jetty = new Server(9090)
def context = new Context(jetty, '/', Context.SESSIONS)
context.setWelcomeFiles(["webserverIndex.groovy"] as String[])
context.resourceBase = '.'
context.addServlet(GroovyServlet, '*.groovy')
jetty.start()
}
println "Starting Jetty on port 9090, press Ctrl+C to stop."
startJetty()
// http://mrhaki.blogspot.com/2009/10/groovy-goodness-groovlets-as.html
def method = request.method
if (!session) {
session = request.getSession(true)
}
if (!session.groovlet) {
session.groovlet = 'Groovlets rock!'
}
html.html {
head {
title 'Groovlet info'
}
body {
h1 'General info'
ul {
li "Method: ${method}"
li "RequestURI: ${request.requestURI}"
li "session.groovlet: ${session.groovlet}"
li "application.version: ${context.version}"
}
h1 'Headers'
ul {
headers.each {
li "${it.key} = ${it.value}"
}
}
}
}
@toraj58
Copy link

toraj58 commented Jun 5, 2018

cooooool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment