Quantcast
Channel: techscouting through the java news » Sönke Sothmann
Viewing all 72 articles
Browse latest View live

Mapping ISO2 and ISO3 Country Codes with Java

$
0
0

There are two commonly used code systems for countries: ISO 3166-1 alpha-2 and ISO 3166-1 alpha-3, aka ISO2 and ISO3 country codes.

In ISO 3166-1 alpha-2, each country is represented by 2 letters, and 3 letters in ISO 3166-1 alpha-3.
ISO2 and ISO3 country codes can be converted to each other, but the Java class library has no build in methods to do the conversion.

To convert ISO3 to ISO2 country codes, initialize a mapping table (call this method once):

private Map<String, Locale> localeMap;

private void initCountryCodeMapping() {
	String[] countries = Locale.getISOCountries();
	localeMap = new HashMap<String, Locale>(countries.length);
	for (String country : countries) {
		Locale locale = new Locale("", country);
		localeMap.put(locale.getISO3Country().toUpperCase(), locale);
	}
}

Now you can use the following method to do the conversion from ISO3 to ISO2:

private String iso3CountryCodeToIso2CountryCode(String iso3CountryCode) {
	return localeMap.get(iso3CountryCode).getCountry();
}

To convert ISO2 to ISO3 country codes, use the following method:

private String iso2CountryCodeToIso3CountryCode(String iso2CountryCode){
	Locale locale = new Locale("", iso2CountryCode);
	return locale.getISO3Country();
}

Einsortiert unter:Java and Quality Tagged: conversion, country codes, ISO 3166-1, iso2, iso3, mapping

Print pages and page fragments using an IFrame and jQuery

$
0
0

In my current Grails project I am using jQueryUI to display information in a dialog window. When opening the dialog window, the content of the dialog is loaded via Ajax.
One requirement we had to implement was a print button in some of those dialogs.

When pressing the print button, only the content of the dialog should be printed.

Simply triggering the browser’s print dialog when pressing the button didn’t work, because the whole page gets printed and the content of the dialog is not visible at all.

The solution I found is based on an IFrame and a JavaScript-Function:
Add a print IFrame to every page (you should add it to your central layout file). I recommend adding it to the bottom of the page.
Size it to 1*1 so that it is not visible.

<iframe width="1" height="1" id="printFrame" />

If you are using Grails, add the IFrame to your main.gsp layout file and place it before the closing body tag.

Include the following JavaScript function in pages where you need printing functionality:

function printUrl(url) {
	$('#printFrame').attr('src', url);
	$('#printFrame').load(function() {
		var frame = document.getElementById('printFrame');
		if (!frame) {
			alert("Error: Can't find printing frame.");
			return;
		}
		frame = frame.contentWindow;
		frame.focus();
		frame.print();
	});
}

This function is called with a url that is used to retrieve the page or page fragment to be printed.
The page gets loaded into the printing IFrame and the browser’s printing functionality is triggered.
If you are using Grails, add the code shown above to your application.js file.

Add a print-button to your page:

<input type="button" value="print" onClick="printUrl('URL_OF_PRINT_SOURCE')"/>

Replace URL_OF_PRINT_SOURCE with the url where the page or page fragment to be printed is located.

If you are using Grails, you can easily link to a controller action with the createLink method (replace CONTROLLERNAME and ACTIONNAME):

<input type="button" value="print" onClick="printUrl('${createLink(controller: 'CONTROLLERNAME', action: 'ACTIONNAME')}')"/>

In my case, I had to print the dialog contents which is loaded from a controller-action, so I could reuse the existing controller action for printing.


Einsortiert unter:Groovy and Grails, Java Web Frameworks Tagged: grails, IFrame, javascript, jquery, print

A Groovy way to retry method calls in case of exceptions

$
0
0

In some scenarios, method calls can fail – but would succeed when retrying the call after some seconds have passed.

That is often the case with remote method calls, where the remote application could be temporarily unavaillable.

I needed a simple way to define something like

“call method foo(). In case the method throws an Exception, retry to call it up to 10 times with a delay of 3 seconds”.

I implemented a simple Groovy util class which enabled me to write code as follows:

RetryUtil.retry(10, 3000){
	foo()
}

Here is the sourcecode of the RetryUtil Groovy class:

import org.apache.commons.logging.LogFactory
import org.apache.commons.logging.Log

