background preloader

Grails

Facebook Twitter

Spring IO '15 - Developing microservices, Spring Boot or Grails? An Example of Analysis Patterns: Observation | The Solid Snake. Querying by Association Redux. A couple of months back I posted about the problems with criteria queries where you want results with a collection property that contains some value. Last night I was reading through my new copy of Glen Smith and Peter Ledbrook's Grails In Action and my eye was caught by a particular example where they use aliases in a criteria query. Sure enough a quick test this morning confirms that this is the solution to the problem.

To recap. If I have these domain classes: and I want to query for all the Ships containing a particular Pirate I would probably try to do this: def ships = Ship.withCriteria { crew { eq("name", "Blackbeard") }} Unfortunately, while I end up with the correct Ship instances, each of their crew collections only contains the item(s) that matched the criteria regardless of any others that may actually exist. Using an alias we can do this type of query without resorting to HQL: def ships = Ship.withCriteria { createAlias("crew", "c") eq("c.name", "Blackbeard")}

Groovy date: build list of all Fridays in 2011. JN0545-Dates. We use class Date for simple date processing: def today= new Date() println today def tomorrow= today + 1, dayAfter= today + 2, yesterday= today - 1, dayBefore= today - 2 println "\n$dayBefore\n$yesterday\n$today\n$tomorrow\n$dayAfter\n"assert today + 7 == today.plus(7) && today - 15 == today.minus(15) def d= today.clone() d++; assert d == tomorrow d= d.next(); assert d == dayAfter d--; assert d == tomorrow d= d.previous(); assert d == today assert tomorrow.after(today) assert yesterday.before(today) assert tomorrow.compareTo(today) > 0assert tomorrow.compareTo(dayAfter) < 0assert dayBefore.compareTo(dayBefore) == 0 def n= today.time println n today.time = 0 println today def sometimeAgo= new Date(0) assert sometimeAgo == today Other date and time processing can be done using the GregorianCalendar class: From Groovy 1.5.7 / 1.6.x, you may use Date.format() directly.

Refer to GROOVY-3066 for details. Alternatively, Dates and times can be formatted easily with String.format(). Durations. The Grails Framework 2.1.0. // simple query Account.executeQuery("select distinct a.number from Account a") // using with list of parameters Account.executeQuery("select distinct a.number from Account a " + "where a.branch = ? And a.created > ? ", ['London', lastMonth]) // using with a single parameter and pagination params Account.executeQuery("select distinct a.number from Account a " + "where a.branch = ?

", ['London'], [max: 10, offset: 5]) // using with Map of named parameters Account.executeQuery("select distinct a.number from Account a " + "where a.branch = :branch", [branch: 'London']) // using with Map of named parameters and pagination params Account.executeQuery("select distinct a.number from Account a " + "where a.branch = :branch", [branch: 'London', max: 10, offset: 5]) // same as previous Account.executeQuery("select distinct a.number from Account a " + "where a.branch = :branch", [branch: 'London'], [max: 10, offset: 5])

Tablas Profesionales con JQGrid | Jose Luis Monteagudo. Puedes ver la demo de las tablas en la siguiente dirección: Puedes descargarte el código fuente en la siguiente dirección: jqgrid En muchas de las aplicaciones web que desarrollamos tenemos la necesidad de mostrar la información en forma de tabla. Existe un plugin desarrollado con jQuery que podemos utilizar en nuestra aplicación para este propósito, independientemente del lenguaje de programación que utilicemos en nuestro servidor. El pugin en cuestión se llama jqGrid, y lo vamos a utilizar en combinación con Grails, como ya viene siendo habitual. Una característica importante de jqGrid que cabe destacar es que no sólo permite mostrar información, sino que permite agregar registros nuevos a la base de datos, consultarlos, actualizarlos y borrarlos. Quiero comentar que hoy en día ya existe un plugin para Grails que permite la utilización de jqGrid de forma sencilla.

Por otra parte tendríamos que agregar los siguientes ficheros JavaScript: Grails Tutorial - Part 3. In part one we created the domain layer and generated the controllers. In part two we changed our layout, css, added jquery and jquery-ui, theme switcher and changed the homepage. In this post I'll cover changing the generated list page. We will add the jqgrid component and modify the Controllers to return json for our ajax requests. Why the jqGrid component? I've chosen the jqGrid component because of the features.

