Gorm: Where Query Between Today and Last Year Tuesday, April 23, 2013

Bizarrely, the GORM where query only accepts the depreciated java.util.Date class.

I was hesitant to write "today - 365" to get last year.

Calendar cal = Calendar.getInstance()
cal.add(Calendar.HOUR, +8)

Calendar cal2 = Calendar.getInstance()
cal2.add(Calendar.YEAR, -1)              

Date today = cal.getTime()
Date lastYear = cal2.getTime()

def query = Stats.where{
    name.id == 1
    period in (lastYear .. today)
}

def results = query.list()
results.each{ println it.period }
Sort the results by the time period with:
results.sort{ it.period }
results.each{ println it.period }

Groovy: Introspect Class Methods

From time to time I need this and can never find it on the web.

def d = new Date()
d.class.methods.each{println it}
d.class.methods.name
Output:

public boolean java.util.Date.equals(java.lang.Object)
public java.lang.String java.util.Date.toString()
public int java.util.Date.hashCode()
public java.lang.Object java.util.Date.clone()
...

[equals, toString, hashCode, clone, compareTo, compareTo, parse, after, before, getDate, getHours, getMinutes, getMonth, getSeconds, getTime, getYear, setTime, setMinutes, setHours, setSeconds, UTC, getDay, setDate, setMonth, setYear, toGMTString, getTimezoneOffset, toLocaleString, wait, wait, wait, getClass, notify, notifyAll]

Also, I found this, which has a more Groovy output:
def dumpOut( clz ) {
  clz.metaClass.methods.each { method ->
    println "${method.returnType.name} ${method.name}( ${method.parameterTypes*.name.join( ', ' )} )"
  }
}

dumpOut String.class 

http://stackoverflow.com/questions

Output:

boolean equals( java.lang.Object )
java.lang.Class getClass( )
int hashCode( )
void notify( )
void notifyAll( )
java.lang.String toString( )
void wait( )
void wait( long )
...

Groovy: Sorting List of Date Strings Monday, April 22, 2013

def list = [
"2013-01-01 0:00:00", "2013-02-01 0:00:00", "2013-03-01 0:00:00", "2013-04-01 0:00:00",
"2009-01-01 0:00:00", "2009-02-01 0:00:00", "2009-03-01 0:00:00", "2009-04-01 0:00:00",
"2008-01-01 0:00:00", "2008-02-01 0:00:00", "2008-03-01 0:00:00", "2008-04-01 0:00:00",
]

Collections.shuffle(list, new Random())

list.each{ println it }

println "-- sorted --"

list.sort()

list.each{ println it }

Output:

2008-03-01 0:00:00
2009-04-01 0:00:00
2009-03-01 0:00:00
2008-02-01 0:00:00
2009-02-01 0:00:00
2013-01-01 0:00:00
2008-04-01 0:00:00
2013-03-01 0:00:00
2013-02-01 0:00:00
2009-01-01 0:00:00
2013-04-01 0:00:00
2008-01-01 0:00:00
-- sorted --
2008-01-01 0:00:00
2008-02-01 0:00:00
2008-03-01 0:00:00
2008-04-01 0:00:00
2009-01-01 0:00:00
2009-02-01 0:00:00
2009-03-01 0:00:00
2009-04-01 0:00:00
2013-01-01 0:00:00
2013-02-01 0:00:00
2013-03-01 0:00:00
2013-04-01 0:00:00

Formatting Number to Currency and Percentage Strings Thursday, April 18, 2013

I found we can use: java.text.DecimalFormat, to take a number like a Integer or a BigDecimal and format it to a string, with the desired formatting:

import java.text.DecimalFormat

def num1 = 654572 //java.lang.Integer
def num2 = 0.7507577625 //java.math.BigDecimal
//println "num1: " + num1.getClass()
//println "num2: " + num2.getClass()

println "Format Currency:"
def list = [0, 1, 6, 23, 245, 8765, 92309, 654572, 6.57, 23.23, 5.876, 5.875, 5.874 ]
list.each{ value ->
    def pattern = "\$##,###.##"
    def moneyform = new DecimalFormat(pattern)
    String output = moneyform.format(value)
    println(value + " " + pattern + " " + output)
}

println "Format Percentage:"
def list1 = [ 0.7507577625, 1.0423815336, 1.1714391045, 0.8603150483 ]
list1.each{ value ->
    def pattern1 = "###.##%"
    def percentform = new DecimalFormat(pattern1)
    String output1 = percentform.format(value)
    println(value + " " + pattern1 + " " + output1)
}
Output:

Format Currency:
0 $##,###.## $0
1 $##,###.## $1
6 $##,###.## $6
23 $##,###.## $23
245 $##,###.## $245
8765 $##,###.## $8,765
92309 $##,###.## $92,309
654572 $##,###.## $654,572
6.57 $##,###.## $6.57
23.23 $##,###.## $23.23
5.876 $##,###.## $5.88
5.875 $##,###.## $5.88
5.874 $##,###.## $5.87

Format Percentage:
0.7507577625 ###.##% 75.08%
1.0423815336 ###.##% 104.24%
1.1714391045 ###.##% 117.14%
0.8603150483 ###.##% 86.03%

Java Tutorial: Decimal Formatting

ZKGrails: Radio Button Example Tuesday, April 16, 2013

