Chlebik goes into JVM jungle. Something ends, something begins.

It’s been a while since the last post. I think, a while is an overstatement, it’s been ages. The reason why is quite obvious – I’ve reached the point, where there’s a problem with what to write. It boils down to two approaches – go with ‘How to…’ or ‘Introduction to…’ posts for the beginners, or very detailed information about specific topics. The former I’m having every day at work (tutoring youngsters and doing code reviews). The latter posts are read by few readers, and they don’t attract wider publicity.

It took me a couple of years to reach the point, where I wanted to change something (build a house along the way, but that’s no biggie). Therefore, my second project emerged, where I’ve dived into low-level stuff, which I’ve never touched before. Over a year has passed, and it’s time for a change there too. More on that can be read in this post, although as it touches Java, I wanted to share a little here too.

My goal is to get away for a moment of strictly business-like Java (which I’m doing every day at work), and dive into the internals of the JVM. Get knowledge about how things work there, where code meets the machine, and all the hard work is being done. Hence my plan to learn C++ and first start with garbage collection algorithms. That’s my goal for upcoming months(years?).

It’s at the same time an official farewell to this blog. I’ve started it a long time ago, when I was PHP programmer with maybe 9 months of commercial experience. In August/September I had 10 year anniversary of working in Java. Seems like a lifetime, and it is. This blog will remain online, as a memory of who I was, and what I can become in the future, but only as it. No more blog posts will be published, oficially confirming the current-state-of-things.

I want to say big Thank You to all the readers of the blog. I met wonderful people through it, and build a network of interesting developers. Learned a lot in a process, and build a strong foundation for my knowledge. But that’s it. It’s time to say goodbye, and close this chapter in my life. If I ever was to return, that will probably happen in the different place. Farewell.

Jboss AS Wildfly for Java developer tutorial

How often do You face situation when local development is done using simple Tomcat or Jetty container? Very often backed up with JRebel? Yeah, that’s what I thought 馃槈 It works like a charm but finally there is always an ultimate problem – deployment to dev/integration/prod environment. Why it is an issue? Because usually it is application server we have to deal with. And here comes the problem.

I’ve faced such situation many times. The expected truth is that it should make no difference. Servlet container is also a part of application server. Yes, I can agree to that, but very often there is some kind of a problem during application deployment in application server. If we have always-ready-to-fast-response-admin-team it is no such big deal. But what happens if reality is not so great – and the only thing we have is log file that does not tell us anything? We have a problem for sure. And that is exactly my point. It is better to understand a little bit of our application server. That is the subject of this blog post. I will show how to install and configure local instance of JBoss Wildfly and deploy simple application to it. I do not see this post as comprehensive tutorial – it is just some kind of ‘lessons learned’ to me. Let’s go.

Versioning, terminology and WTH is EAP?

In the good old days everything was simple. There was JBoss Application Server and that was it. I remember when I entered Java world version in use was 4.x one. As years went by I sometimes came across next versions of that server in my contractor’s career, but never paid special attention as I mostly used Weblogic. Some time ago I found out that there is some kind of new kid in town – Wildfly. After a little bit of digging I learned that it as good old Jboss AS but with different name. Why did that happen?

The answer is simple – JBoss Enterprise Application Platform (or for short Jboss EAP) emerged. EAP is a commercial product – it is usually much more ahead with bugfixes that community version of the server. To use it in a production mode you have to pay Jboss. On the other side there is still good old Jboss AS which is now called Wildfly mostly because there was very similar versioning of EAP and JBoss AS. The truth is – if You have EAP used in production (or dev/integration env) and You want to make sure Your app will work there use this site to find out which application’s server version You need and then download it and run. Wildfly is a name for newer version of Jboss AS (starting from version 8) and as far as I can see it, so far it is not yet used in EAP at all.

Despite what I have written above I decided to use latest stable Wildfly in my tutorial. Why? Because as I browsed through latest EAP and Wildfly documentation and folders I see no difference. What is more important – Wildfly can be downloaded ‘by hand’ from its page, with EAP registration is required. And I know for how many people that can be a concern 馃槈 So just download 8.2.0.Final and we can start.

Installation, folder structure and first run

Installing JBoss is fairly easy – just download ZIP archive and unpack it. Piece of cake. Now we can proceed to the unpacked directory to the bin folder. There are files (executables for both Windows and Linux). What should we use? The idea here is to understand the modes in which server can be run. There are two:

a) standalone mode – which is sufficient for 99% of usages on developer’s machines. It does not mean that it is not suitable for production machines. Server running in standalone just run in one process and whole configuration is specific only to this one machine.

b) domain mode – it is mostly used in production environments as it provides way to keep server’s config consistent using just one machine.

Domain mode does not mean clustering! There is no problem to create cluster using both – standalone or domain mode.

In order to understand basic concepts which are important to Java developers I will use standalone mode in this post. My idea is to present domain and clustering in the future. Sometimes I will mention things related to domain mode (in comparison to standalone).

Having said that we concentrate only on bin/standalone.bat executable (I am working on Windows, Linux users should be familiar with .sh scripts). To separate run-scripts from configuration there is additional config file named standalone.conf.bat, that is used by run-script to customize configuration. Usually when there is no previous JBoss (which in fact means there is no global JBOSS_HOME variable set) we need no additional configuration (besides set JAVA_HOME). Before we start the server we can look around bin folder:

a) adduser.bat – adds user to the server security realm.
b) application-client.bat – it starts lightweight container for client applications that communicate with JBoss. More can be found in this link.
c) init.d – folder containing example run-scripts for running JBoss as a service on linux machine. Be careful! The script may need tweaking to run seamlessly on your system.
d) jboss-cli – I will describe this utility later. It is management utility allowing admins to change server configuration from command line
e) jconsole.bat – widely known tool to monitor working JVM
f) jdr.batJBoss Diagnostic Reporter. It will collect useful data from the server, resulting in ZIP file which can be used eg. by support from JBoss
g) run.bat – legacy launch script, not used
h) vault.bat – command line tool to secure sensitive data
i) wsconsume/wsprovide – are command line tools (and also Ant tasks) to generate webservice from WSDL (wsconsume) or from endpoint class (wsprovide)

Now we know our way around. We can finally start Wildfly in standalone mode and the end of run process should be logged similar to this:

21:00:18,761 INFO [org.jboss.ws.common.management] (MSC service thread 1-3) JBWS022052: Starting JBoss Web Services – Stack CXF Server 4.3.2.Final
21:00:19,045 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.0.0.1:9990/management
21:00:19,048 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.0.0.1:9990
21:00:19,050 INFO [org.jboss.as] (Controller Boot Thread) JBAS015874: WildFly 8.2.0.Final “Tweek” started in 16305ms – Started 184 of 234 services (82 services are lazy, passive or on-demand)

In order to check if everything is ok we can download sample applications for Wildfly from official GitHub page. The most basic is of course helloworld. Just go to the folder You cloned the code and issue the command (with server still running):

mvn clean package wildfly:deploy

In server’s log we should see something like this:

21:21:39,944 INFO [org.wildfly.extension.undertow] (MSC service thread 1-8) JBAS017534: Registered web context: /wildfly-helloworld
21:21:40,894 INFO [org.jboss.as.server] (management-handler-thread – 1) JBAS018559: Deployed “wildfly-helloworld.war” (runtime-name : “wildfly-helloworld.war”)