Changing the list.gsp page We'll start with something that has no relationships. </head> <body> <div class="body"> <g:if test="${flash.message}"> <div id="message" class="message ui-widget-header ui-corner-all">${flash.message}</div> </g:if> <div id="gridWrapper" class="ui-widget-header ui-corner-all" style="overflow: auto;"> <h3 class="ui-widget-header ui-corner-all" style="text-align: center;">${entityName}s</h3> <! All we have done here is create some global javascript variables to hold the URL values for our controller actions. Import grails.converters.JSON def gridService. Grails with JqGrid inline edit with List()

JQGrid. Grails, jQuery & the jQuery Grid - Part Four. Grails one-to-many dynamic forms – train of thought. After searching around trying to find a good way to implement one-to-many dynamic forms in Grails, I have finally come across this post which does a very good job at explaining the details. What I was basically looking for is a clean way to implement saving my domain objects in the backend, rather than the hacked way I did by hand picking request parameters and manually setting up my domain objects (I’m still fairly new to Grails), and the official docs fail to shed the light on the subtle details I found in this post, which is why I decided to post my own version of the one-to-many dynamic forms but with a little bit more complex domain objects to illustrate the use of enums which also I found is a bit of a gray area in the docs (or at least maybe for me).

Make sure you head over and read the original post, as I will not go through all the details already mentioned over there. This example was developed using Grails version 1.3.3 Our views are now ready for prime time. Update contact. Blog Archive » one-to-many relationships in Grails forms. Here’s a scenario we see fairly often in our Grails applications. Parent object has a collection of Child objectsWe want the Parent’s create and edit GSPs to allow us to add/remove/update associated Child objectsThe controller should correctly persist changes to the collection of Child objects, including maintaining Child object ids so any other objects referencing them don’t get screwed up I found a really nice solution that avoids adding a lot of code to the controller to sift out added/changed/deleted collection members.

