Coding

Spring Tip: Check for existence of Bean during startup

Posted on by  
Willem Cheizoo

Sometimes we are working on an application where we have no control over specific Spring bean implementations. Nevertheless we want to check for the existence (or duplication) of these bean implementations during start-up of the application server. Since Spring version 3.0 it is possible to use Spring's ApplicationListener. This interface is based on the EventListener and uses the standard Observer design pattern. In 3 steps we can easily check for the existence of a specific Spring bean.

  1. We create an ApplicationListener<ContextRefreshedEvent> implementation. The method onApplicationEvent will be called when a refresh of the ApplicationContext occurs.

    package com.jdriven.blog.applicationlistener;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class BeanContextStartupListener
       implements ApplicationListener<ContextRefreshedEvent>
    {
       public void onApplicationEvent( ContextRefreshedEvent event )
       {
          ...
       }
    }
    
  2. We need to register the BeanContextStartupListener as a Spring Component. In this sample we just simply enable component scanning in the spring xml configuration as follows.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.jdriven.blog.applicationlistener" />
    </beans>
    

    We also add the @Component to the class definition:

    import org.springframework.stereotype.Component;
    
    @Component
    public class BeanContextStartupListener
       implements ApplicationListener<ContextRefreshedEvent>
    
  3. We implement the onApplicationEvent method of the BeanContextStartupListener and throw an Exception when no bean exists within the current ApplicationContext.

    public void onApplicationEvent( ContextRefreshedEvent event )
    {
       Map serviceImplementations = event.getApplicationContext().getBeansOfType( JDrivenService.class );
       if ( serviceImplementations.isEmpty() ) {
          throw new IllegalStateException("JDrivenService was not instantiated during startup.");
       }
    }
    

Continue reading →

Groovy Goodness: Return Closure From Another Closure or Method

Posted on by  
Hubert Klein Ikkink

Groovy closures are powerful. A closure can be passed to methods as argument or defined as a variable. We can even return closures from methods or other closures. We can use the returned closure to execute the logic from the closure with the explicit call() method or the implicit syntax with just the closure object followed by opening and closing parentheses (()).

// Method returns a closure. Method could
// also have been another closure to return
// the closure.
def repeater(times) {
    { value -> value * times }
}

// Use explicit call() method on the return closure
// object from the repeater() method.
assert repeater(2).call('mrhaki') == 'mrhakimrhaki'

// Use implicit call() method on the return closure
// object from the repeater() method. This
// might looks strange at first...
assert repeater(2)('mrhaki') == 'mrhakimrhaki'

Continue reading →

Tasty Test Tip: Test final and static methods with PowerMock and Mockito

Posted on by  
Arthur Arts

Two of the most famous mocking frameworks EasyMock and Mockito, don't offer out of the box support for mocking final and static methods. It is often said on forums that "you don't want that" or "your code is badly designed" etc. Well this might be true some of the time, but not all of the time. So let's suppose you do have a valid reason to want to mock final or static methods, PowerMock allows you to do it. Here's how (example with Mockito):

 <dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.4.12</version>
    <scope>test</scope>
</dependency>

Continue reading →

Groovy Goodness: Using Project Coin Features Also With Older Java Versions

Posted on by  
Hubert Klein Ikkink

Since Groovy 2 we can use a subset of the Project Coin features from Java 7. But we don't have to run Java 7 to use them in Groovy code. We can use the new features even if we run our Groovy code on older Java versions.

Groovy didn't have to add all Project Coin features, because some are already supported in Groovy, like the switch statement on String objects or diamond operator. A feature that is added is a syntax enhancement to define binary literals. We can now use binary integral literals by prefixing the value with 0b:

Continue reading →

Groovy Goodness: Drop or Take Elements with Condition

Posted on by  
Hubert Klein Ikkink

In Groovy we can use the drop() and take() methods to get elements from a collection or String object. Since Groovy 1.8.7 we also can use the dropWhile() and takeWhile() methods and use a closure to define a condition to stop dropping or taking elements. With the dropWhile() method we drop elements or characters until the condition in the closure is true. And the takeWhile() method returns elements from a collection or characters from a String until the condition of the closure is true. In the following example we see how we can use the methods:

def s = "Groovy Rocks!"

assert s.takeWhile { it != 'R' } == 'Groovy '
assert s.dropWhile { it != 'R' } == 'Rocks!'

def list = 0..10

assert 0..4 == list.takeWhile { it < 5 }
assert 5..10 == list.dropWhile { it < 5 }

def m = [name: 'mrhaki', loves: 'Groovy', worksAt: 'JDriven']

assert [name: 'mrhaki'] == m.takeWhile { key, value -> key.length() == 4 }
assert [loves: 'Groovy', worksAt: 'JDriven'] == m.dropWhile { it.key == 'name' }

Continue reading →

Groovy Goodness: Using Implicit call() Method

Posted on by  
Hubert Klein Ikkink

In Groovy we can invoke an implicit call() method on a Groovy object. We can leave out the call method name and just use (). We can use meta programming to add an implementation for the call() method to a class. In the following example script we add an implementation for the call() method with a single parameter to the String class. The implementation returns the element found at the range specified by the argument when we invoke the method:

String.metaClass.call = { range ->
    delegate[range]
}

def value = 'Groovy is Gr8'
assert value(0) == 'G'
assert value(10) == 'G'
assert value(4) == value[4]
assert value.call(1) == value(1)
assert value(0..5) == 'Groovy'

Continue reading →

Groovy Goodness: Boolean Implications

Posted on by  
Hubert Klein Ikkink

Since Groovy 1.8.3 we can use the implies() method on Boolean types. The implies() method implements a logical implication. This means that if we have two Boolean variables A and B, that if A is true, than B is true. So if A is true than it is implied B is true as well. If A is false than B can be either true or false. We could rewrite the implication as !A or B.

def a = true
def b = true

assert a.implies(b)
assert !(a.implies(false))

assert a.implies(b) == ((!a).or(b))

assert true.implies(true)
assert false.implies(true)
assert false.implies(false)
assert !true.implies(false)

Continue reading →

Gradle Goodness: Customize IDEA Project File Generation

Posted on by  
Hubert Klein Ikkink

With the Gradle IDEA plugin we can generate JetBrains IntelliJ IDEA project files. The plugin uses defaults from our project to generate the files. If we also apply the Java plugin to our project then the Java settings for the project files are generated. We can customize the file generation in several ways. The most low level method is using the withXml hook. With this hook we have access to the XML before the file is written to disk. Here we can add or change XML elements and attribute values. We use a closure as argument for the withXml hook and Gradle adds a XmlProvider object as argument. The easiest way to manipulate the XML is getting a groovy.util.Node from the XmlProvider. We also can get a DOM Element or StringBuilder to work with. In the following example build file we change the contents of the IDEA project file (with extension .ipr). We change the output directory of the JavaDoc tool. We use Groovy syntax to find the JavadocGenerationManager which is automatically added, because we have the Java plugin in our build file. We also change the Encoding component or create it when it doesn't exist:

apply plugin: 'java'
apply plugin: 'idea'

idea {
    project {
        // Here we customize the .ipr file generation.
        ipr {
            // XML hook to customize the XML before
            // it is written to disk
            withXml { xmlProvider ->
                // Get root node.
                def project = xmlProvider.asNode()

                customizeJavaDoc project
                customizeEncoding project
            }
        }
    }
}

/* Customize JavadocGenerationManger component */
def customizeJavaDoc(project) {
    def javaDocGenerationManager = findComponent(project, 'JavadocGenerationManager')
    changeOption javaDocGenerationManager, 'OUTPUT_DIRECTORY', '$PROJECT_DIR$/out/javadoc'
}

/* Search component with given name */
def findComponent(project, name) {
    project.component.find { it.@name == name }
}

/* Set value for option node with given name */
def changeOption(node, name, value) {
    node.option.find { it.@name == name }.@value = value
}

/* Customize Encoding component */
def customizeEncoding(project) {
    def encoding = findComponent(project, 'Encoding')

    if (encoding) {
        // Change existing node.
        encoding.@useUTFGuessing = true
        encoding.@native2AsciiForPropertiesFiles = true
        encoding.@defaultCharsetForPropertiesFiles = 'UTF-8'
    } else {
        // Create new node with default values.
        project.appendNode 'Encoding', [useUTFGuessing: true, native2AsciiForPropertiesFiles: true, defaultCharsetForPropertiesFiles: 'UTF-8']
    }
}

Continue reading →

To Roo or not to Roo...

Posted on by  
Emil van Galen

Recently I've been looking into Spring Roo to find ways to speed-up software development as well as reducing plumbing code. In this blog post I will highlight some of the advantages and disadvantages of Spring Roo which I stumbled upon. So don't expect a full featured introduction or tutorial; plenty of those already exist on the internet ;-)

Spring Roo takes on a different approach to code generation compared to other solutions. Instead of generating additional .java files (through the "Generation Gap Pattern") it generates so-called AspectJ inter-type declaration (ITD) .aj source files. Each generated inter-type declaration (ITD) type will "weave in" structural changes to its target .java file; for example to add new methods (i.e. getter/setter methods) or an "implements ..." clause. The big advantages of such inter-type declaration (ITD) are:

Continue reading →

Google Guava Goodness: Converting Between ASCII Case Conventions

Posted on by  
Hubert Klein Ikkink

The Google Guava libraries contains useful utility classes and methods. If we want to convert between ASCII case conventions we can use the CaseFormat class. The class defines constants for upper and lower case CamelCase, upper and lower case hyphenated and upper case underscore. This means we can convert UPPER_VALUE to upper-value with a simple line of code.

import static com.google.common.base.CaseFormat.*;

assert LOWER_CAMEL.to(UPPER_UNDERSCORE, "lowerCase").equals("LOWER_CASE");
assert LOWER_HYPHEN.to(LOWER_UNDERSCORE, "manual-index").equals("manual_index");
assert UPPER_CAMEL.to(LOWER_UNDERSCORE, "UpperCase").equals("upper_case")

Continue reading →

shadow-left