The original example can be found here:

ZK: Radio Buttons

ZKGrails Composer:

$('#fruit_rg').onCheck{
    $('#fruit').setValue($('#fruit_rg').selectedItem.label)
    println $('#fruit').value
}

ZKGrails Zul Page:


    
        
        
        
    
    You have selected :
    

Using jFreeChart via a Chart Service Tuesday, April 9, 2013

Using ZKGrails I wanted to use its built-in chart tags. However, since the last time I used ZK (3 years ago) they no longer provide charts in their free version.

FYI, ZKGrails no longer supports having zscript code in the .zul pages, so the process of trying to get a dynamically rendered image embedded into a .zul page was that much more difficult. All the code must be the ZKGrails composer class, so rapid prototyping is out.

The difficulty was compounded by an optional ZKGrails Groovy Builder code supported inside the ZKGrails composers. The builder creates a JQuery like syntax for selecting ZK components from the .zul view. Since it provides a "Groovyer" syntax I wanted to use it, but it did add some mental overhead.

So using jFreeChart I created a Grails service, which just statically returns a jFreeChart. The chart is just a static chart I found in one of the jFreechart demos.

package com.lcr.audit

import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartPanel
import org.jfree.chart.JFreeChart
import org.jfree.chart.plot.PlotOrientation
import org.jfree.chart.plot.XYPlot
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer
import org.jfree.ui.ApplicationFrame
import org.jfree.ui.RefineryUtilities
import org.jfree.data.category.DefaultCategoryDataset


class ChartService {
    static transactional = false

    def getChart() {
        def dataset = createDataset()
        def chart = createChart(dataset)
        return chart
    }
    
    def createDataset(){
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(212, "Classes", "JDK 1.0");
        dataset.addValue(504, "Classes", "JDK 1.1");
        dataset.addValue(1520, "Classes", "SDK 1.2");
        dataset.addValue(1842, "Classes", "SDK 1.3");
        dataset.addValue(2991, "Classes", "SDK 1.4");
        return dataset
    }
    
    def createChart(dataset){
            JFreeChart chart = ChartFactory.createLineChart(
            "Java Standard Class Library", // chart title
            "Release", // domain axis label
            "Class Count", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips
            false // urls
        )
        
        return chart
    }
}

This returns a chart that looks like this:









This image is a jFreechart "chart" object, which provides a method that converts it to a buffered image class. After a great deal of trial and error and searching the web, I found a ZK example that I partially got to work, proving I could render a dynamic image, and the code only needed a buffered image as input.

ZK Demo Dynamic Images


Here is a basic .zul page which will work to render the single dynamic chart from the above chart service:


    
        
            
        
    

The important line is:

The "id" of "img" is what we will use to select this image component and set its content to our chart buffered image.

Now, let's look at the ZKGrails Composer:

package com.lcr.audit

import org.zkoss.zk.grails.composer.*

import org.zkoss.zk.ui.select.annotation.Wire
import org.zkoss.zk.ui.select.annotation.Listen

class DomBillAuditToolComposer extends GrailsComposer {
    def chartService
    def img
    
    def afterCompose = { window ->
        // initialize components here
        def chart = chartService.getChart()
        def bufferImg = chart.createBufferedImage(700, 200)
        img.setContent(bufferImg)
    }
}
This composer is not coded using the ZKGrails Builder JQuery syntax. This was the how I first got it to work. Later, I got help from to get the ZKGrails Builder code to work.

Google Groups: ZKGrails User Group

Lines 10 and 16 are important. "def img" is how we select the ZK Image component from the .zul page. Now, the variable img can be used as it is in line 16 to call the "setContent()" method, so we can pass in our buffered image.

Using the ZKGrails builder code we could do something like this:
$('#img').append{
    def chart = chartService.getChart()
    def bufferImg = chart.createBufferedImage(700, 200)
    def img = $('#chart01') // Or: def img = $('#chart01')[0]
    img.setContent(bufferImg)
}

This is how the ZK image component is selected:
$('#img')

Because we are not appending anything to the "img" ZK Image component, maybe we don't need to select the component like this:
$('#img').append{}

Because notice we are "selecting" the component again in this line.
def img = $('#chart01')
This is similar to what we did in the first composer code above, which uses the older style.

Note: if you have no JQuery background, you may find the JQuery style of having a dollar sign and parentheses $(blah), strange, and very non-Groovy. When I first saw it I had no idea what it was. It is optional, as you can always use the first composer syntax.

Grails Transient Domain Properties Wednesday, April 3, 2013

So far, this is the only official document of a transient property.

Grails Docs Transients

But, I found this interesting nugget:

Question about transient properties

"As of 2.0 if there is only a getter or only a setter method, you don't
need to declare the property name of the method in the transients list.
Only typed fields and get/set pairs that form a property but shouldn't
be persisted need to go in the transients list."

I created domain classes based on this nugget, and it does work.

My domain class just has two methods:

def getPercentMinutes(){ "transient PercentMinutes" }
def getPercentCost(){ "transient PercentCost" }
And does not have a "transients" property.
static transients = ['']
It doesn't need it. Finally, no columns for these properties are created in the DB.

Be careful, do not use a closure as your method call. E.g., don't do this:
def getPercentMinutes = { "transient PercentMinutes" }
def getPercentCost = { "transient PercentCost" }