A wonderfully simple solution to run JUnit parameterized tests in parallel:
http://hwellmann.blogspot.be/2009/12/running-parameterized-junit-tests-in.html
Works for JUnit 4.11 also.
Many thanks indeed ! :-)
The Craft of Java
Thursday, March 7, 2013
Tuesday, January 15, 2013
Hidden Gem: Thymeleaf
I don't know how popular Thymeleaf is, but to me it is a hidden gem. It is a very powerful and versatile template engine.
I had to look for a template engine and was thinking about the usual candidates Velocity and FreeMarker. Unfortunately the former hasn't changed since 2010 and the latter has internationalization issue. Hence the need to look for something else.
When looking for the template engine recommendations on devrate, I found Thymeleaf.
The new markup elements were up and running under two hours. There wasn't a single case where the API wasn't providing for what was needed. Still have to check the Spring integration though.
Definitely worth a look !
Friday, November 23, 2012
Day 5 - Devoxx 2012
And the end is already very palpable ... :-(
I wish I could show the example from the slides of the speaker. He overdid on purpose to show where annotations can be added.
The facts:
Although I don't get why they're redoing the annotations of JAX-RS for their own API.
The facts:
ANNOTATION FEATURES IN JDK 8
One of JDK8's features are the type annotations. Besides the already known locations, declarations basically, you'll be able to add annotations to type definitions. Effectively describing your intention in the usage of the type of a variable, method argument, method return type, etc...
An example from the specification: Note the annotation on the generic type.
interface List<T> {
public int size(@Readonly List<@Readonly T> this) { . }
}I wish I could show the example from the slides of the speaker. He overdid on purpose to show where annotations can be added.
The facts:
- JSR-308.
- Aims at making it easier to find annotations.
- Introducing the Checker Framework (code analysis, not part of the JDK).
- Repeating annotations will be supported.
- JEP-120
- Annotating twice or more a declaration with the same annotation (with different attribute values).
- The current way is to wrap those annotations into another annotation containing an array attribute of the repeating annotation.
- JDK8 will eliminate the need for that wrapper construction. But at the usual price of forcing in absurdity to remain 100% backwards compatible.
- You won't actually see an array in the source code alright. BUT ... you'll still need to define it. The repeating annotation should tell what the enclosing annotation type is. Hence you also need to define the enclosing type. But you won't actually use it in the source code.
- Damn ... now that's profound. I wonder how long the linguists at Oracle will be able to find this kind semantic tricks. Before they've driven themselves into a corner I mean.
- Possibility to have sub classes inherit the annotations of their super classes. Today you have to recurse through the ancestry of a class to gather all those annotations.
- Introducing javax.lang.model. A compile-time API for introspection.
- We'll be able to do annotation processing at runtime. This is now solely the domain of the compiler.
After all a very informative presentation. I was wondering what those type annotations were.
JSR 356 : THE JAVA API FOR WEBSOCKET
A very good presentation about web sockets for Java. As a reminder, web sockets is the latest network-level solution to improve performance. It allows to do at network level tricks browsers are using to keep durable connections.
- Version 1.0
- JSR 356.
- To be included into JEE 7.
- Aim for
- Durable
- Low-latency
- Bi-directional
- Full-duplex (asynchronous)
- Build-in keep alive
- Eliminate the overhead from headers, cookies, security, ...
- A web socket connection is obtained by the HTTP upgrade mechanism. One party requests a switch from regular stateless HTTP to web socket. If the other party agrees, the connection becomes as described above.
- It's said to be free of firewall problems because the connection won't be checked again after the upgrade. But that's not counting in firewalls checking the actual traffic content. Sure enough it won't look like regular HTTP.
- There are 4 official sub-protocols (too fast to note) which indicate what use is being made of the connection. Sub protocols can be added.
- Most browsers already support it.
- Project Tyrus is the reference implementation.
- The API is annotation driven. Annotated beans become Session EJB. (I presume Statefull Session EJB.) The annotations are very similar to those of JAX-RS.
- You'll be able to add code to (un)serialize objects.
- A client API will be provided.
- Still a lot of work to do.
Although I don't get why they're redoing the annotations of JAX-RS for their own API.
PUTTING KOTLIN TO THE TEST
The last talk for Devoxx 2012 is an occasion to hear about Jetbrains' own JVM programmaing language Kotlin. A funny presentation that starts with a warning though: Don't compare it to Scala !!! :-)- Jetbrains aims for rewriting all their tools with this language. Today this is mainly Java.
- Currently in milestone build. Try it if you want, but wait for the beta releases for serious work.
- It's open source.
- Like Java, it's statically typed - all typing is set at compile time.
- It's aims for a total interoperability with Java.
- Be better than Java and Scala.
- The syntax is recognizable for those knowing Java (and Scala).
- Specific features
- Compiles to JVM byte code and JavaScript !
- Data classes : Classes only containing state - no methods.
- Traits have no state - only methods.
- Classes are final by default.
- Hard enforcement of null handling. You have to prove not nulls - or write ugly syntax to override the null checks. As such taking responsibility in ignoring the checks.
Notwithstanding the presenter's warning, I think Kotlin looks very much like Scala. :-) But I understand you'd rather do your own language - where you have a total and immediate control of the features. I guess Scala is already beyond that.
Anyway, it's still a bit early to jump on Kotlin. But knowing Jetbrains it'll be impressive ! Especially the null check is awesome. Scala has the Option type; but nothing prevents you from passing a null instead. And thus causing a NPE downstream.
Wednesday, November 21, 2012
Day 4 - Devoxx 2012
BEAN VALIDATION 1.1: IT'S NOT BEANSLAND ANYMORE
A one-hour talk about the upcoming Bean Validation API. The gist of bean validation is to put the validation logic to the model. Everywhere the model passes this logic can be invoked before processing the model. Whereas today, this logic tends to be spread out in the various layers. If it's there at all. Over even equivalent everywhere.
Officially started under JEE 6; to be used by various parts of other JSR's.
The facts:
- Current mainstream release is 1.0.
- JSR-303.
- Homepage http://beanvalidation.org.
- In use for JPA, JSF and CDI.
- Annotation-driven; on the model classes.
- Allows for extending the annotations.
- Grouped validation. Annotation gets a reference to a class. The validation can be invoked for all the annotation of that class. Hence "grouped" validation.
Upcoming release:
- Version 1.1.
- JSR-349.
- Part of JEE 7.
- Tight integration with dependency injection (CDI, Spring, Guice, ...)
- Method validation - where the byte code will be modified to actually enforce the validation on the method arguments and return values !
- Error message formatting.
- Support for JAX-RS.
- Hibernate supports today's state of 1.1.
- Group conversion - Can't recall the specifics, but at the time of the presentation it seemed important. :-)
Bean validation is something I definitely need to pay a closer look. For it allows to centralize the validation logic in one place, with a minimum effort.
OAUTH 2 AND IDENTITY
That's weird... I've lost my notes on the tablet ?!
Anyway, the oauth principle is to ask a third-party (ex. Google) to get some of your account data. Typically you are on site that is giving you the possibility to "register using Google/FaceBook/...". And if you click on the related icon you're directed to that third-party. Where you'll be asked whether it's okay for your to communicate such and such data to the site you're registering on.
The upshot is that the registration process is much faster and that only the third party has an account about you.
The second release is there, and is available for both server- and client side.
SIMPLICITY IN SCALA DESIGN
And yet another Scala talk ! This time Bill Venners is explaining his Scala design principles for API. With ScalaTest as a base of discussion.
- Strive for ease of use.
- Make it easy to remember. One obvious way to do one thing.
- Design for busy people: download, use, don't read any doc and run.
- Make it difficult to make mistakes.
- Be consistent.
- Symbolic operators/methods are destined for experts. Know your audience !
- Don't push functional programming beyond the point readability becomes an issue.
What's not visible here are the many examples he gives how this applies to Scala code. But I guess these rules apply to any programming language.
JAVAPOSSE LIVE
THE mandatory event of Devoxx !!! Fun & Beer from Atlassian. :-)
Although I've got the impression they're a bit running out of steam lately. I sincerely hope the new, and officially accredited member will bring new life: Chet Haase !
In case you don't know the JavaPosse podcast: http://javaposse.com/
THE PRESENT AND THE FUTURE OF JAX-RS AND JERSEY
As a reminder, JAX-RS is the specification for REST web services on a Java application server. Not to be confused with JAX-WS, the SOAP equivalent.
We start with what seems the mandatory (and lengthy) REST recap. A shame really. I guess people coming to a talk with this title are already familiar with it.
The Facts:
- Current mainstream release 1.1.
- JSR-311.
- Included into JEE 6.
- Annotation-driven; on service classes.
- The annotations match inbound HTTP REST requests. Very similar to what Spring MVC is doing.
The upcoming:
- Release 2.0.
- JSR-339.
- Will be part of JEE 7.
- A client API.
- Async HTTP for both client- and server.
- Filters & interceptors (very comparable to Servlet Filters)
- Manipulate requests/responses as they pass along.
- Ordering of those.
- Entity serialization.
- Server push
- Unified configuration (whatever that will become)
- Support for CDI.
Good to know, but nothing groundbreaking really...
SPRING 3.2 AND 3.2 THEMES AND TRENDS
Let's learn Spring 3.2... after checking out 3.1. And again, off to the mandatory recap session. I'd rather expect with that title it would be about 3.2 mostly really...
The Facts:
- Expected for Dec 2012. There are already RC releases.
- Caching will be ramped up. Maybe I'll finally be able to replace EHCache by Infinispan.
- Method results can be cached.
- A real servlet container initializer. So you can initialize and destroy properly the application context.
- JPA without persistence.xml.
- Hibernate 4.
- Quartz 2.
- JDK7.
- Testing with the Spring MVC Test Project. Definitely need to check that one out also.
Release 3.3 has been delayed ... due to delays with JDK8. Hence Spring released what they had earlier in 3.2.
Monday, November 19, 2012
Day 3 - Devoxx 2012
DESIGNING REST-FUL APIS WITH SPRING 3
A quick introduction about REST and how to apply this using Spring MVC. After a long introduction to REST, the speaker finally comes to the application of the principle with Spring:
- Write a controller class
- Annotate it with @Controller and @RequestMapping
- Annotate the REST endpoint methods with @RequestMapping
Exceptions can be converted into concrete HTTP error codes using methods annotated with @ExceptionHandler.
My discovery are the links. You can actually relate entities to the subject entity of a REST request. Which can be involved in the next requests. Etc...
Also briefly touched HATEOAS.
ON THE ROAD TO JDK 8: LAMBDA, PARALLEL LIBRARIES, AND MORE
Learning about the upcoming JDK8, this was a talk not to be missed. Especially as this was Joe Darcy presenting.
The facts:
- There is already a weekly build of JDK8 containing the Lambda expressions.
- Defined by JSR-335.
- Currently there's only one IDE supporting it: Intellij 12 Preview.
- The final release is expected around summer 2013.
The features:
- Lambda expressions.
- Interfaces with default methods.
- Bulk operations on collections.
- Parallel operations on collections.
- Binary compatibility is maintained - against all odds.
Lambda expressions have a now very recognizable syntax. For example (Object o) -> o.toString() represents a function accepting an object as input, returning the string representation.
In practice one should never modify an interface. Because linking the new definition of an interface with code that was compiled with an earlier version might run haywire. Except ...
interface Bar {
String toBar();
default String toFoo() {
return "foo";
}
}
... when a method is added containing a concrete implementation ! Aka default methods. It doesn't hurt old code when the added methods are not abstract. As such opening the gates for real multiple-inheritance in Java.
Collections will get an overhaul with bulk operation methods. For instance you'll be able to run a method forEach( <lambda>) to run the expression for every element in the collection. Those methods could be chained together to define a one-statement sequence of transformations. As this is already the case for other JVM languages.
The consequence is also that the collection can decide autonomously to run some operations in a fork/join style. After all, there is seldom the requirement to run bulk operations sequentially. As long as each element has been visited, there's no problem.
With JDK8, it seems, Java is catching-up with its more functional counterparts. So, even if Jigsaw will be missed, the Lambda Expressions will give us enough to work with.
Somewhere, there is relation with invokeDynamic. But I thought that was only for the dynamically typed languages. Not Java. Or is it ?
USING SPRING IN SCALA
This is a talk about the brand new Spring Scala project. It is supposed to become the Scala version of the Spring bean container.
Still in its very early stages however. First milestone release expected for December.
The features:
- Scala class constructor injection
- @BeanProperty support
- Support for Scala getters/setters
- FunctionalConfiguration trait. Which is the Scala equivalent of JavaConfig; with a nice dsl added.
- XML markup for Scala collection.
- Scala proper templates: JDBC, REST, JMS, ...
- TransactionManagement trait to run code into transactions.
EFFECTIVE SCALA
A discussion of do's and don'ts when programming in Scala. Presented by Joshua Suereth, the author of Scala in Depth.
- Aim to write expressions (returning a result) instead of statements (running code).
- Experiment with the REPL tool to try Scala code.
- Observe immutability
- Case classes
- Immutable collection types
- Don't let mutable state escape methods
- Use Option for optional values. Use the for loop and orElse to process those values.
- Declare the method return types
- Limit the scope of implicits. They might intervene unnoticed in unexpected ways otherwise.
- Avoid implicit view - whatever those are.
- Know your collections
- Vector is best for random access. Linked lists (ie List) are not.
- First check collection methods for the functionality you need.
- When providing a library for Java, do this using Java interfaces.
TESTING JAVA PERSISTENCE LAYER DONE RIGHT WITH ARQUILLIAN
A quick session about Arquillian, a test tool for web applications. In casu testing the persistence layer.
It's not yet clear to me what kind of testing Arquillian is supposed to do (unit or integration) but I'll definitely have a look soon.
Sunday, November 18, 2012
Day 2 - Devoxx 2012
SCALA ADVANCED CONCEPTS AND BEST PRACTICES
My personal favorite talk of Devoxx 2012. Presented by Dick Wall and Bill Venners; about more elaborate Scala stuff.
Implicits
An extremely powerful technique to define omnipresent objects; which are to be used when no regular object seems to be present.
Implicits are object instances marked as such - and used based on their types when the compiler fails to find an object of a certain type. Before the compiler reports an error, it will try to make a match with an implicit object that is in scope. If such an object is found, the compilation resumes. Otherwise it is aborted. This also means that the compiler will not use an implicit object if there's a regular object available.
As of Scala 2.10 you must import language.implicitConversion to enable this feature. And preferably use implicit classes.
Implicit conversion
A form of implicit object handling is implicit conversion. It tells the compiler you know how to convert a type of object to a different type of object.
implicit def str2int(str:String): Int = Integer.parseInt(str)
This statement defines a method telling the compiler, if need to be, how to convert a string to an integer. The name of the method is irrelevant. The input type is the type of the argument. And the target type is the type of the return argument.
Where it gets really interesting is when this feature allows for adding methods to existing classes. Without actually modifying those classes. But in the source code it has all apparences they are.
This little piece of code literally adds a volwelCount method to the String class.
class ExtendedString(original:String) {
val vowels = List('a','u','i','o','e')
def vowelCount:Int = original.count( vowels.contains(_) )
}
implicit def extString(str:String) = new ExtendedString(str)
Assuming the implicit is in scope, the following statement is a valid:
println( "abba".vowelCount )
It will yield 2 - as there are two vowels in the string "abba". And as long as the implicit is in scope java.lang.String will have this method available. Which is way better than defining external static utility methods.
As of Scala 2.10 however it is recommended to use implicit classes. The example from above would be rewritten as:
implicit class ExtendedString(original:String) {
val vowels = List('a','u','i','o','e')
def vowelCount:Int = original.count( vowels.contains(_) )
}
Prefix the class with implicit and don't define an implicit method. When the class comes in scope, the methods will be available.
Implicit parameters
A different way to use implicits is in method calls. Some parameters can be substituted by implicit values that are in scope when the method is called. The syntax uses a second set of parameters in the method definition.
def bar(foo: Foo)(implicit bar: Bar) = { ... }
Method calls to the aforementioned method need one Foo parameter. The Bar parameter is added by the compiler. Depending what implicit Bar value is in scope when calling the method. This is ideal for defining something as a context, a configuration or anything else we would need globally. In Java this would typically be a static ThreadLocal value.
Imported by default
- java.lang.*
- scala.*
- scala.Predef.*
Dynamic trait
Option
Scala's default way to cope with optional values is to define them as Option. From there they can be assigned a Some(value) or None. There is however no way to prevent from passing null values to even those.
Because Option is implemented as a collection (with at most one element) the value can be obtained with the usual collection processing methods. The advantage of doing so instead of checking for the presence of a value is that it would skip if the value is None.
Usage advice
- Try to make everything immutable. (remember Array is mutable !)
- Inside a method one might use mutable state. But never let anything immutable escape a method.
- Do not use null.
- There is no need to write any semi-colons any more.
- Let your ide work for you: if possible let it check for those nono's and color them accordingly.
- Use Option to indicate a value is optional.
- Know the usage of the for statement.
- Avoid foreach as this statement implicitly means there's a side effect somewhere.
- Let methods return Either for exception handling. By convention the left value is the exception and the right the expected value. Throwing exceptions the Java way is considered a non-FP practice.
- Know your collection types.
- Favor case classes for data transfer objects.
- Favor traits over classes.
- Do pattern matching instead of repetitive if/else/else/else.
- Learn the Scala annotations.
- You can check http://scalex.org/ for reference documentation.
FASTER WEBSITES: CRASH COURSE ON FRONTEND PERFORMANCE
Contrary to what the title suggests, this talk isn't about practical advice to make your web application faster. But rather, it's a in depth discussion of how much time is spent to what between the moment the client makes the request and the first response to it.
No doubt the speaker knows his stuff, but the session quickly derailed into an uninterrupted three hour verbal aggression about very low-level network techniques. So in the end I simply left the room.
Perceived response performance
- Fast: -100ms
- Sluggish: -300ms
- Slow: -1s
- Mental switch: +1s
- I'm out of here: +10s
The informal target is a 250ms response time.
Basic facts
- Much traffic are images. So try to reduce their size.
- Much time is spent in DNS lookups. So try to find the fastest for your area.
- Mobile network performance is today still much to be desired. 4G should bring some improvement to that. But that won't make older devices go away.
- Bandwidth is no longer a problem today. However, latency is.
- Browsers usually keep a connection pool of six connections open to pipeline their requests with.
- Older Linux kernels have a low initial TCP/IP packet size. This is improved simply by installing recent kernels.
- Better to disable TCP idle. It resets the initial packet sizing.
Google's SPDY "speedy" protocol
- Is supposed to boost HTTP 1.x performance.
- 1 connection
- Streamed requests
- Multiplexed
- Binary
- Prioritized request
- Uses TLS for encryption
- Already supported by recent versions of Chrome, Firefox and Opera.
- Already supported in number of Java application servers (ie Jetty, Tomcat, ...)
- The relation with web sockets.
- If there's a way to upgrade the http connection to SPDY if the browser is able to do so.
- W3C's Navigation-Timing specification.
TESTACULAR - SPECTACULAR TEST RUNNER FOR JAVASCRIPT
Testacular is a test runner for JS test code. That is, it runs test code of test frameworks. But isn't a test framework on its own. For the demo Jasmine was used.
- Fast & stable
- Runs using real browsers.
- Can run the same code on different browser windows. Making it easy to check visually for differences and errors.
- Can be started from Jenkins. But then it's headless.
To investigate after the conference:
- Any relationship with Selenium ?
JUNIT RULES
Rules are one of those lesser known features - yet powerful - of JUnit. A rule is defined at class level, using the Rule annotation. A typical use case is to use a rule to check the presence of an exception and the exception's message.
The principle is to let a rule wrap the calls to each test method. Allowing you to perform check before and after the method call. A possibility is to delete the contents of a database. Send an email. Etc...
Defining more than one rule wraps those rules into each other with the test method call at the bottom. The order of rule wrapping is undefined. Use RuleChain if the order is important.
For class-level rules use the annotation ClassRule.
Although the principle of rules is very straightforward, one should not underestimate its importance. Because where common testing code was added to tests using inheritance, rules allow now to add this by composition. Avoiding the multiple-inheritance problem entirely.
An example that comes to my mind is using Parameterized tests for Spring integration testing. Both require their own test runner. Unfortunately only one can be defined. There are ways around this with some hacking. However, the clean solution is to define a "Spring rule" to set up the application context before the test method is called. And shut it down again when the call has ended.
And voila ! Making the rule reusable to anywhere a Spring context is needed.
Day 1 - Devoxx 2012
FIRST STEPS WITH SCALA
A very interesting beginner's introduction to the Scala language. Presented by no less than Bill Venners and Dick Wall.
- Basic language features
- REPL demonstration with Sublime. REPL is the command-line, Scala shell environment. Ideal to experiment with the language.
- Because the Scala compiler does an awful lot of work, it is percieved as being slow. There is a practical solution to this however: The FSC (Fast Scala Compiler). Which is basically a background process doing the compiling for you. It caches a lot of work. The downside is that is needs loads of memory to run properly.
Things I didn't know before this talk
- Arrays are mutable. You better know this because Scala encourages you to program with immutable structures.
- The compiler will rewrite statements
- "f(1)" becomes "f.apply(1)"
- "f(1) = 2" becomes "f.update(1,2)"
- The collections of class List are linked lists. Ideal for head/tail processing of the collection.
- The Vector class is better suited for random access processing.
- The method ":::" concatenates lists.
- The method "::" is called cons.
- Nil is an empty list. As such the expression "a :: Nil" creates a list with one element.
- Unit is a singleton object.
- Different variables can be assigned with one statement. For example val (a,b) = (1,2) creates two variables, a and b, and assigns them respectively the values 1 and 2.
- Map.empty[type] creates an empty map of the given type.
I'd recommend watching the presentation on Parley's if you're intending to start with Scala. Made very entertaining by funny people.
HTML5 AND JAVASCRIPT WEB APPS
This presentation was a high-level overview of types of browser, devices and other diversity to expect for (mobile) web development. Although many a speaker shows of his/her book at the start of the talk, this speaker didn't miss an occasion to show it. Neither could we miss his JS library Slidfast.
The practical part of the presentation is really about how to use Slidfast to resolve certain practical problems.
- Although we've got many fantastic devices to run our web application on, there are still loads of less fantastic devices running too. Those need to be supported also.
- Offline usage should be thought about from the start. Not as an after thought.
- Battery usage is also a factor. Some software solutions actually consumes much battery power. So be careful with what you do.
- Browsers for mobile devices
- Webkit-based browsers on mobile:
- Safari (which works pretty well)
- Chrome (slightly less)
- Android (pretty bad)
- FireFox OS devices
- Opera Mini (renders screen on servers)
- Windows 8 / IE10
- Browsers for desktop devices
- Safari 5+
- Chrome 19+
- IE10+
- Opera 22+
- FireFox 12+
- Ergo : There is quite a big diversity of browsers and devices to thing about.
- Websockets is going to solve some latency problems bound to happen for a stateless protocol like HTTP.
- Webstorage is still experimental. That bad even that the performance currently depends of the syntax you use ! Syntax which might have a totally different performance profile on a different browser. Good to know is that the default maximum size is gross - it doesn't take the UTF16 encoding into account. Which means you have at least half less than is pretended.
- Geolocation comes in many sizes; is not part of HTML5. One of those forms is literally tracking the user's device location.
- PhantomJS demo - does load testing, headless browser and periodic screenshot report to check how fast the application renders.
To investigate after the conference
- Link prefetch
- HTML5 app cache
- PhantomJS
- Apply web sockets at work
HACKING THE JAVA COMPILER FOR FUN AND PROFIT
A brief introduction into compiler plugins for JDK8. The example is to modify the compiler to add the Elvis operator to the language. The compiler plugin will transform expressions into ternary conditions.
java -cvf <plugin>
Subscribe to:
Posts (Atom)