class RetryUtil {

	private static Log log = LogFactory.getLog(RetryUtil);

	static retry(int times, long sleeptime, Closure c){
		Throwable catchedThrowable = null
		for(int i=0; i<times; i++){
			try {
				return c.call()
			} catch(Throwable t){
				catchedThrowable = t
				log.warn("failed to call closure. ${i+1} of $times runs.")
				Thread.sleep(sleeptime)
			}
		}
		log.error("finally failed to call closure after $times tries.")
		throw catchedThrowable
	}
}

Einsortiert unter:Groovy and Grails Tagged: Exception handling, Groovy

Displaying Hibernate statistics in a Grails app

$
0
0

Hibernate offers a statistics object (org.hibernate.stat.Statistics) that can be used to monitor the behavior of Hibernate at runtime.
Statistics include connection count, max query execution time, cache hits/misses and many more.

To access the statistics, inject the sessionFactory into a controller and call the getStatistics() method on the sessionFactory:

class SystemController {
	SessionFactory sessionFactory

	def hibernateStatistics = {
		org.hibernate.stat.Statistics statistics = sessionFactory.statistics

		// TODO render the statistics
	}
}

To render the statistics I used Grails’ markup builder in the render() method to output HTML code:

render {
html {
	body {
		p {
			String[] statLines =
				(statistics.toString()-'Statistics').replaceAll('[\\[\\]]', '').split(',')
			statLines.each { stat ->
				span(stat)
				br()
			}
		}
	}
}
}

This should output something like this:
start time=1301467975890
sessions opened=168
sessions closed=167
transactions=325
successful transactions=156
optimistic lock failures=0
flushes=70
connections obtained=169
statements prepared=8629
statements closed=8629
second level cache puts=8074
second level cache hits=764
second level cache misses=0
[...]
queries executed to database=8597
query cache puts=386
query cache hits=2626
query cache misses=386
max query time=297

You should definitely secure this action (e.g. access should be granted to admins only).

The number of cache hits and misses (query cache hits, query cache misses, second level cache hits, second level cache misses) is what I found really helpful to check if my caches are set up correctly.

If you realize too many cache misses, check your caching configuration (see Caching Strategy in the Grails User Guide).


Einsortiert unter:Groovy and Grails Tagged: caching, grails, Groovy, Hibernate statistics

Grails 1.4 canceled, next release version will be 2.0

$
0
0

Grails 1.4 should actually come after Grails 1.3.
SpringSource recently decided to cancel 1.4 and name the next release 2.0.
A lot of improvements and new features justify the new major version number.

The changes of the upcoming 2.0 release include:

  • New console UI and interactive mode
  • Enhanced error reporting and stack trace printing
  • Improved development time reloading with a JVM agent
  • Performance enhancements
  • AST transformation API for plugin devs
  • HTML5 scaffolding
  • Static resource handling
  • A formalized GORM API
  • Abstract inheritance support
  • Multiple data sources support with 2 phase commit
  • Database migrations and reverse engineering
  • Upgrades to libraries from Groovy 1.8, Spring 3.1, Hibernate 3.6 and Servlet 3.0
  • Completely new Testing API with Spock support
  • Unit test scaffolding and enhanced unit test output in the console

Grails 2.0 is scheduled for september 2011.

See the Grails mailing list for more details.


Einsortiert unter:Groovy and Grails Tagged: grails

Dynamic list injection in Spring

$
0
0

Imagine you have a Spring XML configuration which defines a bean with a list property.
The bean could look like

public class MyBean {
	private List listProp;

	public void setListProp(List values) {
		this.listProp = values;
	}
}

Here is the spring config that defines the bean with a static list of values for the listProp property.

<bean id="myBean" class="de.mypackage.MyBean">
	<property name="listProp">
		<list>
			<value>a</value>
			<value>b</value>
			<value>c</value>
		</list>
	</property>
</bean>

If you don’t want to define a static list in the XML config, you could dynamically fill in the values using Java code and the Spring Expression Language.
In the following example, the method getListValues() of the class MyClass is used to retrieve the values for the list property of the bean.

<bean id="myBean" class="de.mypackage.MyBean">
	<property name="listProp" value="#{T(de.mypackage.MyClass).getListValues()}"/>
</bean>

