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
.
In the following sample we see the new methods in action:
Continue reading →
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.
ArrayList myList; //Assume myList has some added entries
//Size is too small a 2nd array will be created
MyClass[] arr = myList.toArray(new MyClass[0]);
Continue reading →
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/:
spray.servlet.Initializer
SprayConnectorServlet
spray.servlet.Servlet30ConnectorServlet
true
SprayConnectorServlet
/*
Continue reading →
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.
In the following example we use the withIndex
method. The sample of the alphabet is the same as in the blog post about indices, but rewritten with the withIndex
method:
Continue reading →
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:
Continue reading →
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.
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.
Continue reading →
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.
In the following sample code we have a User
class with some properties. Via the User.metaClass
we can get a reference to the method invokeConstructor
and turn it into a method closure:
Continue reading →
Suppose I want to make coffee. This involves 4 steps:
- 1a. grind coffee beans
- 1b. heat water
- combine
- filter
Continue reading →
Building a rest API with akka and spray is easy. This is how I did it: SprayApiApp:
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import scala.concurrent.duration._
object SprayApiApp extends App {
//we need an ActorSystem to host our application in
implicit val system = ActorSystem("SprayApiApp")
//create apiActor
val apiActor = system.actorOf(Props[ApiActor], "apiActor")
//timeout needs to be set as an implicit val for the ask method (?)
implicit val timeout = Timeout(5.seconds)
//start a new HTTP server on port 8080 with apiActor as the handler
IO(Http) ? Http.Bind(apiActor, interface = "localhost", port = 8080)
}
ApiActor:
import akka.actor.{ActorLogging, Actor}
import spray.http.MediaTypes
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol
import spray.routing._
object RobotProtocol extends DefaultJsonProtocol {
//Our domain class
case class Robot(name: String)
//We use the default json marshalling for Robot.
//There are multiple jsonFormat methods in DefaultJsonProtocol. Depending on how many parameters the model class has.
//Robot has just one, so we use jsonFormat1
implicit val RobotFormat = jsonFormat1(Robot)
}
import RobotProtocol._
class ApiActor extends Actor with HttpService with ActorLogging {
//A list of our domain objects
var robots = List(Robot("R2D2"), Robot("Asimo"))
//The HttpService trait defines only one abstract member, which
//connects the services environment to the enclosing actor or test
def actorRefFactory = context
//This actor only runs our route, but you could add
//other things here, like request stream processing or timeout handling
def receive = runRoute(apiRoute)
//Notice that both path methods return a Route. We need to chain them together with ~
val apiRoute: Route =
path("robots") {
get { //with get we will return our current list of robots
log.info("Building get route")
complete {
log.info("Executing get route")
//complete will return the result in an appropriate format
//With SprayJsonSupport it knows how to marshall a List to json
//With RobotFormat it knows how to marshall Robot
robots
}
} ~ post { //With post we will add a robot
log.info("Building post route")
handleWith { robot: Robot => //handleWith will unmarshall the input
log.info("Executing post route")
robots = robot :: robots
robot //handleWith will also marshall the result. Here we simply return the new robot.
}
}
} ~ path("") { //When we go to localhost:8080/ just show a link to localhost:8080/robots
respondWithMediaType(MediaTypes.`text/html`) { //XML is marshalled to `text/xml` by default, so we simply override here
complete {
[The list of robots](/robots)
}
}
}
}
Continue reading →
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.
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.
Continue reading →
We have to deal with legacy code, even when we would like to use the best and newest technologies available. Imagine the new code is written with the newest technologies of the Spring Framework and the legacy code is not written in Spring at all. Then using Spring managed Beans in non-managed Spring objects is one of the patterns we have to deal with. The legacy code has non-managed Spring objects, while the code we want to reference to is a Spring managed Bean. How do we solve this problem?
Let's assume we have a managed Spring Bean called TaxService
and an object called LegacyObject
. The LegacyObject
is the legacy code from where we would make a reference to the method calculateTax
on the managed Spring Bean.
Continue reading →
So many men, so many minds. When we are implementing software for different customers we sometimes need to handle various requirements for the same project. For example Customer A needs SAML authentication and customer B needs LDAP authentication. With Spring Profiles (available from Spring 3.1) we are able to provide a way to segregate parts of our implemented application configuration. This blog will help us to make certain code or rather certain Spring beans only available for specific requirements. For example the example used in this blog can be used to activate the required authentication provider for the provider manager when using Spring Security. Profiles can be configured by annotations and/or by xml. Annotations @Component or @Configuration annotated beans can contain the annotation @Profile to only load them in a certain environment.
@Component
@Profile("ldap")
public class LDAPAuthentication {
public LDAPAuthentication() {
System.out.println("LDAP Authentication set by annotations");
}
}
@Component
@Profile("saml")
public class SAMLAuthentication {
public SAMLAuthentication() {
System.out.println("SAML Authentication set by annotations");
}
}
Continue reading →