Right now the only thing left to se is working application. We can visit http://localhost:8080/wildfly-helloworld and see if everything is ok. There should be plain and simple Hello World message on the screen.

Server’s administration

Main idea behind Jboss lately is to avoid editing XML files in order to perform administrative tasks. It is good thing – while doing changes using prepared application it is possible to perform additional validation, which avoid errors. By default console application is accessible on port 9990, although if we visit it right now that is the view we are going to see:

NoUser

As mentioned we must create user to access the app. Remember the list of additional scripts in bin folder? There was script add-user.bat – we are going to use it right now. Process is simple – just add new Management User and follow the questions on the screen. When finished, You can log in http://localhost:9990/console and see something like this.

WildflyConsole

It means we have admin user and server is working properly. More about admin-related tasks can be found on Akquinet.

So how to deploy an app?

When we do not want to use Maven plugins deployment process is fairly simple.

  • GUI application – just visit Deployments tab in this app and point to existing file.
  • Auto deploy – the same way as it was done in previous versions. Just copy new file to standalone/deploy folder and it will be picked up by server automatically.
  • CLI deployment – quite obvious (example taken from the docs):
    // run jboss-cli.bat
    // type 'connect' to connect to running instance
    
    [standalone@localhost:9999 /] deploy ~/Desktop/test-application.war
    'test-application.war' deployed successfully.
     
    [standalone@localhost:9999 /] undeploy test-application.war
    Successfully undeployed test-application.war.
    

Where are my logs?

At the end I will describe problem I’ve faced while deploying my app to development server. The title is right – I could not find my log files. On my local machine slf4j and logback were used, creating two separate files with logs. One for SQL statements and one for everything else. When I deployed application to the Jboss it did not work.

Wildfly has modular architecture. Logging is performed by logging subsystem that can be configured in several ways (yep, console application is one of them). But before that subsystem kicks in, server logging during startup is done via logging.properties file, that resides in configuration directory. I saw that file and was sure that this is final config. Unfortunately it is not. As I’ve mentioned – it is used only before logging subsystem starts.

This subsystem has simple property – add-logging-api-dependencies, that when set to true will force server to provide logging libraries and dependencies. That makes my application’s logging config not working. To fix that I could change above setting, but it was impossible as it affects whole server. So there is another solution. I’ve added file jboss-deployment-structure.xml to my WEB-INF. It is one of deployment descriptors recognized by JBoss. The file looked like this:

<jboss-deployment-structure>
    <deployment>        
        <exclusions>
            <module name="org.slf4j" />
            <module name="org.slf4j.impl" />
            <module name="org.slf4j.api" />
            <module name="org.slf4j.jcl.over.slf4j" />
            <module name="org.apache.log4j" />
            <module name="ch.qos.logback.core" />
            <module name="ch.qos.logback.classic" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>

It excludes modules with given name, but can be done better as described in this forum thread

<jboss-deployment-structure>  
  <deployment>  
     <!-- exclude-subsystem prevents a subsystems deployment unit processors running on a deployment -->  
     <!-- which gives basically the same effect as removing the subsystem, but it only affects single deployment -->  
     <exclude-subsystems>  
        <subsystem name="logging" />  
    </exclude-subsystems>  
</jboss-deployment-structure> 

After deployment everything started to work as expected.

JavaScript Patterns book review

lrg I have never actually studied JavaScript. It was something that came with the job, back then, when I started working as PHP programmer. I have no problem with jQuery usage and also with jQuery Ui components, but this is all. Reading JavaScript Patterns was like a breathe of a fresh air again.

The book concentrates on good practices and patterns used in proper JavaScript coding. It does not cover very much of the language internals but shows why one approach is good and why another is bad. Therefore there is also a great piece of knowledge gained in the process, what is important, every chapter is full of practical solutions. All aspects of JavaScript programming – scalar values, object creation, functions or code conventions have been described. Intentionally or not, the book is short and cohesive course of JavaScript itself.

Maybe it is just me, but all articles or papers I’ve read about JavaScript in the past was heavily linked with the browser. That is not an issue here. Although there is separate chapter describing DOM and browsers, all knowledge and examples were given without browser in mind. You can run all examples eg. in Nashorn.

It seems that mamy review is short. But that is the beauty of book I am reviewing – there is no doubt that You should read it. Despite working with JavaScript or not – it will just make You a better coder.

Model variables for all views in Thymeleaf 2.1 with Spring MVC

Recently I’ve stumbled upon quite common problem – how to inject a few variables to every Thymeleaf view in application. Of course there is @ModelParam annotation, I could use interceptor or @ControllerAdvice. All solutions are described on StackOverFlow (it is about controllers).

The problem was that I wanted to put Maven build information in that model (to show version and build time in footer). Therefore I did not need application-scope wiring, as build informations are available during Spring’s container startup. So I’ve found another solution dealing with model itself on the lower level – pure XML configuration. There is a special property in ThymeleafViewResolver that can be used – static variables. So code sample can look like this:

<bean id="thymeleafViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="staticVariables">
            <map>
                <entry key="myModelVariableIWantToSet" value="My model variable value" />
                <!-- All placeholders taken from context:property-placeholder tag can be used as value-->
            </map>
    </property>
</bean>

All defined variables are put into all Model instances that are linked to Thymeleaf views. If You are just serving plain JSON it does not go there – that can be expected behaviour or not! Be aware of that fact.

Spring MVC Revisited

Recently I had an opportunity to play with architecture of a new internal app in my company. In order to properly do my job I’ve reread whole Spring MVC documentation. It was very refreshing ( after a while of using this framework ) to discover several new things. My goal is just to present short list of features with links to docs. There is no point in reinventing the wheel 馃槈

Matrix Params

Ever wanted to provide more data with just URI? Matrix variables are the best way to do this. Just look at the URI presented:

http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,,+3.91;AZN=236.00,+103.00;SBRY=375.50/account;name=roger;number=105;location=stoke-on-trent,uk

Yep, you can process it and extract data very easilly. Above URI and nice blog posts about them can be found on Captain’s Debug blog (second part with code snippets here).

ModelAttribute

I am used to using ModelAttribute annotation, mostly on update/save actions in my controllers. What I did not know is that this annotation can be also used with methods. Remember all the situations when You must fill several model variables with data just in order to render them as eg. SELECT-tag values? Now you create just one method in controller and annotate it with @ModelAttribute to put method return value in model. More information can be found in spring docs.

Flash attributes with redirects

I remember problems with simple flash redirects a few years back (circa early Spring’s version 3, flash attributes were introduced in 3.1). Today they are even better handled – You do not need to manually put them into FlashMap. There is a nice class RedirectAttributes which greatly improves coders’ quality of life. Just look at this code:

@RequestMapping(value = "/accounts", method = RequestMethod.POST)
 public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
   if (result.hasErrors()) {
     return "accounts/new";
   }
   // Save account ...
   redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
   return "redirect:/accounts/{id}";
 }

Above example comes from RedirectAttributes API, but there is also short Spring doc section and simple tutorial.

BindingResult order