Einsortiert unter:Spring Universe Tagged: spring, Spring Expression Language, XML

Prompt for confirmation when leaving a page

$
0
0

Sometimes users leave a web page without clicking on a save button to save the changes they made to a form.
In this case, it can be useful to show a confirmation popup and ask them if they really want to leave the page without saving.
To achieve that, embed the following Javascript snippet (tested with IE9 and Firefox 5):

<script type="text/javascript">
window.onbeforeunload = function(){
	var message = 'There are unsaved changes. Are you sure that you want to leave this site?';
	if(checkForUnsavedFormChanges){
		return message;
	}
};
</script>

The code above registers for the onBeforeUnload event, which fires when the user leaves the site, e.g. by

  • clicking on a link
  • entering a different URL in the browser
  • closing the browser window

You have to implement the checkForUnsavedFormChanges() function with your custom code to check for form changes.

When using the Dojo Toolkit, you can easily check for form changes using the dojo.formToObject(formNode: DOMNode|String); function. It will create a snapshot of a form. When the form is loaded, create a snapshot and compare this original snapshot with a new snapshot in the checkForUnsavedFormChanges() function.


Einsortiert unter:Java Web Frameworks Tagged: confirmation, javascript, onbeforeunload

Selenium 2 – Differences to Version 1

$
0
0

Selenium 2 is out for a month now. As I had to introduce Selenium into a project, I picked the new version of Selenium (2.2). I’d like to show some of the differences between Selenium 1 and 2 that I experienced.

Selenium 1

  • supports real browsers only – no HtmlUnit support, needs a graphical desktop environment (slower but more realistic compared to HtmlUnit)
  • JavaScript based approach
  • when used in unit tests, you need a proxy application to control the browser (Selenium-RC)
  • limited by the browser’s Javascript security model
  • complex API, API has evolved over time (dictionary-based approach)
  • API methods for specific HTML elements – e.g. checking checkboxes, selecting radio buttons, selecting elements from dropdown menus etc.

Selenium 2

  • Selenium 2 has been created from Selenium 1 and the Webdriver project
  • backwards compatible to Selenium 1
  • Webdriver API
    • simple, object oriented API
    • supports real browsers and headless HTMLUnit (HTMLUnit should be faster than testing with a real browser)
    • uses most appropriate mechanism to control the browser (IE: automation controls, Firefox: Extension, Chrome: Webdriver API)
    • not limited by browser’s Javascript security model
    • more realistic simulation of the user’s actions by using OS level events (typing, mouse, …)
    • no API methods for specific HTML elements (e.g. checking checkboxes etc.) – you use click and type commands only (this could be a disadvantage)
    • you can no longer manipulate non-visible fields (e.g. hidden fields) (this could be a disadvantage)
    • methods to wait for elements to appear – very useful for testing ajax applications
  • you do no longer need selenium-rc (proxy to control the browser) in your unit tests. Webdriver is able to control the browser directly
  • Selenium-RC and Selenium-Grid from Selenium 1 have been merged into Selenium Server
  • supports all major desktop browsers (IE, Firefox, Opera, Webkit, Chrome), mobile browsers (IPhone, Android) and headless HtmlUnit

The newest version of the test recorder tool Selenium IDE already supports Selenium 2.

From my point of view, the improved ajax testing functionality, the direct browser control without proxy and the improved API make the upgrade worthwhile.


Einsortiert unter:Java and Quality Tagged: Functional Testing, selenium, Webdriver

JavaScript Lint – checks your JavaScript source code for common mistakes

$
0
0

I recently worked on a web application with a lot of Javascript code in it. The app worked well in Firefox, but when trying it in Internet Explorer 7 – to my surprise – the app did not work and reported a lot of weird errors (unfortunately, the error report wasn’t helpful). The IDE (Eclipse) did not report any errors in my Javascript files.

I found a tool that helped me a lot in finding the errors: JavaScript Lint.

JavaScript Lint is an open source tool (GPL) that checks your JavaScript source code for syntax errors and questionable coding practices. It gives you a detailed report with line numbers and a description whats wrong (and what could be improved) in your code. You can configure which warnings schould be reported.

