As far as I discoved later there can be 2 possible reasons for that. Jasper Reports has dependencies to xerces-impl and xml-apis which can cause conflict with libraries already included in Weblogic. For more details visit appropriate link.

Therefore correct appropriate pom.xml in order to exclude mentioned dependencies:

Thursday, May 14, 2009

Finally got time to post some new information and it is very pleasant to me. Our product, Ganttzilla - online MPP, MPX, Planner documents viewer, finally launched! Ganttzilla is the online project plan documents viewer which supports popular Microsoft Project and Planner formats. Using it You can view or share your Gantts with anyone using just Web Browser. Now we are only beta version but hope to improve it in the future. Will be very grateful for any comments/remarks/criticism, even bugs :)

Monday, March 9, 2009

As far as You know Grails offers many solutions for configuration of Grails application. But most of the configuration is handled by the Config.groovy file in grails-app/conf. I used standard configurations created by default and simply added mail settings in the end of the file as was described in one of my previous posts. But when I tried to read, for instance, grails.serverURL property using grailsApplication.config at controller's layer (and even using ConfigurationHolder at service layer) I've got empty string at runtime. Part of my Config.groovy file is listed below:

I was quiet confused cause I still could read configuration not connected with grails, for instance, log4j settings. As I discovered later problem lied in fact that using grails { (and open bracket) rewrited all previous settings concerning grails. So one of the correct solution might be:

Sunday, March 8, 2009

While working with GSP it is a common situation to perform actions with strings, domain objects or other classes. Recently I faced the simple situation where I needed to dynamically build full file name (with file extension) in order to allow user to download it from file system. In my simple GSP I created the code similar to listed below:

I use concatenation of strings in order to build full file name. But at runtime exception occurred which was very strange and gave me no tip for possible mistake made. As I discovered later in my example You can not use dot in double quotes (".") cause Grails wants to interprete expression in them and fails.Therefore You can solve mentioned situation in two ways:

Use dot in single quotes ('.'). In that case correct solution might be:

Move mentioned logic to some separate class (for instance, let's call it DocumentFileNameBuilder) and call it as it listed below:

Recently I got acquainted with Grails ReCaptcha Plugin, which is very useful for integration with ReCaptcha service. All steps for its installation and basic usage are described here.But one issue which was not covered in details and was not so easy personally for me is customization of ReCaptcha look'n'feel. In other words how to create own custom theme instead of using few standards (red, white, blackglass and clean). I've looked through ReCaptcha API Documentation and Wiki, investigated simple demo, and as a result created simple example for creation of custom theming.

Pay attention:1. Create div with, for instance, recaptcha_widget identifier which is not displayed. After the ReCaptcha theming code will be fully loaded, it will make the div visible. You don't have to make it visible by hands.2. Place mentioned div identified to appriate attribute of recaptcha tag (custom_theme_widget="recaptcha_widget").3. Create div for recaptcha image, it has to be empty and has fixed size.4. Create text field for response and some additional divs for errors, or for recaptcha options (reloading f recaptcha, changing it to audio, help, etc.). Tag identifiers and names must match!5. As an addition You can download standard ReCaptcha images and integrate them into Your theme.As a result all these divs, text field, links and images can be connected to CSS classes and are easy customizable. Also You can use Grails tags, for instance, to render links. Enjoy!

One of the Groovy features I've discovered recently is "import aliasing". For instance, You have two classes with the same name located in two different packages. When You would like to use them together there will be conflict and to resolve it You have to use one of the mentioned classed with full package name. If someone faced such situation You know how inconvenient it is. Groovy helps to solve such situation using "import aliasing": there is an opportunity to set an alias for every import in Your class. For instance, You want to use two different Calendar classes. Let's create alias for own Calendar entity:

by using ControllerUnitTestCase the controller's render method and params property work without any work on our part. This is true of all the dynamic properties and methods of the controller: request, response, params, session, controllerName, redirect, etc. All stuff is done by Testing Plugin

do not forget to call super methods - this will make sure that test will mock appropriate controller class

Sunday, February 15, 2009

Integration tests differ from unit tests in that you have full access to the Grails environment within the test. Grails will use an in-memory HSQLDB database (or another configured data source, for instance MySQL) for integration tests and clear out all the data from the database in between each test. You have to understand that each test is wrapped into transaction which will be rolled back lately. So integration test:

will talk to database, so it will be slower than unit test

will persist data to database - make sure Your test environment database setting don't point to production or development database

A couple of helpful thoughts concerning integration tests:

You have to initialize the service class yourself, there is no dynamic injection. It is the same way as it was during unit testing.

If the service has other service class inside it, You have to initialize and assign it manually. Also it is the same way as it was during unit testing.

Sometimes it is useful to flush session in order to persist to database immediately - else You might get weird thing like no "id" for the supposedly saved domain object or deleted objects would be not deleted. How to do that? It's very easy, please look at the simple example:

class DocumentServiceTests extends GroovyTestCase {

def documentService

// Dynamic injection of session factory. def sessionFactory

void setUp() { // You have to initialize service, // there is no dynamic injection. documentService = new DocumentService() }

void testSomething() { // Some logic. For instance, // documentService.deleteDocumentById(1L). // But document is still not // deleted after execution. // You have to manually flush the session // before assertions. sessionFactory.currentSession.flush() sessionFactory.currentSession.clear()

Wednesday, February 11, 2009

Essential feature of every web application is possibility to send emails. Traditionally when You will look through Grails reference You will find page concerning proposals for email integration in Grails. But approaches mentioned there are not perfect and their implementation in our application was quiet hard. So I decided to look for another solutions and found excellent Grails Mail Plugin. You can easily install it using command:

grails install-plugin mail

Grails Mail Plugin integration is very simple - everything You need is to dynamically inject mail service into Your service. After that You can use its sendMail method for sending email:

Tuesday, February 10, 2009

Yesterday I faced the situation when in integration test I needed some logic to be mocked and to be executed in particular way. Therefore I asked a question about possibility of combining integration and unit testing approaches. In someone is interested - please review mentioned situation in details. Do not forget that is based on Grails Testing Plugin, so if You are new to it please review some of my previous posts.

I have FileService which has methods for saving/retrieving/deleting files in local file system. Files are distinguished by guid, and full path to the file is generated using storage root property plus mentioned guid. Storage root property is hard coded into the service (I know that is not the best solution but quiet comfortable for me). Described logic is listed below:

class FileService {

// File system's storage root. Hardcoded. String storageRoot = "C:\\"

def retrieveFullPath(String guid) { "${storageRoot}\\${guid}.pdf" }

// Some other methods for // saving/retrieving/deleting files.

}

Also I have other service called Project Service in which File Service is dynamically injected using Spring. It uses its retrieveFullPath method. Let's look more concrete:

Everything looking good and I decided to write simple integration test. But faced with the first question: in my test I need test file to be stored somewhere in the test folder of the application. But when I will use it's guid, file service will retrieve full path according to storage root property and that path will be invalid and exception will be thrown. Therefore I decided to mock mentioned logic in order to retrieve real file which exists under test folder. Let's have a look at the test:

class ProjectServiceTests extends GrailsUnitTestCase {

def projectService

void setUp() {// Do not forget to call super method at first. super.setUp()

// Initialise the service. // There is no dynamic injection. projectService = new ProjectService() }

Monday, February 9, 2009

Recently I wanted to create one-to-one relationship (1 to 0..1) not pure 1 to 1. But unfortunately faced with the problem. Let's review it in details (entity A can have association with zero or only one entity B):

class A { B b

static constraints = { b(nullable: true) }

}

class B { A a

static belongsTo = [A]}

Grails generated the database schema in such way: table A has column b_id (as it has to be), but it cannot be nullable. As You can see for 1 to 0..1 relationship this is a wrong behavior. I posted question on Nabble forums (as I recommended to everyone:) ) and received answer that mentioned problem will be fixed in Grails 1.1. For more details visit appropriate forum post.

Sunday, February 8, 2009

In previous post we got acquainted with Grails Testing Plugin. In this post we will look closer how to write unit test for domain class, especially how to easily test its constraints. As far as I mentioned Testing Plugin includes a lot of mock*() methods for testing domain entities, controllers, tag libs, etc. One of such methods is mockForConstraintsTests() method which is very useful to check whether the constraints are behaving as you expect them to.Suppose we have a simple domain class like so:

Using errors property we can access all the properties and methods we should normally expect. We simply specify the name of the field we are interested in and the map/property access will return the name of the constraint that was violated. Testing Plugin makes testing easy.

The core of the testing plugin is the grails.test.GrailsUnitTestCase class. So each test should extend this class instead of groovys.util.GroovyTestCase.

Special mock*() methods. Using these methods ensures that any changes you make to the given classes do not leak into other tests. It also includes special mock*() methods for mocking domain objects, controllers, for testing constraints, tag libs, etc.

shouldFail(DocumentNotFoundException) { // Method will fail as there are // no test instances to be retrieved. documentService.retrieveDocumentByIdAndOwner( 1L, new User()) } }

}

As You can see Testing Plugin makes unit testing quiet easy. In this post we covered only basic features, if someone will be interested we will look closer into other special features. I recommend to use mentioned plugin instead of using ExpandoMetaClass and Groovy Mocks.

Saturday, February 7, 2009

In part I we got acquainted with unit testing of services based on ExpandoMetaClass approach. In this part we will look on a method based on Groovy Mocks. Groovy has excellent built-in support for a range of mocking alternatives. Let's rewrite test from the previous post in order to use Groovy Mocks.

class DocumentServiceTests extends GroovyTestCase {

def documentService

void setUp() { // Initialize the service class, // there is no dynamic injection. documentService = new DocumentService() }

// Start using the Mock. documentMocker.use {// Document will not be found. // Exception will be thrown. shouldFail(DocumentNotFoundException) { documentService.retrieveDocumentByIdAndOwner( 1L, new User()) } } }

}

Groovy Mocks have a lot of powerful features, especially You can mock few calls of service method, You can mock not only a tested service but also an injected service, etc. For more detailed information check resources listed below:

Now I want to mention one nuance more. In my query I suppose that result type would be a numeric cause versionNumber property is Long type. But result type of using executeQuery method is alwaysjava.util.ArrayList. So even if You try to retrieve maximal value of some field, or count of some records the result type will always be ArrayList. Pay attention to that fact.

As far as You know executeQuery method allows the execution of HQL queries against a domain class. I never tried it before cause used dynamic finders instead. But when I first tried to execute simple HQL query:

That was quiet surprised for me cause DocumentRevision domain class is mapped and I could perform all CRUD operations with it.

Reason for that exception was there is one somewhat frustrating difference between GORM and Hibernate default behaviors. By default in Hibernate the short class name is used and as long as the domain short class name is unique then this is fine. So in my case I should include DocumentRevision with whole package name:

Many times I faced the situation when Grails application has been screwed and comes up with mysterious error messages. Particularly Grails can create columns in database for the fields that were removed from the domain entity long time ago, services perform logic that also was removed long tome ago, etc. In that case try to execute command:

grails clean

If its still not working properly after that the last option is to clean IntelliJ IDEA cache.

Lets create simple unit test for listed service using ExpandoMetaClass approach. As far as You remember during unit tests Grailsdoes not inject any of the dynamic methods present during integration tests and at runtime. So we have to mock them in our tests.

class DocumentServiceTests extends GroovyTestCase {

def documentService

void setUp() { // We have to initialize service class, // there is no dependency injection. documentService = new DocumentService() }

As You can see using ExpandoMetaClass is quiet easy. But be aware of using such approach cause some nuances are present:

Not all dynamic methods can be mocked using metaClass property.

Mocks using ExpandoMetaClass are created for whole tests (including integration tests). So if You mock some method for particular class in some unit test it will affect execution of mentioned method for particular class in other tests, so result can be unpredictable.

Unit testing - testing individual methods or blocks of code without considering for surrounding infrastructure. You have to mock these methods or blocks using something like Groovy Mock or ExpandoMetaClass. Alternatively, you could using the Testing plugin. I will show all 3 approaches in future posts.

Integration testing - you have full access to the Grails environment within the test. Grails will use a database (HSQLDB, MySQL or another found in Grails configuration) for integration tests and clear out all the data from the database in between each test.

I prefer IntelliJ IDEA as my Integrated Development Environment (IDE). Currect IDEA version is 8.0.*.After You've created Your Grails project using

grails create-app application_name

please follow few simple steps to import newly created project to IntelliJ IDEA:

Check that file application_name/.project is created. This is the Eclipse project file generated by grails create-app command during the initial project creation. IntelliJ IDEA is capable of opening such files and transforming them into IntelliJ IDEA project files.

Next you need to tell IntelliJ IDEA to enable Grails support. It may be achieved by registering Grails facet for the project. Intellij IDEA may detect the facet itself and ask to register it. In case it will not, you have to do it manually.

In order to manually register Grails facet open the context menu for your module item in project explorer and click on Module Settings. On the Project Structure window click + button and choose Grails facet. Then just apply the settings and close the window. Module icon will be updated with Grails facet icon - this will tell you that project module is Grails-ready.

I'm Java developer who moved to Groovy/Grails recently.In my blog I will post common simple issues and their solution concerning using Groovy and Grails. I hope that someone will find my posts useful and save time solving common problems.

About Me

I am not only creative and decent person but also a software design engineer working professionally for more than 8 years in the area of distributed web application development. My core competency lies in standard and enterprise Java technologies. Consumers I have worked with include both startups and proven industry representatives.
Now I'm moving to Groovy/Grails and hope to share some experience with others.