There is nothing new in BindingResult interface. But what cought my attention is the need for this interface be declared as first parameter after @ModelAttribute in controller’s method to work!. I was not aware of that and I assume knowing that can be real time-saver. Short example:

public String addNewBlogger(@ModelAttribute("blogger") Blogger blogger,
            ModelMap map, BindingResult results) 

The above example will not work properly. You will get either exception or application’s logic will behave strangely (depends mostly on error handling and view layer/resolver). Proper solution look like this:

public String addNewBlogger(@ModelAttribute("blogger") Blogger blogger, BindingResult results, ModelMap map) 

Simple creation of URIs

Very often there is a need to create a new URI, eg. to perform redirect. Concatenating string values with parameters is not often clean and simple (not to mention it is very error prone). In order to ease developers’ life Spring provides very dsl-like solution with MvcUriComponentsBuilder class. More can be found in documentation.

[Links] Strings concatenation in Java and Groovy

Lately I had a discussion at work regarding strings concatenation in Java and Groovy. To clear the view I hit the web and found several interesting posts about it that I want to share but the truth is after reading this I know less than before 馃槈

http://www.javacodegeeks.com/2013/03/java-stringbuilder-myth-debunked.html
http://java-performance.info/primitive-types-to-string-conversion-and-string-concatenation/
http://stackoverflow.com/questions/11359333/string-concatenation-with-groovy

There is a little bit more – while searching the web I have found neat solution in latest聽Java聽with a class StringJoiner聽which allows programmer to forget about pluses or several <em>append()</em> calls.

Hacking as game

Recently I’ve been interested in several different areas of computer science, one of which is web/system security. I am not trying to join Anonymous or something ;), but You can never have enough knowledge. Due to that fact I’ve stumbled upon a nice page, with some kind of CTF-like games or tasks, which can greatly increase Your knowledge about linux, web and security. I have not ended all tasks but it can be really fun. Here is the page – http://overthewire.org/.

Shortcut for jRebel executor in Intellij Idea

I have recently started working again with Intellij Idea with jRebel. This tool-combo is one of the best things that ever happened to me, although I faced a little problem.

When running Tomcat instance from Intellij (with jRebel configured properly) You should use a little rocket icon on your toolbar.

WhichIcon

After clicking it Tomcat starts and there is console window at the bottom of the screen. But imagine the situation when this window is hidden – You toggled fullscreen mode or searched for something. The only way to show that window again was to use mouse and go to menu View->Tool Windows and the find JRebel Executor. I tried to assign shortcut for this (similar to simple Run action), but I could not find proper action on the shortcut list (menu File->Settings->Keymap). The solution is simple – Tomcat with JRebel must be TURNED ON to create this shortcut!! While running Intellij Idea will show additional item for JRebel executor in actions list! Just assign it shortcut You want and viola, it works.

OneToMany relations with ordering in Grails – one form solution

The article was written during development. Therefore final solution differs from the code presented in the beginning of this post. If You want to see how working code looks like just check my Github.

It is quite common situation – we want two domain classes to share one form. In addition there is also oneToMany relation between them. And to make things a little bit harder we need to keep order of many side of the relationship – despite delete or create operations. With simple drag&drop functionality. Of course in Grails. Are You ready? Let’s go.

I started with solution described by ObjectPartners, but it got one big problem. It was using additional jQuery plugin, and therefore was doing some kind of ‘under the hood’ job, which was not suitable for my needs. So I have switched to plain jQuery and its plugins mainly due to main information source about this topic. My solution is fairly similar to described in omarello post, but if You do not need other form elements that inputs in your list and do not even think about sorting and ordering them, solution provided by by ObjectPartners will suffice.

Grails way of oneToMany

Before coding there is an important issue raised in comments section. Imports required for code snippets to work include:
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService
import org.springframework.security.core.authority.GrantedAuthorityImpl
import org.springframework.security.core.userdetails.UserDetails

We should start with two simple domain classes:

package com.wordpress.chlebik

class Article {

	String title
	ArticleType type
	boolean deleted

	static transients = [ 'deleted' ]

	static constraints = {
		title(size: 3..12, nullabe: false)
	}

	String toString() {
		title
	}

}

enum ArticleType {

	NEWS,
	STORY

}

package com.wordpress.chlebik

class Newspaper {

	String name
	List<Article> articles = []

	static hasMany = [articles: Article]

	static mapping = {
		articles cascade:"all-delete-orphan"
	  }

    static constraints = {
		name(nullable: false, blank: false, size: 3..16)
    }

	String toString() {
		name
	}
}

They are simple but provide several usefull features – like list of types in enum and constraints. They are important in this example, but for now we should just focus on simple relation. Newspaper consists of Articles – you should pay attention to the fact, that I have used not only belongsTo mapping, but directly declared that there is a List of Articles. Default Grails’ behaviour with oneToMany relations is to use Set. We want to maintain order fo our Articles so I used List.

If You run application with default data source settings – Grails will automatically create tables in memory (with h2 db engine). Just visit http://localhost:8080/YOURAPPNAME/dbconsole and see by yourself what is going on. We have two simple tables for domain classes and one join table – NEWSPAPER_ARTICLE. There are two columns with foreign keys and what is more important – there is articles_idx column, which is needed for keeping order of articles. And all that thanks to Grails’ db creation. Awesome.

We got model created, now it is time for web layer. Within Grails’ console issue a command:

generate-all com.wordpress.chlebik.Newspaper

and in a moment we have generated controller and views. Unfortunately they do not provide possibility to create new articles within newspaper but it gives us a solid code-base to proceed. First, we should create a newspaper with articles in it. I will not use form generated, as it lacks functionality we need. Nothing as simple as issuing this code on controller or bootstrap:

Newspaper n = new Newspaper(name: 'ChlebikZine')

Article a1 = new Article(title: 'Title1', type: ArticleType.NEWS)
Article a2 = new Article(title: 'Title2', type: ArticleType.NEWS)
Article a3 = new Article(title: 'Title3', type: ArticleType.STORY)
n.articles.add(a1)
n.articles.add(a2)
n.articles.add(a3)

n.save()

Edit and update existing domain class

After running the application we can visit http://localhost:8080/YOURAPPNAME/newspaper/show/1 to see how our newspaper is rendered (I’ve changed page source generated by Grails, eg. removed links to articles edition).

ChlebikZine

It is show action and it looks fine. To now we can switch to editing. I am interested in list with editable fields. Right now I also want to have delete link to remove existing records (we do not add new ones so far). So our _form.gsp should look like this.

<%@ page import="com.wordpress.chlebik.Newspaper" %>

<script type="text/javascript">

jQuery(document).ready( function() {

	$(document).on("click", ".deleteArticle",function(event) {	

		var tableBody = $('#articlesListTableBody');
		var rowToDelete = $(this).closest('tr');
		var rowId = rowToDelete.attr('rowId');		

		// This is for removing only already existing rows in DB.
		if( !$(rowToDelete).attr('newRow') ) {
			$(tableBody).append("<input type='hidden' name='articles[" + rowId + "].deleted' value='true' />");
		}

		$(rowToDelete).remove();
		return false;
	});

	$('.addNewArticle').click( function() {

	});

} );