Some problems the tool is able to detect (excerpt):

  • Missing semicolons at the end of a line.
  • Curly braces without an if, for, while, etc.
  • Code that is never run because of a return, throw, continue, or break.
  • Case statements in a switch that do not have a break statement.
  • Leading and trailing decimal points on a number.
  • A leading zero that turns a number into octal (base 8).
  • Comments within comments.
  • Ambiguity whether two adjacent lines are part of the same statement.
  • Statements that don’t do anything.

There’s also an online version of the tool that you can use to try it out.

After fixing the errors reported by JSLint, the app worked in both IE and Firefox.


Einsortiert unter:Java and Quality, Other languages for the Java VM Tagged: javascript, Lint

Debugging Dojo Applications

$
0
0

When you try to debug your JavaScript sources of your Dojo Toolkit webapp / website using Firebug, you will realize soon that it’s quite not possible.
Error reports are linked to framework JavaScript files but do not point you to the location where the error actually occurs.
Step debugging is not possible, too. The only thing you can do is to add log statements in your code, which isn’t a very productive debugging approach.

Fortunately, there is a switch to turn on the ability to debug your application.
When you load the Dojo library …

<script type="text/javascript" src="dojo/dojo.js" djConfig="parseOnLoad: true" />

… simply add debugAtAllCosts: true to the djConfig attribute to make debugging work:

<script type="text/javascript" src="dojo/dojo.js" djConfig="parseOnLoad: true, debugAtAllCosts: true" />

debugAtAllCosts will significantly slow down your application, so it is important to disable it when you deploy your application to a production environment.


Einsortiert unter:Java Web Frameworks Tagged: Debugging, Dojo Toolkit, javascript

Environment specific externalized Grails configuration

$
0
0

Grails supports environment specific configuration, which can be used to define different settings for development, test, production or custom environments. The Grails User Guide describes this feature in detail. E.g. you can define different database settings for development (use a local test database) and production (use a remote database).

Besides that, Grails supports externalized configuration (again see Grails User Guide). You can define one or more config files (properties or groovy config files supported). The contents of the config files will be merged with the Config.groovy config file in your application (external config file will override existing Config.groovy settings with the same name). This is extremly useful to separate database settings from your sourcecode.

Here is an example how you can define an external config file with the name of your app in the user’s home directory:

// Config.groovy
grails.config.locations = [ "file:${userHome}/${appName}-config.properties" ]

To get the best of both worlds, you can combine these two features: use a general external config file and one external config file for each environment. The environment specific config file will have precedence over the general external config file.

// Config.groovy
grails.config.locations = [ "file:${userHome}/${appName}-config.properties",
"file:${userHome}/${appName}-${grails.util.Environment.current.name}-config.properties" ]

When you start your app in development mode, the following external config files will be picked up (assuming your app has the name myapp):

myapp-config.properties
myapp-development-config.properties

When you start your app in production mode, a different environment specific config file will be picked up:

myapp-config.properties
myapp-production-config.properties

Einsortiert unter:Groovy and Grails Tagged: Config, Environment, grails

Integrating Selenium 2 with Ant

$
0
0

We recently integrated Selenium 2 into the Ant build of one of our projects. In this blog post I will show you how you can integrate your automated JUnit based Selenium 2 tests with Ant. If you are using Maven instead, you should probably read the german blog post Automatisierte Selenium-Tests mit Maven. The build script snippets in this blog post should also work with Selenium 1 or other web application test tools that can be used with JUnit.

Before the tests can be started, you need to deploy your application to a servlet container and start the server. After your tests have finished, you have to shut down the server container. I assume that you already have Ant targets to start and stop your server. In the following example these targets are called tomcat.start and tomcat.stop.

First define an Ant target called selenium.test. This target should depend on a compile target and on a target to deploy your application to the servlet container. These targets should already exist in your build.xml. Here is the actual Ant target:

