Iterating over a map is slightly more complex than over other collections, because a Map is the combination of 2 collections. The keys and the values.
val m: Map[Int, String] = Map(1 -> "a", 2 -> "b")
m.keys // = Iterable[Int] = Set(1, 2)
m.values // = Iterable[String] = MapLike("a", "b")
Continue reading →
Ratpack comes with a special handler to log requests in the common log or NCSA format. We need the (default) interface ratpack.handling.RequestLogger
which has a method ncsa
that returns a handler instance capable of logging our request data.
In the following example code we have a Groovy DSL definition of our Ratpack application. We use the all
method to add the request logger. The RequestLogger
implementation will make sure the complete handler chain is finished before logging the information.
Continue reading →
When we have multiple Options and only want to do something when they're all set. In this example we have a property file with multiple configurations for one thing. A host and a port, we only want to use them if they're both set.
//The individual properties
val stubHost: Option[String] = Some("host")
val stubPort: Option[Int] = Some(8090)
//The case class I'll turn them into
case class StubConfig(host: String, port: Int)
Continue reading →
Both the JVM and keytool have problems dealing with keystores without a password. If you try to get a listing of the keystore it will think you didn't provide a password and output falsehoods:
$ keytool -list -storetype pkcs12 -keystore keystoreWithoutPassword.p12
Enter keystore password:
***************** WARNING WARNING WARNING *****************
* The integrity of the information stored in your keystore *
* has NOT been verified! In order to verify its integrity, *
* you must provide your keystore password. *
***************** WARNING WARNING WARNING *****************
Keystore type: PKCS12
Keystore provider: SunJSSE
Your keystore contains 1 entry
tammo, Oct 14, 2015, SecretKeyEntry,
Continue reading →
A lot of bugs are in some way related to state. So that is what we will be talking about today. We will start off with a quote from Einstein: “Insanity: doing the same thing over and over again and expecting different results. ” Code should be consistent, calling the same function with the same input should return the same result during the whole life cycle of the object. Insanity and bugs will follow if this rule is violated. This sounds logical, but in practise it is quite easy to violate this principle. The main cause of this, is object state. This state is used in a lot of functions, and can thus affect the behaviour of our program at runtime. This principle can be even be seen in the most basic of examples (imagine the impact on a more complicated class...). Given the following class:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Continue reading →
In a previous post we saw how can use the Spock configuration file to include or exclude specifications based on annotations. Instead of using annotations we can also use classes to include or exclude specifications. For example we could have a base specification class DatabaseSpecification
. Other specifications dealing with databases extend this class. To include all these specifications we use the DatabaseSpecification
as value for the include
property for the test runner configuration.
Because Java (and Groovy) doesn't support real multiple inheritance this might be a problem if we already have specifications that extends a base class, but the base class cannot be used as filter for the include
and exclude
runner configuration. Luckily we can also use an interface as the value for the inclusion or exclusion. So we could simple create a marker interface and implement this interface for these specifications we want to include or exclude from the test execution.
Continue reading →
Logback is a SLF4J API implementation for logging messages in Java and Groovy. We can configure Logback with a Groovy configuration file. The file is a Groovy script and allows for a nice an clean way (no XML) to configure Logback. If we want to show the logging configuration and see how Logback is configured we must add a StatusListener
implementation in our configuration. The StatusListener
implementation prints out the configuration when our application starts. Logback provides a StatusListener
for outputting the information to system out or system error streams (OnConsoleStatusListener
and OnErrorConsoleStatusListener
). If we want to disable any status messages we use the NopStatusListener
class.
In the following example configuration file we define the status listener with the statusListener
method. We use the OnConsoleStatusListener
in our example:
Continue reading →
When we use Logback as SLF4J API implementation in our code we can have our logging output send to our console. By default the standard output is used to display the logging output. We can alter the configuration and have the logging output for the console send to standard error. This can be useful when we use a framework that uses the standard output for communication and we still want to see logging from our application on the console. We set the property target
for the ConsoleAppender
to the value System.err
instead of the default System.out
. The following sample Logback configuration in Groovy send the logging output to the console and standard error:
appender("SystemErr", ConsoleAppender) {
// Enable coloured output.
withJansi = true
encoder(PatternLayoutEncoder) {
pattern = "%blue(%-5level) %green(%logger{35}) - %msg %n"
}
// Redirect output to the System.err.
target = 'System.err'
}
root(DEBUG, ["SystemErr"])
Continue reading →
In a previous blog post we made an API with spray. Now we're going to load test it. For this, we will use http://gatling.io/#/. In a scala class we can write exactly what and how we want to run the test. In this test, we will do a post to our API and create a new robot called C3PO. We will do this 1000 times per second and keep doing this for 10 seconds. For a total of 10000 C3POs! RobotsLoadTest.scala:
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
class RobotsLoadTest extends Simulation {
val baseUrl = "http://localhost:8080" //We need to have our API running here
val httpProtocol = http
.baseURL(baseUrl)
.inferHtmlResources()
.acceptEncodingHeader("gzip,deflate")
.contentTypeHeader("application/json")
.userAgentHeader("Apache-HttpClient/4.1.1 (java 1.5)")
val s = scenario("Simulation")
.exec(http("request_0")
.post("/robots")
.body(StringBody("""{
| "name": "C3PO",
| "amountOfArms": 2
|}""".stripMargin))
)
setUp(s.inject(constantUsersPerSec(1000) during(10 seconds))).protocols(httpProtocol)
}
Continue reading →
Suppose I have a List of things on which I want to do something that may fail. In this example I have a List of Strings that I want to turn into a List of Integers.
val strings = List("1", "bla", "4")
Continue reading →
Tuesday we had our second ever "Vrolijke Framboos" (Dutch for Happy Raspberry) Java code challenge at JDriven and it was a blast! This year’s challenge was to create a REST service client that would play a number guessing game with the server. After setting up a session you would guess a number and the server would respond with either "lower", "higher" or "bingo". The goal was to guess as many numbers in the two minutes you’d be given. Given the name of the challenge you can probably guess that the target platform would be a Raspberry Pi!
It was an incredible and fun experience and in this post I want to explain how I approached the challenge and how my solution ended up in the second place, making me just miss the opportunity to take home the trophy and a new Raspberry.
Continue reading →
In Spray, you get a lot of input validations for free. If you have a model like this:
object RobotProtocol extends DefaultJsonProtocol {
case class Robot(name: String, amountOfArms: Int)
implicit val RobotFormat = jsonFormat2(Robot)
}
Continue reading →