</script>
<div class="fieldcontain ${hasErrors(bean: newspaperInstance, field: 'name', 'error')} required">
	<label for="name">
		<g:message code="newspaper.name.label" default="Name" />
		<span class="required-indicator">*</span>
	</label>
	<g:textField name="name" maxlength="16" required="" value="${newspaperInstance?.name}"/></div>
<div class="fieldcontain ${hasErrors(bean: newspaperInstance, field: 'articles', 'error')} ">
	<label for="articles">
		<g:message code="newspaper.articles.label" default="Articles" />

	</label>
<table id="articlesList">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="articlesListTableBody">
		<g:each in="${newspaperInstance.articles}" var="article" status="i">
<tr rowId="${i}">
<td>
					<g:textField required="" name="articles[$i].title" value="${article.title}"/>
					<g:hiddenField name="articles[$i].id" id="articles[$i].id" value="${article.id}"/></td>
<td>
					<g:select value="${article.type}" name="articles[${i}].type" from="${com.wordpress.chlebik.ArticleType?.values()}" keys="${com.wordpress.chlebik.ArticleType.values()*.name()}" /></td>
<td>
					<a href="#" class="deleteArticle">Delete article</a></td>
</tr>
</g:each></tbody>
</table>
</div>

It is quite simple. Now here is a catch.

In Grails versions before 2.2.x UPDATE method was working differently than shown below. Solution given by ObjectPartners is working then but in newer versions it is not! Check out StackOverflow question. My solution was tested in Grails 2.4.3 with Groovy 2.3.6 and is mainly based on the solution given by Omarello. But it is just partly true. Keep reading to see what I’ve changed to make it work.

Therefore update method of the controller should like this:

 @Transactional
    def update(Newspaper newspaperInstance) {
        if (newspaperInstance == null) {
            notFound()
            return
        }

        if (newspaperInstance.hasErrors()) {
            respond newspaperInstance.errors, view:'edit'
            return
        }

		newspaperInstance.articles.eachWithIndex{ v,i ->
			if( params['articles[' + i + '].deleted'] == 'true' ) {
				v.deleted = true
			}
		}

		newspaperInstance.articles.removeAll{ it.deleted }
        newspaperInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'Newspaper.label', default: 'Newspaper'), newspaperInstance.id])
                redirect newspaperInstance
            }
            '*'{ respond newspaperInstance, [status: OK] }
        }
    }

If you know better solution please let me know – it seems that wiring between form data/params is not transffering deleted property into created Newspaper entity. I’ve tried using:

newspaper.properties = params

With params filled with proper-named attributes for articles but it is not working! So I had to use additional iteration over all articles to set their deleted property. Again – if there is something I am doing wrong please let me know.

Now we should think about adding new articles to our newspaper. As You have seen it is quite simple – we just need to add inputs/selects to our table (in a view layer) with proper name attribute and that is all. Grails should do all the hard work. So after table we add simple link:

<a href="#" class="addNewArticle">Add new article</a>

And of course do not forget about Javascript.

