Archive: 2013

Grails Goodness: Customize Resource Mappings

Posted on by  
Hubert Klein Ikkink

Since Grails 2.3 it is very easy to define RESTful URL mappings for a controller. We can use the resources and resource attribute and use a controller name as the value. Grails will then automatically create a couple of URL mappings. Suppose we use the following mapping in grails-app/conf/UrlMappings.groovy: "/api/users"(resources: 'user'), then the following mappings are automatically created:

"/api/users/create"(controller: 'user', action: 'create', method: 'GET')
"/api/users/(*)/edit"(controller: 'user', action: 'edit', method: 'GET')
"/api/users(.(*))?"(controller: 'user', action: 'save', method: 'POST')
"/api/users(.(*))?"(controller: 'user', action: 'index', method: 'GET')
"/api/users/(*)(.(*))?"(controller: 'user', action: 'delete', method: 'DELETE')
"/api/users/(*)(.(*))?"(controller: 'user', action: 'update', method: 'PUT')
"/api/users/(*)(.(*))?"(controller: 'user', action: 'show', method: 'GET')

Continue reading →

Grails Goodness: Namespace Support for Controllers

Posted on by  
Hubert Klein Ikkink

In a Grails application we can organize our controllers into packages, but if we use the same name for multiple controllers, placed in different packages, then Grails cannot resolve the correct controller name. Grails ignores the package name when finding a controller by name. But with namespace support since Grails 2.3 we can have controllers with the same name, but we can use a namespace property to distinguish between the different controllers.

We can add a new static property to a controller class with the name namespace. The value of this property defines the namespace. We can then write new URL mappings in the grails-app/conf/UrlMappings.groovy file and use the namespace value as a mapping attribute.

Continue reading →

Grails Goodness: Add Extra Valid Domains and Authorities for URL Validation

Posted on by  
Hubert Klein Ikkink

Grails has a built-in URL constraint to check if a String value is a valid URL. We can use the constraint in our code to check for example that the user input http://www.mrhaki.com is valid and http://www.invalid.url is not. The basic URL validation checks the value according to standards RFC1034 and RFC1123. If want to allow other domain names, for example server names found in our internal network, we can add an extra parameter to the URL constraint. We can pass a regular expressions or a list of regular expressions for patterns that we want to allow to pass the validation. This way we can add IP addresses, domain names and even port values that are all considered valid. The regular expression is matched against the so called authority part of the URL. The authority part is a hostname, colon (:) and port number.

In the following sample code we define a simple command object with a String property address. In the constraints block we use the URL constraint. We assign a list of regular expression String values to the URL constraint. Each of the given expressions are valid authorities, we want the validation to be valid. Instead of a list of values we can also assign one value if needed. If we don't want to add extra valid authorities we can simple use the parameter true.

Continue reading →

Grails Goodness: Setting Property Values through Configuration

Posted on by  
Hubert Klein Ikkink

In Grails we can define properties for services, controller, taglibs, Spring components and other components in the Spring application context through configuration. This is called property overriding in Spring terminology. This feature is very useful to define or override property values on components in the application context. We can define the property values in a beans{} block in Config.groovy. We can also load external configuration files, like property files and define property values in those.

With property overriding we don't have to look for property values via an injected GrailsApplication object and the config property of GrailsApplication. The code using the property value is now much cleaner and easier to test.

Continue reading →

Creating a superelipse with canvas

Posted on by  
Richard Rijnberk

Today a colleague asked a group of front-end developers how he would create a superelipse. His current solution was to use a svg mask to remove all non essential visual information. This solution however had a setback, because we used a mask to shield the edges we had no real transparency. Thus we were unable to effectively use it on more graphic backgrounds. I however thought it should be able to use canvas to provide the solution. The code below is my solution. 