<target name="selenium.test" depends="compile.test, webapp.deploy" description="Deploy application, start Tomcat, run Selenium tests, shutdown Tomcat">
    	<parallel>
	    	<antcall target="tomcat.start"/>
    		<sequential>
    			<waitfor maxwait="2" maxwaitunit="minute">
    				<http url="${selenium.browserURL}"/>
    			</waitfor>
    			<mkdir dir="${results}/selenium-tests" />
				<junit fork="true" forkmode="once" haltonfailure="false" printsummary="yes" tempdir="${target}" failureproperty="selenium.test.successful">
					<classpath path="${classes}" />
					<classpath path="${classes.test}" />
					<classpath refid="classpath.compile" />
					<classpath refid="classpath.test" />
					<batchtest todir="${results}/selenium-tests">
						<fileset refid="files.test.selenium" />
					</batchtest>
					<formatter type="xml" />
				</junit>
				<mkdir dir="${reports}/selenium-tests" />
				<junitreport todir="${reports}/selenium-tests">
					<fileset dir="${results}/selenium-tests">
						<include name="TEST-*.xml" />
					</fileset>
					<report todir="${reports}/selenium-tests" />
				</junitreport>
	    		<antcall target="tomcat.stop"/>
    			<fail if="selenium.test.successful" message="Selenium test(s) failed!"/>
    		</sequential>
    	</parallel>
    </target>

Because the tomcat.start target will block until the server has been stopped, you cannot define a dependency to that target. You need to call the tomcat.start target and the actual test tasks in parallel. The test execution has to wait until the servlet container is ready, so it periodically checks a URL (defined via the property selenium.browserURL) until the application is availlable.

The properties needed are as follows:

  • target – points to your target folder, e.g. ${basedir}/target
  • results – points to a folder where the test results will be saved, e.g. ${target}/results
  • reports – points to a folder where the test reports will be saved, e.g. ${target}/reports
  • classes – points to the folder where your compiled classes are located, e.g. ${target}/classes
  • classes.test – points to the folder where your compiled classes are located, e.g. ${target}/classes-test
  • selenium.browserURL – URL of your web application deployed to your local servlet container, e.g. http://localhost:8080/myapp/

Additionally, you need to define the following paths:

  • classpath.compile – fileset with all required libraries for your application
  • classpath.test – fileset with all required libraries to run the tests

This is an example of these path difinitions:

<path id="classpath.compile">
	<fileset dir="${lib.compile}">
		<include name="**/*.jar" />
	</fileset>
</path>
<path id="classpath.test">
	<fileset dir="${lib.test}">
		<include name="**/*.jar" />
	</fileset>
</path>

Finally you need to define a fileset files.test.selenium that includes all Selenium test classes. E.g. you could define to include all files that end with Test.class in a subdirectory of the selenium folder:

<fileset id="files.test.selenium" dir="${classes.test}">
	<include name="**/selenium/**/*Test.class" />
</fileset>

Einsortiert unter:Build, config and deploy, Java and Quality, Java Web Frameworks Tagged: ant, junit, Selenium 2, test, tomcat

Grails 2.0 released

$
0
0

It took Grails 6 years from it’s beginning to reach version 2.0.
A lot of great and long awaited features justify the version jump from 1.3 to the new major release 2.0.

Visit the What’s new in Grails 2.0? page for a nice summary of all the new features and grab it while it’s hot.

My favorite new features are:

  • Spring 3.1
  • Tab completion for the Grails console – closing the gap to Spring Roo
  • Reloading Agent (hopefully it’s better than the current class reloading feature)
  • H2 Database and Console – finally you can look into your development database! RIP HSQLDB…
  • Binary Plugins
  • Controller actions as methods – I did never understand why Grails prior to 2.0 used closures for controller actions…
  • HTML5 Scaffolding – at last. It was about time!
  • Easy Date Parsing – missed it so much, no more hand made date conversion routines…
  • Multiple Data Sources Support – you don’t need a plugin any longer to use multiple data sources in your Grails app
  • Database Migrations plugin – no need to do this manually with Liquibase

To me it looks like the best Grails version ever. Hopefully it doesn’t come with too many new bugs ;-)


Einsortiert unter:Groovy and Grails Tagged: grails, release

Grails Database Queries – Criteria Builder vs. Where Queries [updated]

$
0
0

Before Grails 2.0 arrived, Grails offered 3 ways of doing a database query:

  • dynamic finders
  • HQL queries
  • Hibernate Criteria Builder

If the database query is very simple, dynamic finders are a good choice. But for everything else, I used Criteria Builder which is just the Hibernate Criteria API with builder syntax.

Starting with Grails 2.0, there is another alternative: Where Queries.
Where Queries are similar to the Criteria Builder approach, but using a nicer “programmer friendly” syntax and your queries get checked at compile-time (!).
As it uses Detached Criterias under the hood, it should (hopefully) support everything that is possible with Criteria Builder.

