Android GCM Sender

Esta entrada es una traducción al español de la que publiqué en mi blog, que está en inglés.

Motivación

Imagina que estás desarrollando una aplicación Android que necesita recibir notificaciones push. La aplicación encargada de enviar esos mensajes a GCM está siendo desarrollado por otro equipo, y no sólo no está terminada todavía, sino que además el equipo está en otro departamento de la empresa. No, de hecho está en otra empresa :-) . Quieres estar seguro de que tu aplicación cumple las especificaciones (es decir, reacciona de cierta manera cuando recibe cierta notificación), pero no quieres depender de ese otro equipo (y por supuesto, tampoco quieres desarrollar una aplicación que envíe notificaciones 😀 ):

Solución

Esa necesidad de una aplicación de envío de mensajes configurables a GCM es el segundo artefacto que Adrian Santalla y yo desarrollamos en los dos primeros hacker fridays de OSOCO, al que hemos llamado Android GCM Sender (siendo el primero el plugin de Android GCM para Grails).

Suscribe tus dispositivos usando la URL proporcionada y añade tu identificador de proyecto

Empezó siendo la aplicación de prueba para dicho plugin, pero nos dimos cuenta que sería fácil evolucionarla hasta el punto de ser útil para cualquiera: sólo necesitábamos parametrizar el identificador de proyecto (que puedes obtener creando un proyecto tipo Google API) y crear una acción que permitiese la suscripción de dispositivos Android. Puedes usar Android GCM Sender en la siguiente URL: http://grails-android-gcm-sender.herokuapp.com/.

Uso

El primer paso sería suscribir tus identificadores de dispositivo Android usando la URL http://grails-android-gcm-sender.herokuapp.com/device/subscribe?deviceToken=yourDeviceToken&projectId=yourProjectId. No olvides sustituir substitute yourDeviceToken y yourProjectId con tu identificador de proyecto e identificador de dispositivo Android, y recuerda que esta URL está pensaba para ser invocada con algún tipo de HTTPBuilder dentro de una aplicación Android – opr eso no produce ninguna salida :-). Pero si quieres usarla directamente en tu navegador, también funcionará 😀 .

Compón tu mensaje, envíalo a los dispositivos seleccionados y observa el resultado del envío

Después de eso, escribe tu identificador de proyecto en la página de inicio de Android GCM Sender y dale al botón de actulizar. Verás un formulario que te permite enviar mensajes (simples o compuestos) a uno o varios dispositivos Android. Ten en cuenta que siempre tendrás disponibles dos dispositivos falsos para el caso en que quieras hacer algún tipo de prueba con ellos. Después de rellenar el formulario. puedes darle al botón Send y verás el resultado del envío. Y si tus identificadores de dispositivo y proyecto son válidos, deberías recibir una notificación push con el mensaje que compusiste en la vista anterior 😀 .

Ten en cuenta que para mantener los datos en un volumen pequeño, tus identificadores de dispositivo y proyecto sólo se guardan durante 24 horas – piensa que en realidad es una feature y no un bug 😀 ya que así no te tienes que preocupar de des-suscribir tus dispositivos o similar. De hecho, la base de datos está en memoria, por lo que nosotros no tenemos acceso a ella.

Código fuente

Android GCM sender corre en Heroku, pero su código fuente está disponible en la cuenta Github de OSOCO, por lo que puedes alojarlo tú mismo si quieres. La aplicación ha sido desarrollada usando Grails, y a la UI se le ha añadido un poco de picante con Ajaxify.

Polyglot Programming

Polyglot Programming

How many programming languages do you know?

Most programmers know several languages. We, as web developers, work on a daily basis with Groovy, SQL, Bash Scripting, HTML, CSS, JavaScript…

Learning different languages allows us to solve problems with the most appropriate language and to explore new paths of thinking about computational problems.

Neal Ford coined the term polyglot programming, to refer about this topic.

I think it’s important in this day and age of polyglot programming to understand a variety of different languages, as they are the design tools we use to craft software. Just like regular engineers must understand the physical properties of different materials, we should understand the capabilities, strengths, and weaknesses of different languages. And when to apply them.

Neal Ford

Polyglot JVM and Polyglot Grails

Java has long been known simply as a programming language. Today, when thinking in Java we refer also a robust and mature development platform. Currently, the Java Virtual Machine (JVM) supports over 200 different programming languages.