<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
    var canvas = document.getElementById('myCanvas');
    var image = canvas.getContext('2d');

    var width = canvas.width;
    var height= canvas.height;
    var img = document.createElement('IMG');

    var shape = {
        beginPath : function(node) {
            image.beginPath();
            image.moveTo(
                    node.x,
                    node.y
            );
        },
        createCurve : function(curve, node) {
            image.quadraticCurveTo(
                curve.x,
                curve.y,
                node.x,
                node.y
            );

        },
        node : {
            top_left : {
                x : ((width/100)*20),
                y : ((height/100)*5)
            },
            top_right : {
                x : ((width/100)*80),
                y : ((height/100)*5)
            },
            right_top :{
                    x : ((width/100)*95),
                    y : ((height/100)*20)
            },
            right_bottom :{
                x : ((width/100)*95),
                y : ((height/100)*80)
            },
            bottom_right : {
                x : ((width/100)*80),
                y : ((height/100)*95)
            },
            bottom_left : {
                x : ((width/100)*20),
                y : ((height/100)*95)
            },
            left_bottom : {
                x : ((width/100)*5),
                y : ((height/100)*80)
            },
            left_top : {
                x : ((width/100)*5),
                y : ((height/100)*20)
            }
        },
        curve : {
            top : {
                x : ((width/100)*50),
                y : 0
            },
            top_right : {
                x : ((width/100)*92.5),
                y : ((height/100)* 7.5)
            },
            right : {
                x : width,
                y : ((height/100)* 50)
            },
            bottom_right : {
                x : ((width/100)*92.5),
                y : ((height/100)*92.5)
            },
            bottom : {
                x : ((width/100)*50),
                y : height
            },
            bottom_left : {
                x : ((width/100)*7.5),
                y : ((height/100)*92.5)
            },
            left : {
                x : 0,
                y : ((height/100)*50)
            },
            top_left : {
                x : ((width/100)*7.5),
                y : ((height/100)*7.5)
            }
        }
    }

    img.onload = function() {
        shape.beginPath(shape.node.top_left)

        shape.createCurve(shape.curve.top, shape.node.top_right);
        shape.createCurve(shape.curve.top_right, shape.node.right_top);
        shape.createCurve(shape.curve.right, shape.node.right_bottom);
        shape.createCurve(shape.curve.bottom_right, shape.node.bottom_right);
        shape.createCurve(shape.curve.bottom, shape.node.bottom_left);
        shape.createCurve(shape.curve.bottom_left, shape.node.left_bottom);
        shape.createCurve(shape.curve.left, shape.node.left_top);
        shape.createCurve(shape.curve.top_left, shape.node.top_left);

        image.closePath();
        image.clip();
        image.drawImage(img, 0, 0, width, height);
        image.restore();
    }

    img.src = "http://goo.gl/pC8iIF";

</script>

Continue reading →

Detect Maven Dependency Mediation

Posted on by  
Pim Dorrestijn

As of Maven 2.0.9 a new feature was added to Maven called dependency mediation. Dependency mediation is the technique used by Maven to resolve your project dependencies in the specific case when a dependency occurs multiple times in your dependency tree. Usually this occurs on transitive dependencies linked through the dependencies of your project. In these cases mediation will be performed using the nearest win-strategy. In short this strategy means that Maven will use the version declared in the pom.xml that is closest to your project pom.xml. Hence, no in-depth intelligence is used to resolve the dependency conflict. Actually, I can't really think of a conflict resolve strategy that would really solve this problem. Any strategy I can think of has the hazard of linking incompatible dependencies in to your project. Using Maven version ranges can ofcourse resolve compatibility between artifacts, but this also requires you to establish a compatibility matrix of your dependencies. A pretty tedious task if you ask me. Now this whole mediation feature might sound like a very undesirable feature, but it's not! With this feature you can now at least be made aware of any dependency conflicts in your project dependencies. When you build your project using the -X switch, Maven will output all mediations (and a lot more) that have been performed. Now, wouldn't it be cool if there was a maven-plugin to detect mediation? JDriven took the liberty of extending Apache's dependency plugin with such a feature and share it with you. The goal used to detect mediation is mvn dependency:mediation. Additionally two interesting parameters can be added: 1) -DdisallowMediation=false 2) -DinspectArtifactId={some artifactId} As the name already implies, disallowMediation determines whether or not mediation is allowed. When allowed, the plugin will only warn about mediation being performed on dependencies. Very usefull when combined with for instance Jenkins' ${IS_M2RELEASEBUILD} variable to disallow mediation for release builds, yet allowing it for snapshot builds. The inspectArtifactId parameter is much like goal dependency:tree -Dverbose=true, it will check mediation and print dependency information regarding the artifact having id {some artifactId}. In your pom.xml your can add additional configuration to filter which dependencies must be checked on mediation:

com.jdriven.maven.plugins
maven-dependency-plugin
2.8.1
 com.jdriven:\* 

Continue reading →

Spocklight: Using Mock Method Arguments in Response

Posted on by  
Hubert Klein Ikkink

When we mock or stub methods we can use the method arguments passed to the method in the response for the mocked or stubbed method. We must write a closure after the rightShift operator (>>) and the closure arguments will resemble the arguments of the mocked or stubbed method. Alternatively we can use a single non-typed argument in the closure and this will contains the method argument list.

Let's create a specification where we use this feature. In the following sample we use a mock for the AgeService used in the class under test. The method allowedMaxTime() is invoked by the class under test and basically should return the maximum hour of the day a show can be broadcasted. In our specification we use the name of the show to return different values during the test.

Continue reading →

Understanding and fixing AngularJS directive rendering and parsing

Posted on by  
Emil van Galen

NOTE: This blog post is originally written for AngularJS 1.2.x; in 1.3.x the "input not showing invalid model values" has been fixed.
Although 1.3.x still has the "inconsistencies in how AngularJS parses data entry" the solution from this blog post isn't working for 1.3.x but I will try to find a fix for this within the next few weeks.

A while ago I noticed that AngularJS doesn't show invalid model values bound to an <input/> There is also an open bug report about this: issue #1412 - input not showing invalid model values The bug can be easily illustrated through the following example:

Continue reading →

Grails Goodness: Unit Testing Render Templates from Controller

Posted on by  
Hubert Klein Ikkink

In a previous blog post we learned how we can unit test a template or view independently. But what if we want to unit test a controller that uses the render() method and a template with the template key instead of a view? Normally the view and model are stored in the modelAndView property of the response. We can even use shortcuts in our test code like view and model to check the result. But a render() method invocation with a template key will simply execute the template (also in test code) and the result is put in the response. With the text property of the response we can check the result.

In the following sample controller we use the header template and pass a username model property to render output.

Continue reading →

Grails Goodness: Render Binary Output with the File Attribute

Posted on by  
Hubert Klein Ikkink

Since Grails 2 we can render binary output with the render() method and the file attribute. The file attribute can be assigned a byte[], File, InputStream or String value. Grails will try to determine the content type for files, but we can also use the contentType attribute to set the content type.

In the following controller we find an image in our application using grailsResourceLocator. Then we use the render() method and the file and contenType attributes to render the image in a browser:

Continue reading →

Grails Goodness: Accessing Resources with Resource and ResourceLocator

Posted on by  
Hubert Klein Ikkink

Grails uses Spring and we can piggyback on the Spring support for resource loading to find for examples files in the classpath of our application. We can use the Spring org.springframework.core.io.Resource or org.springframework.core.io.ResourceLoader interface to find resources in our application.

And since Grails 2.0 we can also use the org.codehaus.groovy.grails.core.io.ResourceLocator interface. In our code we can use the grailsResourceLocator service which implements the ResourceLocator interface. We must inject the grailsResourceLocator service into our code and we use the method findResourceForURI(String) to find a resource. The advantage of the grailsResourceLocator service is that it knows about a Grails application. For example resources in plugins can also be accessed.

Continue reading →

Spocklight: Using the Old Method

Posted on by  
Hubert Klein Ikkink

Spock has some great features to write specifications or tests that are short and compact. One of them is the old() method. The old() method can only be used in a then: block. With this method we get the value a statement had before the when: block is executed.

Let's see this with a simple example. In the following specification we create a StringBuilder with an initial value. In the then: block we use the same initial value for the assertion:

Continue reading →

shadow-left