Commenting XML

Another mailing list question.

Not proud of this answer, but couldn't come up with anything better…

Here's the 'commenting out' part:

import groovy.xml.*
import groovy.xml.dom.DOMCategory

final CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'>
        <country>Australia</country>
        <record type='speed'>Production Pickup Truck with speed of 271kph</record>
      </car>
    </records>
  '''

def reader = new StringReader(CAR_RECORDS)
def doc = DOMBuilder.parse(reader)
def records = doc.documentElement

use (DOMCategory) {

  def maloo = records.'car'[0]
  assert maloo.'@name' == 'HSV Maloo'

  maloo.replaceNode {
    'comment' XmlUtil.serialize(maloo)['<?xml version="1.0" encoding="UTF-8"?>'.size()..-1]
  }

  println XmlUtil.serialize(records).replaceAll('<comment>', '<!--').replaceAll('</comment>', '-->')
}

This gives:

<?xml version="1.0" encoding="UTF-8"?><records>
      <!--&lt;car make="Holden" name="HSV Maloo" year="2006"&gt;&#13;
        &lt;country&gt;Australia&lt;/country&gt;&#13;
        &lt;record type="speed"&gt;Production Pickup Truck with speed of 271kph&lt;/record&gt;&#13;
      &lt;/car&gt;&#13;
-->
    </records>

This is SO yukky! If I really had to do this, I'd probably drop back to plain Java-style DOM manipulation (and even then it would STILL be very yukky).

(I gave up on the uncomment part…)

Tags: Groovy, Programming

Updating Namespaced Attributes With Groovy's XmlSlurper

A recent question on the Groovy mailing list asked

I need to update the "xlink:title" attribute in:

<gmi:instrument xlink:title="$INSTRUMENT"/>

Here's what I came up with:

import groovy.xml.*

def xmlSource = '''
<bob:root xmlns:bob="stuff"
  xmlns:gmi="http://www.isotc211.org/2005/gmi"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <gmi:instrument xlink:title="$INSTRUMENT"/>