These days we have been exploring different languages on the JVM: Java, Groovy, Scala, Clojure, JRuby… and how to incorporate them into a Grails project. We shared our experiences with others developers at Spring I/O 2012 and Codemotion 2012.

Hope you enjoy the slides.

Create your own Groovy type conversion

Type conversion the standard way

Type conversion or casting is a programming language method for changing an object’s data type into another.

I’m sure you are familiar with this code that converts a String to an Integer.

def number = (Integer)'1'
def number = '1'.toInteger()
def number = '1' as Integer

If I want to convert the type of my own objects, I need to create a method to achieve this goal. I copy object properties to another object in a generic way; if a property exists on target object, I copy it from the source object.

class User {
    String name
    String city
    Integer age

    def toAdminUser() {
        def adminUser = new AdminUser()
        copyProperties(this, adminUser)
        return adminUser
    }

    def copyProperties(source, target) {
        source.properties.each { key, value ->
            if (target.hasProperty(key) && !(key in ['class', 'metaClass'])) {
                target[key] = value
            }
        }
    }
}

class AdminUser {
    String name
    String city
    Integer age
}

Now I can do something like this:

adminUser = user.toAdminUser() 

Type conversion the fancy way

Great, but I want to use this fancy way to coerce one type to another:

adminUser = user as AdminUser 

Simple, Groovy supports operator overloading and creating your own type conversion is really easy: we can override the asType() method.

class User {
    String name
    String city
    Integer age

    Object asType(Class clazz) {
        if (clazz == AdminUser) {
            def adminUser = new AdminUser()
            copyProperties(this, adminUser)
            return adminUser
        }
        else {
            super.asType(clazz)
        }
    }

    def copyProperties(source, target) {
        source.properties.each { key, value ->
            if (target.hasProperty(key) && !(key in ['class', 'metaClass'])) {
                target[key] = value
            }
        }
    }
}

Asynchronous tests with GPars (Osoco test gallery, part 4)

If you wrote multithreaded code in Groovy/Grails, I’m sure you stumbled upon the GPars library. It simplifies parallel processing – sometimes it’s as easy as wrapping a code fragment with a GPars closure, changing the iteration method (in our example from each to eachParallel) and passing the closure to a GPars pool. The library implementation handles the executor pool creation and adds new methods to collections.

Whenever I deliberately add multithreading, I always separate responsibilities (processing logic and concurrency handling). I wrap the single-threaded class with a new one, handing the parallel execution (creating a pool, managing threads, handling cancellation, etc.):

class MultithreadedProcessorService {
    ProcessorService processorService
    def threadPoolSize = ConfigurationHolder.config.threadPool.size

    void processMultithreaded(batches) {
        GParsPool.withPool(threadPoolSize) {
            batches.eachParallel { batch ->
                processorService.process(batch)
            }
        }
    }
}

class ProcessorService {
    void process(batch) {
        // some processing
    }
}

To test the multithreaded class you can you use Spock interactions. As opposed to Groovy and Grails mocks, they are thread-safe and you won’t get any weird and unstable results:

class MultithreadedProcessorServiceSpec extends UnitSpec {
    private MultithreadedProcessorService multithreadedProcessorService
    // Using Spock mocks because they are thread-safe
    private ProcessorService processorService = Mock(ProcessorService)

    def setup() {
        mockConfig('threadPool.size=2')
        multithreadedProcessorService = new MultithreadedProcessorService(
            processorService: processorService
        )
    }

    def 'processes batches using multiple threads'() {
        given:
        def batches = [[0, 1], [2, 3, 4], [5]]
        def processedBatches = markedAsNotProcessed(batches)

        when:
        multithreadedProcessorService.processMultithreaded(batches)

        then:
        batches.size() * processorService.process({ batch ->
            processedBatches[batch] = true
            batch in batches
        })
        assertAllProcessed(processedBatches)

    }

    private markedAsNotProcessed(batches) {
        batches.inject([:]) { processed, batch ->
            processed[batch] = false
            processed
        }
    }

    private void assertAllProcessed(batches) {
        assert batches*.value == [true] * batches.size()
    }
}

This post series present the best of Osoco tests – tests that were tricky or we are just proud of. You can find a runnable source code for this test and more in the Grails Test Gallery project shared on GitHub.

Grails base persistence specification (Osoco test gallery, part 3)

In our projects we include at least one integration test per domain class. We want to assure us that the GORM mapping is correct and the class is persistable in the target database. The test plan is simple:

  • create a valid persistable sample of the domain object
  • save it
  • clear Hibernate first level cache (i.e. flush and clear current session)
  • retrieve the object once again and compare it with the previously saved object. They must be equal as by equals() but be different object references

