// scratch.groovy
import java.util.regex.Matcher
import java.util.regex.Pattern
List entries = [
['2004-08-06-thing-thing.html', 'This is a title'],
['2004-08-15-thing.html', 'This is a title'],
['2005-02-12-a-thing-thing.html', 'This is a title'],
['2005-04-29-thing-thing-thing.html', 'This is a title'],
['2005-04-29-thing-thing.html', 'This is a title'],
['2008-01-01-thing.html', 'This is a title'],
['2009-12-31-thing.html', 'This is a title'],
]
for(e in entries) {
new File( (e[0] - ".html") + ".yam" ).withWriter {
it << e[1]
it << '\n\n'
it << "This is some content in file ${e[0]}"
}
}
System.exit(0)
/*
List entries = [
'2004-08-06-thing-thing.html',
'2004-08-15-thing.html',
'2005-02-12-a-thing-thing.html',
'2005-04-29-thing-thing.html',
'2005-04-29-thing-thing.html',
'2008-__-__-thing.html',
'2009-12-31-thing.html',
]
Pattern pat = ~/(?i)([12][0-9][0-9][0-9])-(..)-(..)-.*\.html/
for(e in entries) {
Matcher mat = pat.matcher(e)
if(mat.find()) {
String y = mat[0][1]
String m = mat[0][2]
String d = mat[0][3]
println "${y} ${m} ${d}"
}
}
import com.google.gson.Gson
import com.google.gson.GsonBuilder
class Utilities {
public static String prettyJson(Object o) {
StringBuffer buf = new StringBuffer()
Gson gson = new GsonBuilder().setPrettyPrinting().create()
buf.append(gson.toJson(o))
return buf
} // prettyJson()
} // Utilities
class EntryTree {
Map years = [ : ]
void add(String y, String m, String d, String t, String p) {
Map thisYear = years.get(y)
if(! thisYear) {
years.put(y, [ (m): [(d): [ [t, p] ] ] ])
} else {
Map thisMonth = thisYear.get(m)
if(! thisMonth) {
thisYear.put(m, [(d): [ [t, p] ] ])
} else {
List thisDay = thisMonth.get(d)
if(! thisDay) {
thisMonth.put(d, [ [t, p] ])
} else {
thisDay.add([t, p])
}
}
}
} // add(String, String, String, String, String)
List sortedYears() {
return years.entrySet().sort()
}
List sortedMonths(String y) {
return years.get(y).entrySet().sort()
}
String toString() {
StringBuilder s = new StringBuilder("")
for(y in years.entrySet())
s.append(y)
return s.toString()
}
String print(
boolean prY, String yPref, String ySuff,
boolean prM, String mPref, String mSuff,
boolean prD, String dPref, String dSuff,
boolean prE, def eMarkup
) {
StringBuilder s = new StringBuilder()
for(year in sortedYears()) {
String y = year.key
if(prY) s.append "${yPref}${y}\n"
for(month in year.value) {
if(prM) s.append " ${mPref}${month.key}\n"
for(day in month.value.entrySet().sort()) {
if(prD) s.append " ${dPref}${day.key}\n"
for(e in day.value.sort()) {
if(prE) {
Closure templ = { args -> "${args[0]}" }
Closure instantiate = {
templ.delegate = delegate
templ.resolveStrategy = Closure.DELEGATE_FIRST
return templ.call(e)
}
s.append " ${instantiate.call()}\n"
}
}
if(prD) s.append " ${dSuff}\n"
}
if(prM) s.append " ${mSuff}\n"
}
if(prY) s.append "${ySuff}\n"
}
return s
} // print(...)
} // EntryTree
EntryTree et = new EntryTree()
et.add("2009", "04", "22", "An Second Entry", "2009-04-22-two.html")
et.add("2008", "04", "29", "An Entry and a Half", "2008-04-29-xyz.html")
et.add("2008", "05", "02", "An Entry", "2008-05-02-something.html")
et.add("2008", "04", "22", "An Entry", "2008-04-22-something.html")
et.add("2008", "04", "22", "Another Entry", "2008-04-22-something-else.html")
et.add("2008", "__", "__", "Another Other Entry", "2008-__-__-something-else.html")
et.add("2008", "06", "22", "An Entry", "2008-06-22-something.html")
et.add("2008", "06", "22", "An Entry", "2008-06-22-something-more.html")
et.add("2009", "04", "22", "An Third Entry", "2009-04-22-three.html")
et.add("2009", "04", "22", "An First Entry", "2009-04-22-one.html")
println (et.toString())
println ""
println (et.years.toMapString())
println ""
println(Utilities.prettyJson(et))
// println(Utilities.prettyJson([ sortedYears: et.sortedYears() ]))
println(et.sortedYears())
println(et.years.get("2008").entrySet())
println(et.sortedMonths("2008"))
println ""
print et.print(
true, "", "",
true, "", "",
true, "", "",
true, '${e[0]}'
)
import java.util.regex.*;
Pattern p = Pattern.compile("([0-9])%");
p = Pattern.compile("([0-9])%");
Matcher m = p.matcher("");
m.reset("100%");
String result = m.replaceAll('$1\\\\%');
println result
System.exit(0);
String yes = "100% 10% 10"
String no = "%%%"
//println yes.replaceAll("([0-9])%", "$1\\%")
System.exit(0);
String arg = "123pt"
if(arg.length() > 0 && Character.isDigit(arg.charAt(arg.length() - 1)) )
arg = arg + "px";
println( arg )
Integer intVal = 0
String x = "123"
try {
intVal = Integer.parseInt(x)
intVal = (int) ( ((double)intVal) / 1.2 )
} catch(NumberFormatException e) {
}
println intVal
System.exit(0);
System.out.printf("Started at %tc", System.currentTimeMillis())
println ""
println("${new Date(System.currentTimeMillis())}")
println ""
Map m = [ a : 12, b : 13 ]
for(String key in m.keySet()) {
println key
}
System.exit(0)
String xml = """
"""
XmlParser parser = new XmlParser()
def html = parser.parseText (xml)
//assuming div occurs under body
html.body.div.each { processDiv(it) }
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(html)
def result = writer.toString()
print "$result"
void processDiv(div) {
def atts = div.attributes()
if(atts.id.equals("a")) {
div.value = "New Text Here"
}
// if div is not exactly under the body tag but somewhere down the hierarchy
div.div.each {processDiv(it)}
}
println "================================"
String pageString = '''
'''
String text = "new text!"
String divId = "leftBar"
XmlParser pageParser = new XmlParser()
def parseTree = pageParser.parseText(pageString)
parseTree.div.each {
if(it.attributes().id.equals(divId))
it.value = text
}
def treeWriter = new StringWriter()
new XmlNodePrinter(new PrintWriter(treeWriter)).print(parseTree)
def newTreeString = treeWriter.toString()
print "$newTreeString"
System.exit(0)
////////////////////////////////////////////////////////////
def parseTree = new XmlParser().parseText('''
''')
def input1 = '''
- Chocolate
- Coffee
- Paper
- Pens
- Kathryn's Birthday
'''
println parseTree.body.value
println parseTree.body.value.find { it.@id == 'leftBar' }
//println parseTree.body.find { it.@id == 'leftBar' }.value = "ahhooba"
parseTree = new XmlParser().parseText(input1)
//parseTree.html.body.find { it.@id == 'leftBar' }.value = "ahhooba"
println parseTree
println parseTree.category
println parseTree.find { it.@id == 'leftBar' }
println ""
def stringWriter = new StringWriter()
new XmlNodePrinter(new PrintWriter(stringWriter)).print(parseTree)
def updatedDoc = stringWriter.toString()
println updatedDoc
System.exit(0)
////////////////////////////////////////////////////////////
def input = '''
- Chocolate
- Coffee
- Paper
- Pens
- Kathryn's Birthday
'''
def expectedResult = '''
- Luxury Chocolate
- Luxury Coffee
- Paper
- Pens
- Mum's Birthday
- Monica's Birthday
'''
def root = new XmlParser().parseText(input)
println root.findAll { it.@id == 'topBar' }
println root.find { it.@id == 'topBar' }
println root.category.item[0]
println ""
root.find { it.@id == 'topBar' }.value = "ahhooba"
println root
println ""
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
def result = writer.toString()
println result
// modify groceries: quality items please
def groceries = root.category.findAll{ it.@type == 'groceries' }.item[0]
groceries.each { g ->
g.value = 'Luxury ' + g.text()
}
// modify supplies: we need extra pens
def supplies = root.category.findAll{ it.@type == 'supplies' }.item[0]
supplies.findAll{ it.text() == 'Pens' }.each { s ->
s.@quantity = s.@quantity.toInteger() + 2
s.@when = 'Urgent'
}
// modify presents: August has come and gone
def presentCategory = root.category.find{ it.@type == 'present' }
presentCategory.children().clear()
presentCategory.appendNode('item', "Mum's Birthday")
presentCategory.appendNode('item', [when:'Oct 15'], "Monica's Birthday")
// check the when attributes
def removeNulls(list) { list.grep{it} }
assert removeNulls(root.'**'.item.@when) == ["Urgent", "Oct 15"]
System.exit(0)
////////////////////////////////////////////////////////////
Map params = [ a : 1, b : 2 ]
params.remove('a')
println params
System.exit(0)
////////////////////////////////////////////////////////////
def x = """
${id}
${pagePath}
"""
Map m = [ a: 1, b: 2, c: 3 ]
println m
String javaView = ((m as java.util.LinkedHashMap).toString())
println javaView
println jMap2GMap(javaView)
/ **
* Takes a Java string view of a map ({a=1, b=2, c=3}) and returns the
* equivalent Groovy map (["a":"1", "b":"2", "c":"3"]).
* /
Map jMap2GMap(String javaMapView) {
Map m = [:]
javaMapView[1..-2].split(',').each {
List entry = it.trim().split('=')
m.put(entry[0], entry[1])
}
return m
} // jMap2GMap(String)
System.exit(0)
////////////////////////////////////////////////////////////
URL gateUrl = new URL("http://gate.ac.uk/")
// println gateUrl.text
println """"here is "${gateUrl}" """
System.exit(0)
////////////////////////////////////////////////////////////
File cwd = new File(".")
List fileNames = []
cwd.eachFileRecurse { file ->
if(
file.path.startsWith("./plugins") ||
file.path.startsWith("./doc") ||
file.path.startsWith("./web-app") ||
file.path.startsWith("./bin") ||
file.path.startsWith("./src/java/gate/yam/parse/") ||
file.path.startsWith("./src/templates/scaffolding") ||
file.path.startsWith("./grails-app/taglib/FckEditorTagLib.groovy") ||
file.path.startsWith("./grails-app/services/EmailerService.groovy") ||
file.path.startsWith("./test/unit/org/tmatesoft") ||
file.path.startsWith("./src/java/gate/wiki/antlr") ||
file.path.startsWith("./src/java/gate/yam/convert/JSPWikiMarkupParser.")
)
return
if(file.name.endsWith(".groovy") || file.name.endsWith(".java"))
fileNames.add(file.path)
}
//fileNames.each { println it }
//System.exit(0)
//fileNames = ['grails-app/controllers/PageController.groovy']
//fileNames = ['src/java/gate/yam/translate/AbstractTranslator.java']
for(path in fileNames) {
println path
boolean inLicence = false
String licence = \
'''
*
* This code is from the GATE project (http://gate.ac.uk/) and is free
* software licenced under the GNU General Public License version 3. It is
* distributed without any warranty. For more details see COPYING.txt in the
* top level directory (or at http://gatewiki.sf.net/COPYING.txt).'''
File f = new File(path)
File t = File.createTempFile("scratch-", "", cwd)
t.withWriter { writer ->
String previous = ""
f.eachLine { line ->
if(line.startsWith(' * Copyright (c) 1998')) {
t << "${line}${licence}\n"
inLicence = true
} else if(inLicence) {
if(line.startsWith(' * /')) {
if(previous.contains("Hamish")) // old style author note
t << " * \n${previous}\n"
t << line + "\n"
inLicence = false
}
} else if(line == " *") {
} else {
t << line + "\n"
}
previous = line
}
}
t.renameTo(f)
}
System.exit(0)
////////////////////////////////////////////////////////////
import org.springframework.core.io.FileSystemResource
CowFileSystemResource fsr = new CowFileSystemResource("/a/b/c.html")
println fsr.fsr
println fsr.fsr.file.name
File serializationFile = new File("test.ser")
FileOutputStream fos = new FileOutputStream(serializationFile)
ObjectOutputStream oos = new ObjectOutputStream(fos)
oos.writeObject(fsr)
oos.close()
FileInputStream fis = new FileInputStream("test.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
CowFileSystemResource fsr2 = (CowFileSystemResource) ois.readObject();
ois.close();
println fsr2.fsr
println fsr2.fsr.file.name
System.exit(0)
////////////////////////////////////////////////////////////
class Thing {
String a = "A"
String b = "B"
boolean c = true
Map toMap() {
return this.properties.findAll {
it.key != "metaClass" && it.key != "class"
}
}
}
class OtherThing {
Map doSomething() {
Thing t = new Thing()
return t.toMap()
}
}
OtherThing t = new OtherThing()
println t.doSomething()
assert t.doSomething() == ["b":"B", "a":"A", "c":true]
System.exit(0)
////////////////////////////////////////////////////////////
URI u = new URI("/x/y/z")
println u.resolve("a.html")
println u.resolve("a.html?d=1")
println u.resolve("?d=1")
Map m = [ a : 2 ]
println m
m + [ b : 3, c : 4 ]
println m
m += [ b : 3, c : 4 ]
println m
Map thing() {
[ a : 26 ]
}
println(thing())
System.exit(0)
conf = new ConfigSlurper().parse('''
gate {
cow {
version = props."app.version"
mode = "workstation"
user.home = System.getProperty("user.home")
data = "${user.home}/${dot}cowrc.d/${version}"
dbs = "${data}/dbs"
sandboxes = "${data}/sandboxes"
svnrep = "${data}/svnrep"
help.wiki = "${sandboxes}/help"
main.wiki = "${sandboxes}/main"
page {
thing = "another thing"
thing3 = "yet another"
}
}
}
''')
println( conf.gate.cow.mode == "workstation" )
String path = "cow.mode"
println( evaluate("conf.gate.${path}") == conf.gate.cow.mode )
System.exit(0)
// Flatten a ConfigObject adding a prefix to the keys
Map flattenConf(String prefix, Map conf) {
Map result = [ : ]
for(k in conf.keySet()) {
def val = conf.get(k)
def dot = prefix ? "." : ""
def key = "${prefix}${dot}${k}"
if(val instanceof Map)
result.putAll( flattenConf(key, val) )
else {
result.put( (key), val )
}
}
return result
} // flattenConf(String, Map)
println flattenConf("gate", [ 'a' : [ 'b' : [ 'c' : 'x', 'd' : 'y' ] ] ])
[ 'a' : [ 'b' : [ 'c' : 'x', 'd' : 'y' ] ], e : 'z' ].each {
println "${it}"
}
// print the dependency tree for the build targets
def buildxml = new XmlSlurper().parse("build.xml")
List targets = []
buildxml.target.each { targets << it }
for(t in targets) {
printTarget(t, targets)
}
void printTarget(t, targets) {
printTarget(t, "", targets)
return
print t.@name
print " "
List dependencies = t.@depends.toString().split(",").collect { it.trim() }
print dependencies
println ""
}
void printTarget(t2, String indent, targets) {
if(indent == " ")
return
print indent
print t2.@name
println ""
List dependencies = t2.@depends.toString().split(",").collect { it.trim() }
for(child in dependencies) {
for(x in targets) {
println x.class
if(x && x.@name && x.@name == child)
printTarget(x, "$indent ")
}
}
}
*/