//see: http://groovyconsole.appspot.com/edit/1032002
String generateToken(Integer size = 16){
String availableChars = 'ABCDEFGHIJLMNOPQRSTUVXZYabcdefghijlmnopqrstuvxzy0123456789!@#$%*_'
Random generator = new Random()
String token = ""
size.times {
token += availableChars[generator.nextInt(availableChars.length() - 1)]
}
return token
}
generateToken()
generateToken(8)
Wednesday, July 24, 2013
Random String generator
Thursday, July 4, 2013
printf with Strings
//all formatting options: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
//test padding on both sides of "HI"//
(-8..8).each{ i ->
if (i == 0) i = '' // avoid illegal printf syntax
String f = "**%${i}s**"
print ((f + ' --> ').padRight(15)) // just for debugging
printf(f+'\n', "HI")
}
//Tic Tac Toe//
List field = [["","x","o"],["","x",""],["o","",""]]
field.eachWithIndex { line,index ->
if(index > 0) {
println "---+" * 2 + "---"
}
printf(" %-2s| %-2s| %-2s\n", line)
}
Monday, June 17, 2013
Gradle templates
// Generate a new Groovy Project Qwickly (tm) //
// source: https://github.com/townsfolk/gradle-templates
// in build.gradle file (in the project's root folder):
apply from: 'http://www.tellurianring.com/projects/gradle-plugins/gradle-templates/apply.groovy'
dependencies {
groovy localGroovy()
}
//then get a list of tasks:
>> gradle tasks
...
Template tasks
--------------
createGroovyClass - Creates a new Groovy class in the current project. **************
createGroovyProject - Creates a new Gradle Groovy project in a new directory named after your project.
createJavaClass - Creates a new Java class in the current project.
createJavaProject - Creates a new Gradle Java project in a new directory named after your project.
exportGroovyTemplates - Exports the default groovy template files into the current directory.
exportJavaTemplates - Exports the default java template files into the current directory.
initGroovyProject - Initializes a new Gradle Groovy project in the current directory. **************
initJavaProject - Initializes a new Gradle Java project in the current directory.
...
>> gradle initGroovyProject
>> gradle createGroovyClass
/**********************************************************/
//Here's a pretty useful project build.gradle:
apply plugin: 'groovy'
apply from: 'http://www.tellurianring.com/projects/gradle-plugins/gradle-templates/apply.groovy'
apply from: 'http://evgenyg.artifactoryonline.com/evgenyg/libs-releases-local/CodeNarc.gradle'
group = 'myapp1'
mainClassName = 'org.MyCompany.Main'
dependencies {
groovy localGroovy()
}
jar {
manifest {
attributes("Main-Class": mainClassName)
}
}
// uberjar adds in groovy jars to make this easy: "java -jar MyApp.jar"
task uberjar(type: Jar, dependsOn:[':compileJava', ':compileGroovy']) {
from files(sourceSets.main.output.classesDir)
from configurations.runtime.asFileTree.files.collect { zipTree(it) }
manifest {
attributes 'Main-Class': mainClassName
}
}
Script template
// this is just intended to give a little more OOP structure to a script.
// put most code inside of run(), plus class variables and methods.
class Script {
private String hello = "Hello"
public Script run(Map options = [:]) {
println "$hello ${options.name ?: 'World'}${shout(23)}"
return this // for method chaining
}
private String shout(int times = 1) {
return ('!' * times)
}
}
new Script()
.run()
.run([name:'Crazy4Groovy'])
println 'DONE'
Friday, June 14, 2013
Simple Performance Benchmarking
int delayMillis = 100 Long startMillis = Calendar.instance.time.time Thread.sleep(delayMillis) Long passedMillis = Calendar.instance.time.time - startMillis println passedMillis assert passedMillis >= delayMillis
Wednesday, June 12, 2013
XML StreamingMarkupBuilder
import groovy.xml.StreamingMarkupBuilder
Map props = [addressid:'1', line1:'line-1_VALUE', line2:'line-2_VALUE']
def builder = new StreamingMarkupBuilder()
def address = {
"address"(id: props.addressid) {
"line-1"(props.line1)
"line-2"(props.line2)
"city"("city_VALUE") // typing wimped out...
"state"("State_VALUE")
"postal-code"("postal_VALUE")
}
}
println builder.bind(address).toString() // something XML-compatible <address id="1">
...</address>
Thursday, June 6, 2013
Scrape image src's from a web page
import java.net.URLEncoder
String url = "http://msnbc.com"
String serviceUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22${URLEncoder.encode(url)}%22%20and%20xpath%3D%22%2F%2Fimg%22"
//println serviceUrl
String resultXML = serviceUrl.toURL().text // YQL will return the HTML page as XML!
//println resultXML
def root = new XmlSlurper().parseText(resultXML)
List imgSrcs = root.results.img.@src as List
imgSrcs = imgSrcs*.toString().unique()
//println imgSrcs.join('\n')
Subscribe to:
Posts (Atom)