We put the steps above in a base abstract specification. In concrete specifications we implement merely the factory method spawning a persistable object instance.

abstract class PersistenceSpec extends IntegrationSpec {
    SessionFactory sessionFactory

    protected abstract createPersistableDomainObject()

    def 'persistable domain object should be able to be saved and retrieved'() {
        given:
        def persistableDomainObject = createPersistableDomainObject()

        when:
        def savedDomainObject = persistableDomainObject.save()

        then:
        savedDomainObject.id != null

        when:
        clearFirstLevelCache()

        def retrievedDomainObject = persistableDomainObject.class.get(savedDomainObject.id)

        then:
        savedDomainObject == retrievedDomainObject
        !savedDomainObject.is(retrievedDomainObject)
    }

    private clearFirstLevelCache() {
        sessionFactory.currentSession.flush()
        sessionFactory.currentSession.clear()
    }
}

This post series present the best of Osoco tests – tests that were tricky or we are just proud of. You can find a runnable source code for this test and more in the Grails Test Gallery project shared on GitHub.

Grails equals and hashCode testing (Osoco test gallery, part 2)

If you work with GORM and your objects are held in collections, you should implement equals and hashCode methods. As everything, they should be thouroughly tested if they obey equals-hashCode contract. At Osoco we created a equals-hashcode-test Grails plugin that provides a base Spock specification for that. In your equals and hashCode tests you simply have to extend the EqualsHashCodeSpec and provide at least two methods:

  • a factory method createDomainObjectToCompare that will create a fresh object for the comparison
  • a map of modified properties included in equals and hashCode
  • optionally a map of modified properties ignored in both methods

Additionally in case of inheritance, we check whether the equals method complies with the symmetry rule. We do it in an extra feature method added to the spec:

def 'equals relation must be symmetric with inheritance'() {
    given:
    def content = new Content()

    and:
    def book = new Book()

    expect:
    (content == book) == (book == content)
}

You may say, in Grails 2.0 and Groovy 1.8 there are @Equals and @HashCode AST transformations and you don’t need to write tests of them. I agree to some point. I think you can trust Groovy developers and you don’t have to test the methods for reflexivity, symmetry, transivity, consistency, and ‘non-nullity’. Anyway, you have to test the annotation configuration if it includes the properties that actually account for the logical equality between objects.

In the future releases of the plugin we will surely simplify the base specification and remove some checks but we will surely continue testing both methods (with our plugin it’s dirt-cheap!)


This post series present the best of Osoco tests – tests that were tricky or we are just proud of. You can find a runnable source code for this test and more in the Grails Test Gallery project shared on GitHub.

Functional Programming with Groovy

The diversity of languages and programming paradigms allow us to solve existing problems by thinking solutions from very different approaches.

But why a Groovy developer should learn functional programming?

As I learned about functional programming, I found good ideas but I also found that it brought new clarity to my thinking about the design of class and methods. It also allowed me to write more concise code and how to make it better for reuse.

A few weeks ago, I spoke about functional programming with Groovy at Greach 2011. I presented basic concepts of functional programming paradigm and then focus on how to apply them to improve the code that we write with Groovy.


Grails as daemon in Jenkins

Sometimes you need to run Grails embedded Tomcat container in background as a part of your build in Jenkins/Hudson. Launching a grails run-app & as Execute shell build step will result in a warning from Jenkins: Process leaked file descriptors.

The problem is described in the Jenkins wiki with some possible solutions. I chose the daemonize tool. As far as I know it is not available in any Debian repository, so I had to build it myself. It takes less than 3 minutes; just follow the instructions from the daemonize website.

I wrapped the grails run-app with daemonize in a handy script: run-app-as-daemon.sh that you can download from the Osoco’s GitHub repository.

The script starts the embedded Grails server with HTTP or HTTPS connector and then checks if the server is up and running by polling a configured URL. After e.g. some functional tests, it kills the server process by its PID.

If you want to apply the script in your build, you have to customize some variables, listed (and documented) in the script header. Usage is very simple:

run-app-as-daemon.sh start|start-https|stop|force-stop

Sample Jenkins build configuration:

Build steps:

your-app-dir/run-app-as-daemon.sh force-stop
your-app-dir/run-app-as-daemon.sh start

Post build tasks:

your-app-dir/run-app-as-daemon.sh stop