$('.addNewArticle').click( function() {
		var allArticles = $("#articlesListTableBody tr[rowId]");
		var rowId = 0;			

		// This operation is performed to allow safe-delete of newly created (not saved in DB) articles
		if( allArticles.length ) {
			var maxId = 0;
        	allArticles.each(function() {
            	maxId = Math.max(maxId, parseInt($(this).attr('rowId')));
        	});
        	rowId = maxId+1;
		} 			

		$("#articlesListTableBody").append( '<tr newRow="true" rowId="' + rowId  + '">' +
		'<td><input type="text" required="" name="articles[' + rowId + '].title" value=""/></td>' +
                 '<td><select name="articles[' + rowId + '].type" >' +
        	'<g:each in="${com.wordpress.chlebik.ArticleType?.values()}" var="type">
<option value="${type}">${type}</option></g:each>
</select></td>
' +
									'
<td><a href="#" class="deleteArticle">Delete article</a></td>
</tr>
');

		return false;
	});

Nothing new here. We just add another row in our table. Pay attention to the fact, that there is newRow attribute in newly created row. Now it is clear why there was check for that attribute in delete function – if new article was not stored in DB, removal of it is not needed to be presented with deleted property set. You can play around with above solution – adding and deleting articles was never so easy. There is one thing to add – I resigned from cloning existing rows like it was presented in Omorello post. It is possbile when there are for sure rows in articles list and in my way – we can start with empty list so there is nothing to clone. Appending pure strings is maybe more low-level, but gives developer total control (which was compromised by using writetable-plugin).

Validate me

So far we did not checked two things – creation of totally new newspaper (that will come in a moment), ad validation (in facts it is about re-rendering of the view). Let’s have a look.

In generated views there is required attribute in inputs which are responsible for rendering domain class properties that have nullable : false in constraints. Newspaper name is one of them. Let’s see what will happen if we remove that attribute in GSP and submit empty newspaper name.

SaveSuccess

Apparently everything is all-right. Added article was successfully persisted in the DB. That is because our newspaper is separated from articles – constraint violation on newspaper do not stop persisting new article (because it is proper entity). Now let’s try to remove required attribute from article title and try to submit new article without it – sorry. We receive error message.

NPE

Do not ask me why and what does it mean. fortunately I know what helps – removing @Transactional annotation on our update method in controller!. If you remove it, form will re-render with proper error message. But try to submit form another time with new article empty title. It will give us error with finding deleted property in our code.

newspaperInstance.articles.removeAll{ it.deleted }

Somehow Grails managed to create new article which violates constraint (empty title) and is trying to save it! The cure for this is adding if statement in GSP that is listing all articles.

<g:each in="${newspaperInstance.articles}" var="article" status="i">
<tr rowId="${i}">
<td>
					<g:textField required="" name="articles[$i].title" value="${article.title}"/>
					<g:if test="${article.id}">
						<g:hiddenField name="articles[$i].id" id="articles[$i].id" value="${article.id}"/>
					</g:if></td>
<td>
					<g:select value="${article.type}" name="articles[${i}].type" from="${com.wordpress.chlebik.ArticleType?.values()}" keys="${com.wordpress.chlebik.ArticleType.values()*.name()}" /></td>
<td>
					<a href="#" class="deleteArticle">Delete article</a></td>
</tr>
</g:each>

This is the second time I do not know why Grails behaves like this – I understand that when there is no id attribute Grails will treat created domain class as new instance to persist. But how can it try to persist an entity which fails validation! Just to remember, generated update method has at the beginning:

if (newspaperInstance == null) {
      notFound()
      return
}

if (newspaperInstance.hasErrors()) {
     respond newspaperInstance.errors, view:'edit'
     return
}

Why this works for the first empty-title submit and fails at the second – I have no idea. Fortunately adding show-id logic in GSP helped.

But I want new newspaper

We started this topic from existing entity and editing it. It was easier that way to create clean code and show what is essential in oneToMany in one form. Right now we are going to create new newspaper and add some articles to it. There is already generated form and controller action. The truth is that – it works 馃槈 But only if we do not start to fool around validation again. To make long things short – there is a problem with treating newly added articles as new ones, not stored in DB (therefore they do not have id). _form.gsp must be modified in a section reponsobile for rendering article list (mainly safe-operator logic).

<table id="articlesList">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="articlesListTableBody">
		<g:each in="${newspaperInstance.articles}" var="article" status="i">
<tr <g:if test="${!article?.id}">newRow="true"</g:if> rowId="${i}">
<td>
					<g:textField required="" name="articles[$i].title" value="${article?.title}"/>
					<g:if test="${article?.id}">
						<g:hiddenField name="articles[$i].id" id="articles[$i].id" value="${article?.id}"/>
					</g:if></td>
<td>
					<g:select value="${article?.type}" name="articles[${i}].type" from="${com.wordpress.chlebik.ArticleType?.values()}" keys="${com.wordpress.chlebik.ArticleType.values()*.name()}" /></td>
<td>
					<a href="#" class="deleteArticle">Delete article</a></td>
</tr>
</g:each></tbody>
</table>

Now we can do whatever we want with creation of new entity – try to break validation, add and delete articles, try to break articles’ validation, whatever You want. It just works 馃槈

Gimme more – I want to sort things out

Generally I did not expect sorting to work so easily and quickly. Of course You need to download/link jQeury UI with sortable. After that You must change _form.gsp to this:

<%@ page import="com.wordpress.chlebik.Newspaper" %>

<script type="text/javascript">

jQuery(document).ready( function() {

	$(document).on("click", ".deleteArticle",function(event) {	

		var tableBody = $('#articlesListTableBody');
		var rowToDelete = $(this).closest('tr');	

		// This is for removing only already existing rows in DB.
		if( !$(rowToDelete).attr('newRow') ) {
			var rowId = $(rowToDelete).attr('rowId')
			var articleId = $("input[name='articles[" + rowId + "].id']").val();
			$(tableBody).append("<input type='hidden' name='articles[" + articleId + "].deleted' value='true' />");
		}

		$(rowToDelete).remove();
		return false;
	});

	$('.addNewArticle').click( function() {
		var allArticles = $("#articlesListTableBody tr[rowId]");
		var rowId = 0;			

		// This operation is performed to allow safe-delete of newly created (not saved in DB) articles
		if( allArticles.length ) {
			var maxId = 0;
        	allArticles.each(function() {
            	maxId = Math.max(maxId, parseInt($(this).attr('rowId')));
        	});
        	rowId = maxId+1;
		} 			

		$("#articlesListTableBody").append( '<tr newRow="true" rowId="' + rowId  + '">' +
		'<td><input required="true" type="text"  name="articles[' + rowId + '].title" value=""/></td>' +
                '<td><select name="articles[' + rowId + '].type" >' +
		'<g:each in="${com.wordpress.chlebik.ArticleType?.values()}" var="type">
                  <option value="${type}">${type}</option>
                 </g:each></select></td>' +
                 '<td  class="moveRow"><a href="#" class="deleteArticle">Delete article</a></td>
                  <td class="moveRow">Move</td></tr>');

		return false;
	});

	 $('#articlesListTableBody').sortable({
	        stop: function (event, ui) {
	            updateNames($(this))
	        },
	        handle: '.moveRow',
	    });

	 function updateNames($tbody) {
		    $tbody.find('tr').each(function (idx) {
		        var $inp = $(this).find('input,select,textarea');
		        $(this).attr('rowId', idx);
		        $inp.each(function () {
		            this.name = this.name.replace(/(\[\d\])/, '[' + idx + ']');
		        })
		    });
	}

   } );

</script>
<div class="fieldcontain ${hasErrors(bean: newspaperInstance, field: 'name', 'error')} required">
	<label for="name">
		<g:message code="newspaper.name.label" default="Name" />
		<span class="required-indicator">*</span>
	</label>
	<g:textField name="name" required="" maxlength="16"  value="${newspaperInstance?.name}"/></div>
<div class="fieldcontain ${hasErrors(bean: newspaperInstance, field: 'articles', 'error')} ">
	<label for="articles">
		<g:message code="newspaper.articles.label" default="Articles" />

	</label>
<table id="articlesList">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Delete</th>
<th>Move</th>
</tr>
</thead>
<tbody id="articlesListTableBody">
		<g:each in="${newspaperInstance.articles}" var="article" status="i">
<tr <g:if test="${!article?.id}">newRow="true"</g:if> rowId="${i}">
<td>
					<g:textField required="" name="articles[$i].title" value="${article?.title}"/>
					<g:if test="${article?.id}">
						<g:hiddenField id="" name="articles[$i].id" value="${article?.id}"/>
					</g:if></td>
<td>
					<g:select value="${article?.type}" name="articles[${i}].type" from="${com.wordpress.chlebik.ArticleType?.values()}" keys="${com.wordpress.chlebik.ArticleType.values()*.name()}" /></td>
<td>
					<a href="#" class="deleteArticle">Delete article</a></td>
<td class="moveRow">
					Move</td>
</tr>
</g:each></tbody>
</table>
<a href="#" class="addNewArticle">Add new article</a></div>

JavaScript code used in this example comes from StackOverflow question – it works just out-of-the-box. But there is a catch – only with already persisted entities. So create new newspaper, add several new articles, save them. After that edit newspaper switch order and save it again. It works like a charm.

The problems begin when removal of rows or changing order of not yet persisted rows – I receieved many different errors and logical errors. It took me about two hours – after that I was not sure what was the reason that it started working 馃槈 But it does – I definetly added refreshing input-indexes after row removal in Javascript (same action that is triggered when sorting ends). I’ve removed delete property completly – and it still works. Magic.

So here is view and controller.

<%@ page import="com.wordpress.chlebik.Newspaper" %>

<script type="text/javascript">

jQuery(document).ready( function() {

	$('#articlesListTableBody').sortable({
        stop: function (event, ui) {
            updateNames($(this))
        },
        handle: '.moveRow',
    });

 	function updateNames($tbody) {
	    $tbody.find('tr').each(function (idx) {
	        var $inp = $(this).find('input,select,textarea');
	        $(this).attr('rowId', idx);
	        $inp.each(function () {
	            this.name = this.name.replace(/(\[\d\])/, '[' + idx + ']');
	        })
	    });
	}

	$(document).on("click", ".deleteArticle",function(event) {	

		var tableBody = $('#articlesListTableBody');
		var rowToDelete = $(this).closest('tr');	

		$(rowToDelete).remove();
		updateNames(tableBody);
		return false;
	});

	$('.addNewArticle').click( function() {
		var allArticles = $("#articlesListTableBody tr[rowId]");
		var rowId = 0;			

		// This operation is performed to allow safe-delete of newly created (not saved in DB) articles
		if( allArticles.length ) {
		    var maxId = 0;
        	    allArticles.each(function() {
            	        maxId = Math.max(maxId, parseInt($(this).attr('rowId')));
        	    });
        	    rowId = maxId+1;
		} 			

		$("#articlesListTableBody").append( '<tr newRow="true" rowId="' + rowId  + '">' + 									
                 '<td><input required="true" type="text"  name="articles[' + rowId + '].title" value=""/></td>' +
                 '<td><select name="articles[' + rowId + '].type" >' +
		'<g:each in="${com.wordpress.chlebik.ArticleType?.values()}" var="type">
                 <option value="${type}">${type}</option></g:each></select></td>' +
		'<td  class="moveRow"><a href="#" class="deleteArticle">Delete article</a></td><td class="moveRow">Move</td></tr>');

		return false;
	});

} );

</script>
<div class="fieldcontain ${hasErrors(bean: newspaperInstance, field: 'name', 'error')} required">
	<label for="name">
		<g:message code="newspaper.name.label" default="Name" />
		<span class="required-indicator">*</span>
	</label>
	<g:textField name="name" required="" maxlength="16"  value="${newspaperInstance?.name}"/></div>
<div class="fieldcontain ${hasErrors(bean: newspaperInstance, field: 'articles', 'error')} ">
	<label for="articles">
		<g:message code="newspaper.articles.label" default="Articles" />

	</label>
<table id="articlesList">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Delete</th>
<th>Move</th>
</tr>
</thead>
<tbody id="articlesListTableBody">
		<g:each in="${newspaperInstance.articles}" var="article" status="i">
<tr <g:if test="${!article?.id}">newRow="true"</g:if> rowId="${i}">
<td>
	<g:textField id="" required="" name="articles[$i].title" value="${article?.title}"/>
		<g:if test="${article?.id}">
			<g:hiddenField id="" name="articles[$i].id" value="${article?.id}"/>
		</g:if></td>
<td>
	<g:select value="${article?.type}" name="articles[${i}].type" from="${com.wordpress.chlebik.ArticleType?.values()}" keys="${com.wordpress.chlebik.ArticleType.values()*.name()}" /></td>
<td>
	<a href="#" class="deleteArticle">Delete article</a>
</td>
<td class="moveRow">Move</td>
</tr>
</g:each></tbody>
</table>
<a href="#" class="addNewArticle">Add new article</a></div>
 def update(Newspaper newspaperInstance) {

        if (newspaperInstance == null) {
            notFound()
            return
        }

        if (newspaperInstance.hasErrors()) {
            respond newspaperInstance.errors, view:'edit'
            return
        }

	newspaperInstance.articles.clear()
	newspaperInstance.properties = params

	newspaperInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'Newspaper.label', default: 'Newspaper'), newspaperInstance.id])
                redirect newspaperInstance
            }
            '*'{ respond newspaperInstance, [status: OK] }
        }
    }

