Groovy Goodness: New Methods to Sort and Remove Duplicates From Collection

In Groovy we can use the sort and unique methods to sort a collection or remove duplicates from a collection. These methods alter the collection on which they are invoked. This is a side effect we might want to avoid. Therefore the sort and unique methods where changed and we could pass a boolean argument to indicate if the original collection should be changed or that we must have a new collection as the result of the methods, leaving the original collection untouched. Since Groovy 2.4 we have two new methods which by default return a new collection: toSorted and toUnique.

Continue reading

Construct a typed Array via List.toArray() with correct size

When we construct an typed Array out of an existing List, we use the method T[] toArray(T[] a). When an array with a lower size than the size of the List is passed as argument, this results in a new array being created. Take a look at the implementation of ArrayList here.
Using the method with an incorrect sized array is inefficient. Using the toArray method directly with a correctly sized array is therefore preferable.

Not preferred

Preferred 1

Preferred 2

N.B.: This blog is written based on this stackoverflow entry. All credits go to the stackoverflow poster and commentators of this entry.

Building a war with spray-servlet

We will use spray-servlet to build a war file of our API. So we can run it in a java app server.
I assume we already have a working REST API.

We will need a web.xml, under src/main/webapp/WEB-INF/:

We need an sbt plugin to build wars. Add this to project/plugins.sbt:

We’ll add dependencies to build.sbt, and also extra tasks:

We’ll need to extend spray.servlet.WebBoot:

And add a reference to this class in application.conf:
spray.servlet {
boot-class = “Boot”
}

on spray.io is a good example application

Now we can run sbt package to build a war.
And in sbt, use container:start to start a tomcat server with our application. And container:stop to stop it.

A good way to restart the server every time we change code is:

Groovy Goodness: Combine Elements Iterable with Index

Since Groovy 2.4.0 we can get the indices from the elements in a collection with the indices method. In addition to this method we can also use the withIndex to combine an Iterable with the indices directly. The output is a List of tuples where the first item is the value of the Iterable and the second the index value. We can pass an optional argument to the withIndex which is the starting point for the index values.
Another alternative is the indexed method. The indexed method returns a Map, where the key of the entry is the index value and the entry value is the Iterable value.

Continue reading

Groovy Goodness: Swapping Elements in a Collection

Groovy already has so many extra methods for working with collections. If we have to need to swap two elements in a collection we can use the swap method. We provide the two index values of the elements we want to swap and Groovy swaps the elements.

In the following sample we have a simple list and swap all elements by invoking the swap method two times:

Written with Groovy 2.4.1.

Original article

Spicy Spring : Different ways of Autowiring

I would like to show different ways of using Spring’s @Autowired annotation: Constructor, Method and Field autowiring.
The examples I show are all a form of byType autowiring mode (constructor autowiring mode is Analogous to byType). Take a look at the Spring Reference guide for more information on the Autowiring modes.

Constructor Autowiring

Create a constructor with a dependent bean as constructor parameter and add the @Autowired annotation to the constructor. A big advantage of autowiring by constructor is that the field can be made final, and therefore may not be changed after construction.

Method Autowiring

Create a setter method for the dependent bean and add the @Autowired annotation to the setter method. A disadvantage of using Method autowiring is that the setter can be called in production code, overriding the bean accidentally.

Field Autowiring

Create a field (member variable) for the dependent bean and add the @Autowired annotation to the field. This way of Autowiring has less code, but takes more effort to test the AutowiredCapabilityBean with an implementation of the InjectableBean, since there is no constructor and no setter for it.

Groovy Goodness: Use Constructor as Method Pointer

In Java 8 we can create a constructor reference. We must use the syntax Class::new and we get a constructor reference. This syntax is not supported in Groovy, but we can use the method pointer or reference syntax .& to turn a method into a closure. We can even turn a constructor into a closure and use it everywhere where closures are allowed.

Continue reading

Chaining futures in Scala

Suppose I want to make coffee. This involves 4 steps:

  • 1a. grind coffee beans
  • 1b. heat water
  • 2. combine
  • 3. filter

All these steps take time, so they return a Future.
This is our domain:

One way we could chain the futures together is with onSuccess:

Using flatMap we can simplify this to:

Notice that we have the future of our filtered coffee at the highest level. This is nice! We can return it, or call Await.Result on it to wait for our coffee to be ready.

Since a for comprehension is a shorter way of writing flatMaps, we can simplify it to this:

cheers!

Building a rest API with spray

Building a rest API with akka and spray is easy. This is how I did it:
SprayApiApp:

ApiActor:

The full example code: https://github.com/tammosminia/sprayApiExample

When we run this, we can do a get on http://localhost:8080/robots and get the list of robots:

And we can do a post to http://localhost:8080/robots to add a robot:
with header Content-Type: application/json

When we take a look at the logging, we notice that the code in the route construction will only run once during startup.
Only the code within complete and handleWith will be run with every request.

with thanks to: http://blog.michaelhamrah.com/2013/06/scala-web-apis-up-and-running-with-spray-and-akka/

Nifty JUnit : Using Rule on Method and Class level

As shown in a the post Nifty JUnit : Working with temporary files, it is possible to use @Rule in a JUnit test, which is a Method level Rule. In this example I would like to show the variation of the @ClassRule for a Class level Rule.

Method Rule

The @Rule is fired before each test method (just like @Before) and after each test method (just like @After) of the test class, as shown in the example below.

Class Rule

Besides the regular @Rule we have the possibility to create a @ClassRule. In the example of the TemporaryFolder it will result in a folder which is created before all test methods (just like @BeforeClass) and destroyed after all test methods (just like @AfterClass). In the example below you can create a temporary file and use the exact same file in all the test methods. The temporary file will be deleted when all the test methods are finished.