Archive: July 2016

Expandable list component for AngularJS (1.5)

Posted on by  
Richard Rijnberk

For several of my projects I required a list where input items could be dynamically added and removed. Because i saw uses for this over and over i created a component which i'm sharing with you here. The component ended up like the code below. Where i used a template generation function in order to create the ul and li elements. I'm using the angular.element function to create nodes as a method of preference.

function mpExpandableListController(){
    var vm = this;

    vm.add = add;
    vm.manipulatable = true;
    vm.remove = remove;

    // If items was not declared, create new array.
    if(!vm.items) {
        vm.items = [];
    }

    // If the items array is empty, create first item.
    if(vm.items.length === 0) {
        add();
    }

    /**
     * Add an item to the item list.
     */
    function add(){
        vm.items.push({});
        setManipulatable();
    }

    /**
     * Remove an item from the item list.
     * @param item The item to remove
     */
    function remove(item){
        vm.items.splice(vm.items.indexOf(item), 1);
        setManipulatable();
    }

    /**
     * Set the flag which designates that the list may be manipulated.
     */
    function setManipulatable() {
        vm.manipulatable = vm.items.length > 1;
    }
}

/**
 *
 * @param $element The element as declared in the HTML
 * @param $attrs The attributes for said element
 * @returns {string} A template for this component.
 */
function template($element, $attrs){
    var container = angular.element('<ul>'),
        item = angular.element('<li ng-repeat="item in list.items">'),
        footer = angular.element('<li>');

    container.addClass($attrs.universalClass);
    item.addClass($attrs.itemClass);
    footer.addClass($attrs.footerClass);

    item.html($element.find('item').html());
    footer.html($element.find('footer').html());

    container.append(item);
    container.append(footer);

    return container[0].outerHTML;
}

var mpExpandableList = {
    bindings: {
        footerClass: '@',
        itemClass: '@',
        items: '=',
        universalClass: '@'
    },
    controller: mpExpandableListController,
    controllerAs: 'list',
    template: template
};

angular
    .module('my.project')
    .component('mpExpandableList', mpExpandableList);

Continue reading →

Ratpacked: Create a Partial Response

Posted on by  
Hubert Klein Ikkink

Suppose we want to support partial JSON responses in our Ratpack application. The user must send a request parameter with a list of fields that need to be part of the response. In our code we must use the value of the request parameter and output only the given properties of an object. We implement this logic using a custom renderer in Ratpack. Inside the renderer we can get access to the request parameters of the original request.

In our example Ratpack application we have a Course class, which is a simple class withs some properties:

Continue reading →

Grails Goodness: Pass JSON Configuration Via Command Line

Posted on by  
Hubert Klein Ikkink

We can use the environment variable SPRING_APPLICATION_JSON with a JSON value as configuration source for our Grails 3 application. The JSON value is parsed and merged with the configuration. Instead of the environment variable we can also use the Java system property spring.application.json.

Let's create a simple controller that reads the configuration property app.message:

Continue reading →

Ratpacked: Using Groovy Configuration Scripts As Configuration Source

Posted on by  
Hubert Klein Ikkink

Ratpack has a lot of options to add configuration data to our application. We can use for example YAML and JSON files, properties, environment variables and Java system properties. Groovy has the ConfigSlurper class to parse Groovy script with configuration data. It even supports an environments block to set configuration value for a specific environment. If we want to support Groovy scripts as configuration definition we write a class that implements the ratpack.config.ConfigSource interface.

We create a new class ConfigSlurperConfigSource and implement the ConfigSource interface. We must implement the loadConfigData method in which we read the Groovy configuration and transform it to a ObjectNode so Ratpack can use it:

Continue reading →

Spicy Spring: Using Groovy Configuration As PropertySource

Posted on by  
Hubert Klein Ikkink

We have many ways to provide configuration properties to a Spring (Boot) application. We can add our own custom configuration properties format. For example we can use Groovy's ConfigObject object to set configuration properties. We need to read a configuration file using ConfigSlurper and make it available as a property source for Spring. We need to implement two classes and add configuration file to support a Groovy configuration file in a Spring application.

First we need to write a class that extends the PropertySource in the package org.springframework.core.env. This class has methods to get property values based on a given key. There are already some subclasses for specific property sources. There is for example also a MapPropertySource class. We will extend that class for our implementation, because we can pass our flattened ConfigObject and rely on all existing functionality of the MapPropertySource class:

Continue reading →

Ratpacked: Handling Exceptions When Reading Configuration Sources

Posted on by  
Hubert Klein Ikkink

To define configuration sources for our Ratpack application we have several options. We can set default properties, look at environment variables or Java system properties, load JSON or YAML formatted configuration files or implement our own configuration source. When something goes wrong using one of these methods we want to be able to handle that situation. For example if an optional configuration file is not found, we want to inform the user, but the application must still start. The default exception handling will throw the exception and the application is stopped. We want to customise this so we have more flexibility on how to handle exceptions.

We provide the configuration source in the serverConfig configuration block of our Ratpack application. We must add the onError method and provide an error handler implementation before we load any configuration source. This error handler will be passed to each configuration source and is execute when an exception occurs when the configuration source is invoked. The error handler implements the Action interface with the type Throwable. In our implementation we can for example check for the type of Throwable and show a correct status message to the user.

Continue reading →

Groovy Goodness: Customise Log AST Annotations

Posted on by  
Hubert Klein Ikkink

Adding logging support to a class in Groovy is easy. We can choose to add SLF4J, Log4j, Log4j2, Apache Commons or Java Util Logging to our class. The default implementation of the Abstract Syntax Tree (AST) transformation is to add a log field of the correct type. As category name the complete class name (including the package) is used. We can change the name of the field with the value attribute. To alter the category name we use the attribute category.

In the following example snippet we change the log field name to LOGGER and set a custom category name:

Continue reading →

Groovy Goodness: Represent Map As String

Posted on by  
Hubert Klein Ikkink

Groovy adds to Map objects the toMapString method. With this method we can have a String representation of our Map. We can specify an argument for the maximum width of the generated String. Groovy will make sure at least the key/value pairs are added as a pair, before adding three dots (...) if the maximum size is exceeded.

def course = [
    name: 'Groovy 101',
    teacher: 'mrhaki',
    location: 'The Netherlands']

assert course.toMapString(15) == '[name:Groovy 101, ...]'
assert course.toMapString(25) == '[name:Groovy 101, teacher:mrhaki, ...]'

Continue reading →

shadow-left