Almost finished

Looking back at all the trouble I had with figuring out the proper solution made me wonder – why do not use AJAX? This is fine idea but I wanted to deal with pure Grails’ form handling. Full source (with final solution) can be found on my Github. As I mentioned before – I have used Grails 2.4.3 with Groovy 2.3.6.

ENUM in Grails with i18n support

Enums are pretty usefull聽Java聽feature. However, developers often encounter problems with two things – reflecting enum in database and i18n. Database is often a easy thing – store enum value in character column or even in specialised column type (eg. in聽MySQL). Internationalization is a little bit harder but fortunately聽Grails聽makes it so easy. The goal of this tutorial is to show how Grails can present enum values in a view layer with translated values.

The key interface is MessageSourceResolvable 聽which comes of course from聽Spring.聽We can have simple enum like this:

 

enum WarriorLevel implements org.springframework.context.MessageSourceResolvable {

    BEGGINER, NOVICE, APPRENTICE, MASTER

    // Methods inherited from interface
    public Object[] getArguments() { [] as Object[] }
    public String[] getCodes() { [ name() ] }
    public String getDefaultMessage() { name() }
}

Nothing new except implementation of methods inherited from interface. They are very simple, just for demonstration purposes.
Another thing to be done are internationalization entries. Grails keeps them in i18n folder with separate files for every language that can be supported. I come from Poland therefore my filename is messages_pl.properties. For given enum entries look like that (prefix is just for clearance):

com.wordpress.chlebik.BEGGINER=nowy
com.wordpress.chlebik=nowicjusz
com.wordpress.chlebik=adept
com.wordpress.chlebik=mistrz

Now the only thing is to put everything in motion – in a view layer we naturally use Grails tags to create select element:

<g:select name="chlebikTest" from="${WarriorLevel?.values()}" keys="${WarriorLevel .values()*.name()}" value="${warrior?.level?.name()}" valueMessagePrefix="com.wordpress.chlebik" />

And that’s all folks. Here are some links about it:

Grails page (check out last entry)
Enum in Grails domain from StackOverflow
Enum in GSP view from StackOverflow

Incrementing Grails application version during WAR packaging

Grails comes with several predefined properties, which can be used in application or build process. One of them is application version. It can be found in application.properties file and the usual way is to change it manually. Of course we can find a plugin – version updater – that makes that via Grails console. But what about situation in which every WAR creation should trigger version update?

Quick fix for that can be seen below (it is based on the script I have found on this blog). It is a simple script which should be places in /scripts folder of our project in a file named _Events.groovy. During WAR creation this script will be read and executed. Of course logic presented is fairly simple and lacks some parameters validation but I will leave it up to the developer.


eventCreateWarStart = { warName, stagingDir ->
	
	Map<String,Integer> mappings = [ 'M' : 0, 'm' : 1, 'p' : 2 ]
	String versionParam = System.getProperty('version.update.position', 'M')
	def lastAppVersionNumberList = metadata.'app.version'.split('\\.')
			   
	
	println "*** Started customised version update of Grails app. Current version: ${metadata.'app.version'}"
				
	lastAppVersionNumberList[ mappings[versionParam] ] =        Integer.valueOf(lastAppVersionNumberList[mappings[versionParam]]) + 1
	
	metadata.'app.version' = lastAppVersionNumberList.join('.')
	metadata.persist() 
	
	println "*** Ended customised version update of Grails app. Current version: ${lastAppVersionNumberList.join('.')}"
}

Happy anniversary Chlebik – 200 blog posts and counting

Yep, WordPress does not lie – this post is number 200. When I think who I was back in 2008 (‘Hello World’ published 11th of August 2008) I see a giant leap I made. Moreover, I have managed to ‘jump into’ Java ecosystem and stay there 馃槈 Starting writing in English was another big step in my career. It is seventh blog post written in English and it seems I am doing quite well.

To make things better – I have decided to start my own GitHub account, to share the code I am presenting in more blog-independent way. I hope it will improve my readers well-being and also helps to spread good code samples around 馃槈 I was surprised that chlebik account name was not already taken – here it is.

Grails logging class names

I have recently dived into聽Grails’ logging features. It is simple mechanism but I stumbled upon a problem with class names. If You want to log behaviour in controllers, domains or services – You have to prefix class name with prefix聽grails.application.聽So when I tried to log my services i should have write something like this:

warn   'grails.app.services.com.wordpress.chlebik.MyClass'

Instead of:

warn   'com.wordpress.chlebik.MyClass'

The truth is that documentation聽shows that in code samples – next time – read the manual stupid 馃槈

LDAP Authentication and DB authorisation with Grails Spring Security

Recently I faced quite simple problem – allow application to authenticate users via LDAP but authorise them via database. It is a common solution – we make sure that only company’s users are logging into app, but there comes flexibility with ACL stored locally. In Grails it looked pretty simple until I started to integrate this solution into my application. It took me a while to put everything together so I decided to share it.