Here is an example of a simple Where Query:

def query = Book.where {
   title == "Grails in Action"
}
Book grailsInAction = query.find()

The syntax is more natural for Groovy developers. You don’t need to have the Hibernate Criteria API in mind. Just write your query as if you would deal with a normal collection using Groovy code. Because it uses AST transformations (compile-time metaprogramming), your query gets compile time checked and you will get IDE support / code completion (e.g. using STS). Using Where Queries, you can refactor your domain model and you will almost instantly see whether or not the refactoring breaks existing query logic.

I asked myself if the Where Query approach is as powerful as Criteria Builder. Are there queries that you can’t implement using Where Queries?
And is the generated SQL identical to Criteria Builder’s SQL statements?

I started to expermiment with same common database queries which I wrote both using Criteria Builder and Where Queries:

Multiple restrictions and querying associations

This example shows how to use multiple restrictions in one query and how to query associations. In this case: list all books with a title that contains the word ‘grails’ (case insensitive) and that have an author whose last name starts with an ‘R’ character (again, case insensitive).

// Criteria Builder
Book.createCriteria().list {
	ilike('title', '%grails%')
	authors {
		ilike('lastName', 'r%')
	}
}

// Where Query
Book.findAll {
	title =~ '%grails%' && authors.lastName =~ 'r%'
}

The generated SQL statements are identical for both approaches:

SELECT THIS_.ID AS ID0_1_, THIS_.VERSION AS VERSION0_1_, THIS_.DATE_CREATED AS DATE3_0_1_, THIS_.ERSCHEINUNGSDATUM AS ERSCHEIN4_0_1_, THIS_.ISBN AS ISBN0_1_, THIS_.LAST_UPDATED AS LAST6_0_1_, THIS_.PUBLISHER_ID AS PUBLISHER7_0_1_, THIS_.TITLE AS TITLE0_1_, AUTHORS3_.BOOK_ID AS BOOK1_0_, AUTHORS_AL1_.ID AS AUTHOR2_, AUTHORS_AL1_.ID AS ID3_0_, AUTHORS_AL1_.VERSION AS VERSION3_0_, AUTHORS_AL1_.FIRST_NAME AS FIRST3_3_0_, AUTHORS_AL1_.LAST_NAME AS LAST4_3_0_ FROM BOOK THIS_ INNER JOIN AUTHOR_BOOKS AUTHORS3_ ON THIS_.ID=AUTHORS3_.BOOK_ID INNER JOIN AUTHOR AUTHORS_AL1_ ON AUTHORS3_.AUTHOR_ID=AUTHORS_AL1_.ID WHERE lower(this_.title) like ? and (lower(authors_al1_.last_name) like ?)

Pagination and sorting

This example show how to sort the results of the query and how to limit the result count, starting at a given offset. In this case: list all books with a title containing the word ‘grails’ (case insensitive), limit results to one result, starting at index 1, sorted by property ‘title’ ascending.

// Criteria Builder
Book.createCriteria().list {
	ilike('title', '%grails%')
	maxResults(1)
	firstResult(1)
	order('title', 'asc')
}

// Where Query
Book.findAll(max:1, offset:1, sort:'title', order:'asc'){
	title =~ '%grails%'
}

The generated SQL statements are identical for both approaches:

SELECT THIS_.ID AS ID1_0_, THIS_.VERSION AS VERSION1_0_, THIS_.DATE_CREATED AS DATE3_1_0_, THIS_.ERSCHEINUNGSDATUM AS ERSCHEIN4_1_0_, THIS_.ISBN AS ISBN1_0_, THIS_.LAST_UPDATED AS LAST6_1_0_, THIS_.PUBLISHER_ID AS PUBLISHER7_1_0_, THIS_.TITLE AS TITLE1_0_ FROM BOOK THIS_ WHERE LOWER(THIS_.TITLE) LIKE ? ORDER BY this_.title asc limit ? offset ?

Unfortunately, the sort order of the Where Query (sort:’title’) doesn’t get compile time checked.

Sorting by more than one property

This example shows how to sort by two properties. In this case: list all books, sorted by title and isbn.

// Criteria Builder
Book.createCriteria().list {
	order('title', 'asc')
	order('isbn', 'asc')
}

// Where Query
def query = Book.where {}.order('title', 'asc').order('isbn', 'asc')
query.list()