</bob:root>
'''

def bobRoot = new XmlSlurper(false,true).
                parseText(xmlSource).
                declareNamespace(bob: 'stuff',
                                 ns2: 'http://www.example.org/NS2',
                                 gmi: "http://www.isotc211.org/2005/gmi")

def instrument = bobRoot.'gmi:instrument'

// NB: does NOT work: instrument[0].attributes().remove('xlink:title')
// NB: works, but YUK: instrument[0].attributes().remove('{http://www.w3.org/1999/xlink}title')

// NB: leads to duplicate attribute: instrument.'@xlink:title' = 'XXX'
instrument.'@{http://www.w3.org/1999/xlink}title' = 'XXX'

println new StreamingMarkupBuilder().bind {
  mkp.yield instrument
}.toString()

'OK'

The key here is finding out that you need to use the full namespaced name, not the shorter name.

IMHO, this is a bug and I have created GROOVY-6356 using this code.

I'm also wondering why I needed to use 'instrument[0]' to get at the attributes.

All this is more obscure and convoluted than it probably needs to be so keep watching the Jira.

Tags: Groovy, Programming

AWSomeDay

Well!

Just went along to a free day on "Introduction to Amazon Web Services." Thank you, Amazon.

I even got the certificate to prove it…

…along with the other 300+ people in the room, of course.

Many, many attendees are already using AWS, it appears.

The degree of sophistication now is startling. LOTS more 'stuff' available than first meets the/my eye.

Loadbalancers, DNS, caches, NAT boxes, clusters, networking ACLs, SSO, etc. All "straight out of the box." All quickly provisioned and at ridiculously low prices, to boot.

The presenter continually kept hammering home: "no need for server engineers, network engineers, database engineers, etc., etc."

Actually, it doesn't matter what he or anyone says…just tell the bean counters: "this is opex, not capex" and they will go for it like a dog after a bone.

Tags: Cloud, Tools

Java And Windows

I can't believe that Java is now 19 years old and people are still asking about how to deal with path-like structures and spaces in Java.

It is really very simple: avoid using spaces :-)

You can do "dir /x" in a command prompt window, find out what the short pathname for a directory is and just use that version wherever needed. Viz.:

You will usually (UNLESS you have been tweaking one of NTFS's more esoteric parameters, in which case…stop tweaking) find that "Program Files" is 'PROGRA~1′. This form can be used anywhere with no problems.

For example:

set JAVA_HOME=R:\PROGRA~1\Java\jdk1.7.0_25
PATH %JAVA_HOME%\BIN;%PATH%

Etc.

Simple. There's no need to avoid the nice human-readable paths usually used in Windows.

Seriously, it isn't a problem, guys!

It hasn't been a problem since at least NT4.0 (which is as far back as I go, anyway).

For reference: DIR.

BOB
Update: This of course applies to any JVM-based language/system, including Groovy.

Tags: Groovy, Java, Programming

Data-Driven Documents In The Browser

Just came across D3.js:

a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3's emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.

Lots of nice, interactive graphs and visualisations.

then there is Dimple:

The aim of dimple is to open up the power and flexibility of d3 to analysts. It aims to give a gentle learning curve and minimal code to achieve something productive. It also exposes the d3 objects so you can pick them up and run to create some really cool stuff.

Both sites have more beautiful and impressive examples than you can shake a stick at!

There's just so much good stuff happening in the browser at the moment…

Tags: Javascript, Programming

Geb Runner For LoadUI

Following on from the previous post, here is the Geb Runner for LoadUI.

Here's a pretty picture (copied for the LoadUI website):

Tags: Geb, Groovy, Programming, Tools

Recipes For Testing Grails

An excellent collection of practical tips and tricks.

Many thanks to Tomás Lin for his work.

This is sure to become a useful reference.

Tags: Grails, Groovy, Programming, Tools

Disaster!

Well!

I was scheduled to present Groovy and the other Gr8 technologies to the Hong Kong Java User Group on Thursday 9 May, 2013.

Unfortunately, I just (Tuesday 7 May, 2013) spent a rather uncomfortable night in Tai Po's Alice Ho Miu Ling Nethersole Hospital and am now under strict {Doctor's, Wife's} orders not to exert myself for the next few days.

This means that I have had to cancel the presentation.

Apologies to any HKJUG member that was planning to come along.

Since there will be no chance to reschedule (at least for this year), I am putting the slide pack up anyway.

So: please enjoy The Future Is Gr8.

Once again, I apologise to the HKJUG for any inconvenience this causes.

Tags: Grails, Groovy, Programming

Microsoft Simplifies IE Testing

Subtitle: Free Windows/IE VMs for testing purposes…
Sub-subtitle: …and other useful things to help IE and cross-browser site testing.

Part of the Modern.ie site.

Worth remembering.

Tags: Programming, Tools

Prepending A Node With Groovy's XmlParser

A recent question on the Groovy mailing list: how to update an XML document by prepending an element before another?

Not as completely trivial as it might sound.

Groovy's XMLSlurper only allows for appending a node to a given node's list of children and so one needs the services of XMLParser.

A teensy bit of fiddling is required, thusly:

def xml = """<x name="fred">
                <y name="bill">
                    <z>
                        <a index="0" size="10"/>
                    </z>
                </y>
                <y name="harry">
                    <z>
                        <a index="0" size="200"/>
                        <a index="1" size="500"/>
                    </z>
                </y>
             </x>"""

def x = new XmlParser().parseText(xml)

x.y.each { y ->
    int numA = 0
    int totalASize = 0
    y.z.a.each { a ->
        numA ++
        totalASize += a.@size.toInteger()
    }
    // add a new node as the 0th child, ie: before <z>
    y.children().add(0, new Node(null, 'summary', [numA:numA,totalASize:totalASize]))
} 

new XmlNodePrinter().print(x)

And the beautiful resultant XML is:

<x name="fred">
  <y name="bill">
    <summary numA="1" totalASize="10"/>
    <z>
      <a index="0" size="10"/>
    </z>
  </y>
  <y name="harry">
    <summary numA="2" totalASize="700"/>
    <z>
      <a index="0" size="200"/>
      <a index="1" size="500"/>
    </z>
  </y>
</x>

Not sure if it's generally a good idea to depend on the specific ordering of elements in a document but it's common (Apple's [nasty] XML Property List format is one example that pops to mind) and-as I've shown above-can be done with XMLParser.

Tags: Groovy, Programming