To make long things short – there is an offical documentation but IMHO, it should be tweaked a little to be more user-friendly. The most important thing to understand are sides and roles that take place in logging process. There is LDAP instance, where we send requests to authorise user. LDAP response must be transmitted to our app and full our users’ object. Meanwhile there is also roles read from database. In addition there is simple check – if logging user has no account in our app, we will create it with default roles.

My app uses simple domain classes provided by Spring Security (User, Role and UserRole). If You are not familiar with them I suggest reading official docs. First we create UserMappingDetails class, which is simple POJO that will store user data (login, password, account data) and authorities (roles that user has).

class ChlebikUserDetails extends GrailsUser {

   ChlebikUserDetails(String username, String password, boolean enabled,
                 boolean accountNonExpired, boolean credentialsNonExpired,
                 boolean accountNonLocked,
                 Collection<GrantedAuthority> authorities,
                 long id, String fullName) {
      super(username, password, enabled, accountNonExpired,
            credentialsNonExpired, accountNonLocked, authorities, id)      
   }
}

Next we create mapping class, which will translate LDAP response to our application user.

class ChlebikUserDetailsContextMapper implements UserDetailsContextMapper {

	private static final List NO_ROLES = [new SimpleGrantedAuthority(SpringSecurityUtils.NO_ROLE)]
		
	@Override
	@Transactional
	public ChlebikUserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<SimpleGrantedAuthority> authority) {
		
		User user = User.findByUsername(username)
		
		if(!user) {					
				// Create new user and save to the database                                
				user = new User()
				user.username = username				
				user.password = "123" // doesn't matter
				user.save(flush: true, failOnError: true)
									
				UserRole userRole = new UserRole()
				userRole.user = user
				userRole.role = Role.findByAuthority('USER') // Default role in my app
				userRole.save(flush: true, failOnError: true)			
		}
						 
		def authorities = user.getAuthorities().collect { new SimpleGrantedAuthority(it.authority) }		
		def userDetails = new ChlebikUserDetails(username, user.password, user.enabled, false,
					false, false, authorities, user.id, username)
		return userDetails
	}

	
	@Override
	public void mapUserToContext(UserDetails arg0, DirContextAdapter arg1) {}	
}

Ok, we are getting closer. Last class to create is service that will be called by Spring Security to retrieve our user when needed. It cannot be put in Grails’ service directory!!! Just place it in src/groovy

class PrePopulateUserDetailsService implements GrailsUserDetailsService  {
	
	Logger logger = Logger.getLogger(getClass())
	LdapUserDetailsService ldapUserDetailsService
	
	static final List NO_ROLES = [new SimpleGrantedAuthority(SpringSecurityUtils.NO_ROLE)]
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		return loadUserByUsername(username, true)
	}
	
	@Override
	@Transactional	// Services in Grails are transactional by default but it is normal class so we put this annotation
	public UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException, DataAccessException {
				
		User user = User.findByUsername(username)
		def authorities = user.getAuthorities().collect {new SimpleGrantedAuthority(it.authority)}
		
		return new ChlebikUserDetails(user.username, user.password, user.enabled,
			!user.accountExpired, !user.passwordExpired,
			!user.accountLocked, authorities ?: NO_ROLES, user.id,
			user.username)   
	}
}

That’s all. Of course we need to add some config to our application. First we visit configuration folder and spring subfolder. There in resources.groovy we put this (registering beans):

beans = {		
	ldapUserDetailsMapper(com.wordpress.chlebik.ChlebikUserDetailsContextMapper)
	userDetailsService(com.wordpress.chlebik.PrePopulateUserDetailsService)
}

And in out Config.groovy (or whatever user-defined config file You are using) we should have several config properties. I am putting them all (to allow Grails connect to LDAP).

grails.plugin.springsecurity.providerNames = ['rememberMeAuthenticationProvider', 'ldapAuthProvider', 'anonymousAuthenticationProvider']

// Probably better to keep this data in an external file for security reasons
grails.plugin.springsecurity.ldap.context.managerDn = ''
grails.plugin.springsecurity.ldap.context.managerPassword = ''
grails.plugin.springsecurity.ldap.context.server = ''

grails.plugin.springsecurity.ldap.authorities.ignorePartialResultException = true // typically needed for Active Directory
grails.plugin.springsecurity.ldap.search.base = 'CN=putwhatyoumust,O=putwhatyoumust'
grails.plugin.springsecurity.ldap.authenticator.dnPatterns=='uid={0},CN=putwhatyoumust,O=putwhatyoumust'
grails.plugin.springsecurity.ldap.search.filter="uid={0}" 
grails.plugin.springsecurity.ldap.search.searchSubtree = true
grails.plugin.springsecurity.ldap.auth.hideUserNotFoundExceptions = false

// These are crucial for LDAP/DB configuration
grails.plugin.springsecurity.ldap.mapper.userDetailsClass='com.wordpress.chlebik.ChlebikUserDetails'
grails.plugin.springsecurity.ldap.authorities.retrieveGroupRoles = false
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = true

And it magically works. Above code is the result of several hours on the web. Below I put all links that helped me a lot.

Grails passwords salted
Juan Vazquez GitHub
Most helpfull Nabble
Customizing authentication in your grails app
Official plugin page

Groovy 2.3.5 backward compatibility with Spock unit tests

In my new workplace there is a problem – corporate firewall, which is a common problem in IT world. Therefore update sites of Eclipse are blocked, which means quite a mess with dependencies and plugin management.

My main concern was Spock, which I have run using built-in Groovy in version 2.3.6, while tests and whole application was written in Grails 2.2.3 with Groovy a little bit older 馃槈 Finally it came to my attention that hated exception

Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.typehandling.ShortTypeHandling at java.net.URLClassLoader$1.run(URLClassLoader.java:372)

can be easily fixed in a way that Guillaume Laforge wrote. Just downloaded JAR, added to project’s classpath and there it is – my Spock test are working like charm.

Welcome back Grails

I started my journey with learning Java web-frameworks with Grails. That was really long time ago (around 2009) with Grails’ version 1.0.4. When I became full-time Java programmer I used Grails in several internal CRUD apps, but it was quick&dirty solution to provide basic functionality. My new job (I’ve just started) involves mainly programming with Groovy&Grails therefore I’ve decided to write a few posts about what is going on in Groovy&Grails world right now.

grails Before I start there is a big announcement. As Graeme Rocher posted on Twitter, new version of Grails (starting with number 3) will be totally new thing – based on Spring Boot and many projects around it. Therefore Grails being described here is going to retire in a predictable future. Just so You know.

The latest version of Grails which I am using is 2.4.3 with Groovy in version 2.3. In a following article I am gonna to point out some problems and interesting things I have discovered while ‘getting in touch’ with latest Grails.

Scaffolding

Scaffolding is often presented as one of the most ‘groovy’ thing in Grails. The ability to quickly prototype working application is powerful feature and it was a place where I started my revisit. And right at the beginning I have encountered an subtle problem. Reference documentation says that there is a possibility to run such code:

class UserController {
     static scaffold = true     
}

And it should work with existing User domain class. I have given it a try but I was unsuccessfull. Why? Grails complained about missing domain class. What have I done wrong? The problem is with packaging – I have never liked examples using default package. With Grails it is even more problematic as there are separate folders for controllers, domain classes and so on. Therefore as I created com.wordpress.chlebik.grails.tutorial package inside domain folder, framework could not resolve proper path. The solution is simple – just use full class name.