The generated SQL statements are identical for both approaches:

SELECT THIS_.ID AS ID3_0_, THIS_.VERSION AS VERSION3_0_, THIS_.DATE_CREATED AS DATE3_3_0_, THIS_.ERSCHEINUNGSDATUM AS ERSCHEIN4_3_0_, THIS_.ISBN AS ISBN3_0_, THIS_.LAST_UPDATED AS LAST6_3_0_, THIS_.PUBLISHER_ID AS PUBLISHER7_3_0_, THIS_.TITLE AS TITLE3_0_ FROM book this_ order by this_.title asc, this_.isbn asc

Although it is possible to use Where Queries here, you have to add the sort order to the query using Criteria API. So: no compile time checks, no IDE support -> no advantage over Criteria Builder approach.

Projections

This example shows how to use restrictions, which means retrieving just some fields and not domain objects. In this case: retrieve just the ‘isbn’ property of all books in the database.

// Criteria Builder
Book.createCriteria().list {
	projections {
		property('isbn')
	}
}

// Where Query
def query = Book.where {}.projections {
	property('isbn')
}
query.list()

Again, it is possible to use Where Queries here, but you have to add the projection to the query using Criteria API. So: no compile time checks, no IDE support -> no advantage over Criteria Builder approach.

Conclusion

Where Queries offer a nicer syntax and – which is imho a really great feature – get compile time checked.
Unfortunately, it lacks some advanced query features like multi sorting or projections. As Where Queries use the Criteria API under the hood, it is possible to do such things by adding them to your query using the Criteria syntax, but you are loosing compile time checks. This hopefully gets fixed with future Grails releases.
Personally, I’m going to use Where Queries whenever possible, falling back to Criteria Builder for queries that are not possible with Where Queries.

[update]
Updated “Sorting by more than one property” and “Projections”: it is possible to do such things by combining Where Queries with Criteria API. (thanks to Stephane Maldini)
[/update]


Einsortiert unter:Groovy and Grails Tagged: Criteria Builder, Database, grails, Hibernate, Query, Where Query

Knockout JS 2.0.0 released – Dynamic JavaScript-UIs using Data Binding

$
0
0

The Knockout JS Team recently released version 2.0.0 of their JavaScript data binding framework.

Knockout JS is a small Javascript library that offers declarative data binding for your HTML code. It enables you to separate you HTML code from your data and UI logic, offering automatic UI refresh and dependency tracking.
I’m going to write an introductional blog post on KnockoutJS soon. In the meantime, check out the great introduction video of the creator Steve Sanderson.

The new features of version 2.0.0 are:

  • Control flow bindings
    You don’t need a template engine like jquery-tmpl any longer. Simply use the new control flow bindings if, ifnot, with, and foreach.
    <ul data-bind="foreach: products">
        <li>
            <strong data-bind="text: name"></strong>
            <em data-bind="if: manufacturer">
                &mdash; made by <span data-bind="text: manufacturer.company"></span>
            </em>
        </li>
    </ul>
    
  • Containerless control flow
    You can now avoid using a container element for bindings like foreach by using the new comment-based control flow syntax.
    <ul>
        <li><strong>Here is a static header item</strong></li>
        <!-- ko foreach: products -->
        <li>
            <em data-bind="text: name"></em>
        </li>
    </ul>
    
  • Access to parent binding contexts
    You can now access properties that exist at the upper levels of binding via the new pseudo-variables $data, $parent, $parents and $root.
  • Cleaner event handling
    There is now a cleaner, more declarative syntax for event handling bindings that does no longer require to write inline function literals.
  • Binding providers
    There is a new binding providers API to extend the default data binding mechanism. It acts as a general extensibility mechanism.
  • Throttling
    It is now possible to limit how often change events are fired (e.g. only one change event per 500ms). BTW, ko.dependentObservable has been renamed to ko.computed.

For a full list of all new features see Steve Sanderson’s blog entry.

There is also a Grails Plugin available, but as Knockout is just a single JavaScript-File, I would recommend to include it in a Grails project directly without a plugin.


Einsortiert unter:Groovy and Grails, Java Web Frameworks Tagged: Data Binding, Dynamic UI, grails, javascript, Knockout JS, mvvm

Firebug 1.9 released

$
0
0

Firebug