The original page seems to have disappeared, so here are copies from archive.org (easier to read) and Google cache (PDF). I was disappointed that the original page is gone, and I found some small errors in the sample code, so I thought it would be nice to document here. Here’s a sample project I created to go through this. Source code: one-many.tar.gz The original example used Quest objects that can hold many Task objects. First, create the Author class. 04.class Author { Mastering Grails: Authentication and authorization. In this article, I continue building a "tiny little blog" named Blogito. I stubbed out Users in the previous article ("Rewiring Grails with custom URIs and codecs") because the name field was a integral part of the URI. Now it's time to implement the User subsystem fully. You'll learn how to enable logins, limit activity based on whether or not the User is logged in, and even add in some authorization based on the User's role.

To start, Users need a way to log in so that they can post new entries. Authentication Authentication is probably a good idea for a blog server that supports multiple users. Listing 1 shows the grails-app/domain/User.groovy file that you created last time: Listing 1. The login and password fields are in place. Listing 2. The empty login closure simply means that visiting in your browser will render the grails-app/views/user/login.gsp file. Now it's time to create login.gsp. Listing 3. login.gsp Figure 1. Figure 2. Back to top. Grails Example. An Army of Solipsists » Blog Archive » Accessing the GrailsApplication and ApplicationContext from domain classes without holders. The various holder classes in Grails (ApplicationHolder, ConfigurationHolder, etc.) are now deprecated and the plan was to remove them at some point since static variables cause problems.

One example is deploying multiple Grails applications with the --nojars option, using jar files in the server’s shared classpath. If a class with a static field is loaded by the shared classloader, its value is shared by all callers. Kaboom. We’re working on a fix but it doesn’t look like it’ll be ready for 2.0 final, so it’s still best to avoid their use. In practice this isn’t really that much of a problem since you can use dependency injection to inject the GrailsApplication into any artifact (controllers, services, Quartz jobs, etc.) with def grailsApplication. From there you can get the configuration (grailsApplication.config) and the ApplicationContext (grailsApplication.mainContext) . , and it’s still a good option. But it turns out this is all possible in 2.0 without changes.

Grails Standalone Plugin @ GitHub. Generating PDFs for Fun and Profit with Flying Saucer and iText. PDFs are one of the most common and most significant document formats on the internet. Typically, developers must use expensive tools from Adobe or cumbersome APIs to generate PDFs. In this article, you will learn how to programmatically generate PDFs easily with plain XHTML and CSS using two open source Java libraries: Flying Saucer and iText. The Problem with PDFs PDFs are a great technology. There is one big problem with PDFs, however: the spec is complicated and the APIs for generating PDFs tend to be cumbersome, requiring a lot of low-level coding of paragraphs and headers. The way to make good looking PDFs is to let the programmers do what they are good at: writing code that manipulates data, and let the graphic designers do what they are good at: making attractive graphic designs.

An Introduction to Flying Saucer and iText iText is a PDF generation library created by Bruno Lowagie and Paulo Soares, licensed under the LGPL and the Mozilla Public License. Generating a Simple PDF. Craig Burke Blog : Creating Google Calendar in Grails – Part 1: The Model. Over this series of posts I’m going to look at recreating some of the basic functionality of Google Calendar including the capability of adding recurring events within Grails. We’ll start by looking at the model. For a basic event, our model is very simple. We just need a title, a start and end time, a location and a description. Here’s what we’re starting with: class Event { String title String location String description Date startTime Date endTime Things get a lot more complicated when we start talking about repeating events though. Now think about the case where we want this event to happen every Monday without a specific end date.

So lets take a look at the Google Calendar options for a repeating event to figure out what additional properties we might need: Ok, so we’re going to need to allow for different recurrence types (weekly, daily, monthly, or yearly). Boolean isRecurring = false EventRecurType recurType Integer recurInterval = 1 Date recurUntil Integer recurCount DAILY( 'Daily' ), save() 2 Getting Started 2.1.0. (Quick Reference) Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith Version: 2.3.7 2.1 Installation Requirements Before installing Grails you will need as a minimum a Java Development Kit (JDK) installed version 1.6 or above.

Download the appropriate JDK for your operating system, run the installer, and then set up an environment variable called JAVA_HOME pointing to the location of this installation. These will show you how to install Grails too, not just the JDK. A JDK is required in your Grails development environment. On some platforms (for example OS X) the Java installation is automatically detected. Export JAVA_HOME=/Library/Java/Home export PATH="$PATH:$JAVA_HOME/bin" if you're using bash or another variant of the Bourne Shell. 2.2 Downloading and Installing The first step to getting up and running with Grails is to install the distribution. Grails version: 2.0.0 2.3 Creating an Application Run create-app to create an application: Job done. Eclipse. Introduction to Griffon. The Grails Framework 2.1.0. (Quick Reference) Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari Version: 2.3.8 Java web development as it stands today is dramatically more complicated than it needs to be.

Most modern web frameworks in the Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles. Dynamic frameworks like Rails, Django and TurboGears helped pave the way to a more modern way of thinking about web applications. Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and its associated plugins. All of these are made easy to use through the power of the Groovy language and the extensive use of Domain Specific Languages (DSLs) This documentation will take you through getting started with Grails and building web applications with the Grails framework. 1.1 What's new in Grails 2.3?

Improved Dependency Management Data Binder Forked Execution Async support. Grails in Production. Thursday, February 9th, 2012 There are a few gotcha’s when deploying a Grails war in a container like Tomcat. Most commonly are issues with stacktrace.log. Second most common are issues with file based db’s. Setting stacktrace.log Open up grails-app/conf/Config.groovy. By default Grails tries to create a stacktrace.log file in the directory it is executed in, which is won’t have permission to do unless you’ve overridden the permissions (not recommended). Setting up H2 Grails now uses H2 for it’s in-memory and default database. Open up grails-app/conf/DataSource.groovy. Url = "jdbc:h2:file:/usr/local/grailsdb;MVCC=TRUE" You can change the path or name to whatever you like, point is it isn’t left as the default which means it will try to create it in a directory it won’t have permission to use.

Contribute a Tag. This page contains user submissions of custom tags that may or may not be included in the Grails core. For general information on using and creating custom tags see Add your tag below and please update this list, too: dateFormat Tag Description Allows formatting of data objects. Example The Code!

Def dateFormat = { attrs -> out << new java.text.SimpleDateFormat(attrs.format) .format(attrs.value) } esc Tag Escapes HTML entities within its body to ensure no cross-site scripting (XSS) attacks can work. <g:esc>${someobj.name}</g:esc> /** * Escape HTML entities within the body. */ def esc = { attrs, body -> def text = '' if(body instanceof Closure) { text = TagLibUtil.outToString(body, attrs) } else if(body instanceof String) { text = body } else if(attrs instanceof String) { text = attrs } out << escapeEntities(text); } format The core formatDate tag now allows formats specified in the message bundle (since 1.0-RC2). test.gsp messages.properties The Code!

jQuery Tags. Mastering Grails: Grails services and Google Maps. IntelliGrape/Grails-Google-Map-Plugin. Domain Patterns in Enterprise Projects | Blog. New Grails Spring Security Core Plugin - Eric on JavaEric on Java. Simplified Spring Security with Grails.