class UserController {
     static scaffold = com.wordpress.chlebik.grails.tutorial.User
}

It works like a charm. It is also possible to use such code to enable scaffolding for a given domain class even from controllers with different name:

class AdminController {
     static scaffold = com.wordpress.chlebik.grails.tutorial.User
}

In my opinion Grails scaffolding is even better than it was with feature called static scaffolding. Back in 2009 scaffolding was interesting, but it was done as a ‘runtime magic’. There was no way to interact with generated sources (or it was not so easy). Right now we have static scaffolding which is scaffolding but with generated sources. Imagine creating simple domain class like User

class User {

    static constraints = {}
	
    String       firsrName
    String       lastName	
    String       email	
	
}

Using Grails console or IDE support we can invoke command:

grails generate-all User

which creates separate views (I mean GSP files) and controller with implemented methods. What is more cool, are test classes (based on Spock specifications) generated as well with testing logic within! So if You are not familiar with unit-testing – it is a great place to learn how it is done.

Testing

A few years ago my knowledge about TDD was almost non-existent. It has changed since then, therefore I welcomed Grails’ testing support pretty great. As I mentioned above, we can be given out-of-the-box tests methods with logic in them. Of course it is not what TDD is about, but it makes a good start to make changes and go further. What is more interesting is use of mixins. They provide simple way to link tested class with tests itseslf. What is more cool is use of Spock testing framework. I have to admit I have a problem with finding which plugin/core functionality provides Spock as a dependency. There is Spock Grails Plugin but I do not see any dependencies to it in plain configuration files.

But enough of it – we have Spock at our service, so using it is very simple. Just like this:

@TestFor(UserController)
class UserControllerSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
    }
}

If You are trying to run above test it is possible You get initializationError. Test method must atually test something – leaving empty method body is not an option!

We are given several implicit objects like request, response, controller, view to support controller testing. We can use very straightforward annotation @Mock – which just instantiates in-memory GORM which mocks all ORM-related calls. There is also possiblity to run integration tests, and what is even more cool – even more plugin for functional tests. Back in time there was only Canoo available, now new solutions like Selenium and Geb are also an option. It is hard to write here all about testing in Grails. I am planning to wrote more in separate posts.

Config options

Config files are still very neat way to tail application to our needs. What is the most important change since I last worked with Grails is added BuildConfig.groovy file, which was designed to separate configuration of build process and application config itself. What is more fabulous is logging configuration – so many customizing possibilities! To keep things short I am planning also some kind of post about it, but there is a nice place to start.

Asset Pipeline Plugin

As a Java programmer I am not keeping up with latest changes in HTML&CSS&JavaScript community. There has been tremendous progress in that areas lately (not to mention HTML5, LESS&SASS, writing MVP apps in JavaScript). Therefore creators of Grails are trying to simplify several things so they have switched from resources-plugin to asset-pipeline-plugin.

With previous approach, all resources put in web-app folder were just laying there waiting for the programmer to use them. It was a matter of view layer to include or exclude used resources. Right now plugin has possibility to include or exclude portions of CSS or JavaScript used on certain page. Another cool thing is ability to automaticaly apply changes in resources code while in development mode. there is a great Youtube video about it.

Static compilation

Somewhere by the road to Groovy 2.0 and Java 7 appeared static compilation and invoke dynamic. To make long things short – in a situation where You do not need dynamic Groovy features, it is possible to disable them and gain boost on performance. There are is nice blog post worth mentioning.

Summary

As I walk through the latest reference documentation I constantly see something new. It is hard to put everything in one blog post therefore I am planning several additional articles about latest Grails and Groovy combo. Stay tuned.

Knock knock! Who is there? Chlebik in English…

Yep, the time has come, my blog will be – as of this moment – written only in English.

keep-calm Switching languages is not a simple thing, but lately I’ve realised, that my skills and experience have grown a little since 2008 when I started blogging and I need some new challenges. There are many great blogs and programming sites on the internet (unfortunately – in English) and I want to be a part of it. Writing only in Polish (which was a great decision back in 2008) now is somehow limiting.

I keep all my archives as they were – in Polish – main pages descriptions will also not be translated. Blog’s interface should be changed to English by the time You are reading this note. From this day all my posts are gonna be written in English. It is not my native language so I am asking my readers to forgive me if any mistakes appear.

Jak zarz膮dza膰 ba艂aganem framework贸w, czyli o narz臋dziu GVM

Z pewno艣ci膮 znacie ten b贸l, kiedy u偶ywa si臋 jednego z framework贸w czy j臋zyk贸w JVM, kt贸rych kolejne wersje wychodz膮 do艣膰 cz臋sto i dobrze by艂oby od czasu do czasu uaktualni膰 istniej膮ce instalacje. Zazwyczaj ko艅czymy z du偶膮 ilo艣ci膮 poinstalowanych wersji, w r贸偶nych miejscach i nie wiedz膮c do ko艅ca ile tego mamy i gdzie. Je偶eli nie jest to sytuacja Wam obca polecam zapoznanie si臋 z bardzo fajnym narz臋dziem o nazwie GVM, kt贸re jest napisane w czystym bash-u, a do sprawnego dzia艂ania potrzebuje tylko curl-a oraz unzip-a. Narz臋dzie to pozwala w bardzo wygodny spos贸b zarz膮dza膰 wszystkimi zainstalowanymi wersjami najr贸偶niejszych bibliotek – oto lista obecnie wspieranych:

  • Groovy
  • Grails
  • Griffon
  • Gradle
  • Groovyserv
  • Lazybones
  • vert.x
  • Crash
  • Glide
  • Gaiden
  • JBake
  • Springboot

Wi臋cej informacji oraz sposoby u偶ycia mo偶na znale藕膰 na oficjalnej stronie narz臋dzia.

Usuwanie wierszy z tabel MySQL pomijaj膮c klucze obce

Dzi艣 troch臋 z innej beczki. Ostatnio w zak艂adzie przysiadam troch臋 nad wydajno艣ci膮. Jedn膮 z rzeczy, w kt贸rej macza艂em palce jest przeczyszczenie du偶ych tabel w聽MySQL. Niestety – momentami logika kluczy/contraint贸w聽dla poszczeg贸lnych tabel bywa totalnie niezrozumia艂a, st膮d konieczno艣膰 zastosowania ma艂ych hak贸w.

Jeden z nich objawi艂 si臋 kiedy trzeba by艂o przeczy艣ci膰 tabel臋, kt贸rej cz臋艣膰 klucza g艂贸wnego by艂a kluczem obcym w innej tabeli. 聽Stosowanie znoszenia聽constraint贸w, albo kaskadowe czyszczenie nie wchodzi艂o w gr臋 (kilka archaicznych system贸w, r贸偶ne procesy wk艂adania danych do tabel, itp). St膮d ostatecznie internet podpowiedzia艂 przyjemn膮 rzecz – wy艂膮czenie sprawdzania kluczy obcych. Wi臋cej w tym temacie mo偶na znale藕膰 w tym miejscu, dodam te偶, 偶e rzecz dzia艂a r贸wnie偶 w najnowszej wersji聽MySQL.