The popular web developer tool Firebug has been released in version 1.9.

The new features include:

  • Firebug panel docking
    it is now possible to dock the Firebug panel to any of the four sides of the browser window.
  • Syntax error position
    Firebug now shows not only the line of an error, but also the exact position.
  • Support for JSON responses
    JSON responses are now supported, including a partial copying of tree elements to the clipboard.
  • Console log output linked to origin
    All console messages are now linked to their origin (file+line).
  • More tooltips while debugging scripts

The full changelog is available at hacks.mozilla.org.

Firebug 1.9 is compatible with Firefox 5.0 – 11.0

.


Einsortiert unter:Java Web Frameworks Tagged: clipboard, developer tool, Firebug, web developer

Grails is getting Maven support

$
0
0

According to a recent blog post of Grails project lead Graeme Rocher, Grails is getting Maven support in the form of a plugin.

Currently, Grails uses Maven repositories for dependency resolution, but the build system of a Grails application uses Gant. For Grails 3.0 it is planned to establish Gradle as the build system of choice, as Gradle is getting more and more popular.

But as Maven is already widely used in the Java world, Graeme wants to provide Maven as an alternative build system.
There will be an initial plugin providing basic Maven support soon, which will be compatible with Grails 2.0.
A more refined integration will become available later, but it will probably requiere Grails 2.1.


Einsortiert unter:Build, config and deploy, Groovy and Grails Tagged: ant, Build, Gant, gradle, grails, maven

Grails 2.0 Upgrade Guide

$
0
0

The Grails team has started a Google Plus discussion to gather feedback from the community on how their upgrade to Grails 2.0 went.

To sum it up, small applications can be upgraded easily to Grails 2.0, but for large application the upgrade is quite painful.

Peter Ledbrook has published a Guide on how to upgrade an existing Grails application to version 2, summarizing the pitfalls that have been found by the Grails team and the community. This guide will be updated when the Grails team has gathered further feedback from Grails developers.

Some hours ago, the Grails team has published an advice on Google Plus: If you want to migrate your tests to the new unit testing capabilities of Grails 2.0, wait for the next bugfix release (which is due to some issues found):

If you’re upgrading to Grails 2 and you want to migrate your tests, it’s probably worth waiting for 2.0.1. Several important fixes related to unit tests coming in that version.


Einsortiert unter:Groovy and Grails Tagged: grails, Guide, Upgrade

JSON as core type in PostgreSQL 9.2

$
0
0

It looks like PostgreSQL 9.2 will get a JSON core type. Additionally, there will be functions to produce JSON data from database queries:

  • query_to_json()
  • array_to_json()
  • row_to_json()

Here is a simple example that uses the new query_to_json function:

SELECT query_to_json('select user_name as username, role_name as role from USER',false);

This query will produce JSON data:

[{"username":"testuser","role":"user"},{"username":"johndoe","role":"admin"}]

This could be very useful for web applications that use a lot of JSON data to communicate between the frontend and backend.


Einsortiert unter:Java Persistence Tagged: JSON, PostgreSQL

Twitter’s Bootstrap 2.0 released

$
0
0

Twitter recently released Bootstrap 2.0.

Bootstrap is a open-source HTML/CSS toolkit (Apache 2 licence) to build modern websites or web applications. It’s not a framework but a set of css styles and jQuery plugins to help kick starting your application with responsive layout and modern design that works on desktop browsers as well as on mobile devices.

Bootstrap offers fluid, responsive layouts that adjust with screen / browser window sizes. It also offers a set of UI components (some are pure HTML/CSS, more complex components are based on jQuery).

To sum it up, Bootstrap offers:

See the examples page to get an impression on how a web site could look like that use Bootstrap.

You don’t have to use the whole feature set – you can customize your download and pick only the parts you need, e.g. just use styling for tables, but nothing else, or use just the UI components you need.

The new features of version 2.0 include:

  • improved documentation
  • smarter default styling
  • new 12-column grid system
  • new table and form styles, compatible with jQuery UI
  • new ui components like improved navigation components, buttons, button groups, button dropdowns
  • simplified alert messages
  • carousel, collapse, and typeahead jQuery plugins

Einsortiert unter:Java Web Frameworks Tagged: Bootstrap, CSS, html, Layout, Style, twitter
Viewing all 72 articles
Browse latest View live