Groovy Script to rename all TXT files in a directory



#!/usr/bin/env groovy
// Script to rename files that end in .txt replacing the XX to YY in the name

dirName = "/tmp"
new File(dirName).eachFile() { file ->
if ( file.getName() =~ /.txt/ ) {
def newName = (file.getName()).replaceFirst("XX", "YY")
File f = new File(dirName + "/" + newName)
file.renameTo(f)
println file.getName() + " -> " + f.getName()
} else {
print "Skipping file " << file.getName() << "\n"
}
}

Advertisements

Sparklines

From: http://www.testearly.com/2008/05/22/groovy-sparklines/ Original Article



package com.stelligent.gsparkyimport org.jfree.chart.JFreeChart
import org.jfree.chart.axis.NumberAxis
import org.jfree.chart.plot.XYPlot
import org.jfree.chart.renderer.xy.StandardXYItemRenderer
import org.jfree.data.general.Dataset
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYSeriesCollection
import org.jfree.chart.ChartUtilities

class GSparky {

def DEFAULT_HEIGHT = 30
def DEFAULT_WIDTH = 150

boolean build( def data, def imgPath, def height = DEFAULT_HEIGHT, def width = DEFAULT_WIDTH ) {

def chart = buildChartFromData(data)
return buildImageFromChart( chart: chart, height: height, width: width, path: imgPath)
}

private JFreeChart buildChartFromData( data ) {

def dataset = generateDataset(data)

def plot = new XYPlot()
plot.dataset = dataset

plot.domainAxis = minimalAxis()
plot.rangeAxis = minimalAxis()

plot.domainGridlinesVisible = false
plot.domainCrosshairVisible = false
plot.rangeGridlinesVisible = false
plot.rangeCrosshairVisible = false
plot.outlinePaint = null
plot.renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES)
plot.insets = new RectangleInsets(-1, -1, 0, 0)

def chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, false)
chart.borderVisible = false

return chart
}

private boolean buildImageFromChart( args ) {

ChartUtilities.saveChartAsPNG( new File(args.path), args.chart, args.width, args.height )

return true
}

private Object minimalAxis() {

def a = new NumberAxis()
a.tickLabelsVisible = false
a.tickMarksVisible = false
a.axisLineVisible = false
a.negativeArrowVisible = false
a.positiveArrowVisible = false
a.visible = false;

return a
}

private Dataset generateDataset(def data) {

def series = new XYSeries("Sparkline")

def i = 0
data.each { y -> series.add(i++, y) }

def dataset = new XYSeriesCollection()
dataset.addSeries(series)

return dataset

}
}

Testing program:


package com.stelligent.gsparky

class GSparklineTest extends GroovyTestCase {

public void testBuildSparklineImage() {

def gs = new GSparky()

def data = [20]

def r = new Random( new Date().getTime() )

(0..99).each { x ->
def y = data.get(x) + (x/2 - r.nextInt(x + 1))
data << y
}

assert gs.build( data, "out/GSparklineTest_test1.png")

}

}

Requires: http://www.jfree.org/jfreechart/ and

Executing External Processes From Groovy – Improved

I’ve started using an exec method as shown below to run sub processes from groovy. If you run the standard exec like:



def torun = "ls -l "
proc = torun.execute()
proc.waitFor()

This will hang on UNIX systems if these programs generate more STDOUT data than the buffer can handle. Better to handle this yourself with the following:



#!/usr/bin/env groovy

void execute(def command ) {

println "Running command : " + command
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", command)
pb.redirectErrorStream(true)
def process = pb.start()
def output = process.inputStream
output.each() { // Throw away stdout in this example, could return it at the end.
}
process.waitFor()
println "Done executing command , return value : " + process.exitValue()
process.destroy()
process = null
pb = null
System.gc()

}

execute("ls -l /usr/bin ")

NOTE From: http://jira.codehaus.org/browse/GROOVY-2620

A Better solution is :



StringWriter stringWriterOutput = new StringWriter()
StringWriter stringWriterError = new StringWriter()
Process proc = command.execute()
stringWriterOutput << proc.in
stringWriterError << proc.err
proc.waitFor()

Multithreaded simple URL Crawler

Here is a quick program to create X threads that crawl a given URL given a set of results for a database.


#!/usr/bin/env groovy
import groovy.sql.Sql
//
// MultiThreaded query script.
// Runs a query and then submits all the jobs as threads using the Executor.newFixedThreadPool
//
// 3/2008 by George kowalski
//

// How may Threads to allow to run at one time.
def MAX_THREADS = 10

println "Processing started .. Quering Database for RGDIds ... "

def sql = Sql.newInstance("jdbc:oracle:thin:@site.edu:1521:SCHEMA", "USERID", "passwd", "oracle.jdbc.driver.OracleDriver");
def service = java.util.concurrent.Executors.newFixedThreadPool(MAX_THREADS)

def rgdIDList = []

sql.eachRow("select * from genes, rgd_ids where genes.rgd_id = rgd_ids.rgd_id and rgd_ids.object_status = 'ACTIVE' and rgd_ids.species_type_key = 3", { rgdIDList << it.rgd_id })

println "Done with Query we will be processing ${rgdIDList.size} ids "

// Class that is run.
class toRun implements Runnable {
String id
toRun(String newid) {
this.id = newid
}
public void run() {
println "Calling URL with id: ${id}"
def contents = new URL("http://rgddev.mcw.edu/tools/genes/genes_view.cgi?id=${id}").getText()
println "Return from: ${id}"
}
}

for (id in rgdIDList) {
println "Submitting Thread for id: ${id}"
service.execute( new toRun(id.toString()) )
// This is just to slow down display on console, not needed.
Thread.sleep(500)
}

Running Oracle SQL / Call URL

The following program was whipped together to pre-cache pages on our server by hitting them with an HTTP request based on a query.

Running a SQL query and calling that URL like Curl to precache results


#!/usr/bin/env groovy
//
// Groovy Script to call each gene page in turn
// Requirements : Drop the Oracle jdbc14.jar driver in your $HOME/.groovy/lib directory then run this script
//
import groovy.sql.Sql

println "Started"
sql = Sql.newInstance("jdbc:oracle:thin:@server.com:1521:SID", "USERID", "password", "oracle.jdbc.driver.OracleDriver");

sql.eachRow("select * from genes, rgd_ids where genes.rgd_id = rgd_ids.rgd_id and rgd_ids.object_status = 'ACTIVE' and rgd_ids.species_type_key = 3", {
println "Calling: http://rgd.mcw.edu/tools/genes/genes_view.cgi?id=${it.rgd_id}"
// creates a new URL obect and downloads that HTML into the contents variable
def contents = new URL("http://rgd.mcw.edu/tools/genes/genes_view.cgi?id=${it.rgd_id}").getText()
// Uncomment next line to print contents of page
// println contents
}
)
println "Done"