What Is CDI, How Does It Relate to @EJB And Spring?
Context Dependency Injection (CDI, JSR 299) is a part of Java EE 6 Web Profile and itself builds on Dependency Injection for Java (JSR 330), which introduces @Inject, @Named etc. While JSR 330 is for DI only and is implemented e.g. by Guice and Spring, CDI adds various EE stuff such as @RequestScoped, interceptors/decorators, producers, eventing and a base for integration with JSF, EJBs etc. Java EE components such as EJBs have been redefined to build on top of CDI (=> @Stateless is now a CDI managed bean with additional services).
A key part of CDI aside of its DI capabilities is its awarness of bean contexts and the management of bean lifecycle and dependencies within those contexts (such as @RequestScoped or @ConversationScoped).
CDI is extensible - you can define new context scopes, drop-in interceptors and decorators, make other beans (e.g. from Spring) available for CDI,... .
Resources to check:
Continue reading →
Book Review: Agile Project Management With Scrum
The book is basically a set of case studies about Scrum that show how to implement the individual aspects of Scrum, what are the common pitfalls and how to avoid them, and help to understand its mantra of "the art of the possible" and how to adapt Scrum to various situations. It's very easy to read thanks to the case studies being brief and organized by topics (team, product owner, ...). I'd absolutely recommend it as a third book in this domain, after a general introduction into the lean thinking (Implementing Lean Software Development – From Concept to Cash by M. & T. Poppendieck is great for that) and an introduction into Scrum itself. Scrum is not just a set of practices, it requires an essential shift in thinking. Thus it is not enough to learn about the practices - you have to learn, understand, and accept the principles behind. This book will hopefully help you to refine your understanding of these principles.
Extract
This extract contains the quotes and observations that I find the most interesting. It tries by no means to be objective or representative, a different person with a different experience and background would certainly pick different ones. Thus its value for others than myself is rather limited but it may perhaps serve as an inspiration to read the book. My all favourite quotes are in italics.Continue reading →
Groovy: Creating an Interface Stub and Intercepting All Calls to It
Continue reading →
Groovy: Use @Canonical to Get Compiler-generated Equals, HashCode and ToString
Continue reading →
Most interesting links of October
Recommended Readings
- Steve Yegge's Execution in the Kingdom of Nouns - I guess you've already read this one but if not - it is a well-written and amusing post about why not having functions as first class citizens in Java causes developers to suffer. Highly recommended.
- Reply to Comparing Java Web Frameworks - a very nice and objective response to a recent blog summarizing a JavaOne presentation about the "top 4" web frameworks. The author argues that based on number of resources such as job trends, StackOverflow questions etc. (however data from each of them on its own is biased in a way) JSF is a very popular framework - and rightly so for even though JSF 1 sucked, JSF 2 is really good (and still improving). Interesting links too (such as What's new in JSF 2.2?). Corresponds to my belief that GWT and JSF are some of the best frameworks available.
- Using @Nullable - use javax.annotation.Nullable with Guava's checkNotNull to fail fast when an unexpected null appeares in method arguments
- JavaOne 2011: Migrating Spring Applications to Java EE 6 (slides) - nice (and visually attractive) comparison of JavaEE and Spring and proposal of a migration path. It's fun and worthy to see.
- xUnitPatterns - one of the elementary sources that anybody interested in testing should read through. Not only it explains all the basic concepts (mocks, stubs, fakes,...) but also many pitfalls to avoid (various test smells such as fragile tests due to Data Sensitivity, Behavior Sensitivity, Overspecified Software [due to mocks] etc.), various strategies (such as for fixture setup), and general testing principles. The materials on the site were turned into the book xUnit Test Patterns: Refactoring Test Code (2007), which is more up-to-date and thus a better source.
- Eclipse tip: Automatically insert at correct position: Semicolon, Braces - in "while(|)" type "true {" to get "while(true) {|" i.e. the '{' is moved to the end where it belongs, the same works for ';'
- Google Test Analytics - Now in Open Source - introduces Google's Attributes-Components-Capabilities (ACC) application intended to replace laborous and write&forget test plans with something much more usable and quicker to set up, it's both a methodology for determining what needs to be tested and a tool for doing so and tracking the progress and high-risk areas (based not just on estimates but also actual data such as test coverage and bug count). The article is a good and brief introduction, you may also want to check a live hosted version and a little more detailed explanation on the project's wiki.
- JSF and Facelets: build-time vs. render-time (component) tags (2007) - avoid mixing them incorrectly
- StackOverflow: What are the main disadvantages of Java Server Faces 2.0? Answer: The negative image of JSF comes from 1.x, JSF 2 is very good (and 2.2 is expected to be just perfect :-)). Nice summary and JSF history review.
- Ola Bini: JavaScript in the small - best practices for projects using partly JavaScript - the module pattern (code in the body of an immediately executed function not to polute the global var namespace), handling module dependencies with st. like RequireJS, keeping JS out of HTML, functions generating functions for more readable code, use of many anonymous functions e.g. as a kind of named parameters, testing, open questions.
Continue reading →
JSF: Beware the Difference Between Build-Time and Render-Time Tags in Facelets
A typical mistake is the nesting of ui:include (build-time) inside ui:repeat (render-time) using the var that ui:repeat declares:
Continue reading →
Never Mix Public and Private Unit Tests! (Decoupling Tests from Implementation Details)
Continue reading →
Hacking A Maven Dependency with Javassist to Fix It
The process is as follows:
- Phase process-sources - maven-dependency-plugin unpacks the dependency to classes/
- Phase compile (implicit) - compile the bytecode manipulation code
- Phase process-classes - exec-maven-plugin executes the compiled Javassist instrumenter to modify the unpacked classes
- Phase test - run tests on the instrumented code
- Phase package - let maven-jar re-package the instrumented classes, excluding the instrumenter itself
Continue reading →
Comparison of Eclipse 3.6 and IntelliJ IDEA 10.5: Pros and Cons
For the impatient:
IntelliJ is a very good tool, its killing feature for me is its excellent support for other languages such as Groovy (e.g. for unit tests) and Clojure. Many details are more worked-out and with a higher usability then in Eclipse, f.ex. search & replace with match highlighting and replacement preview. Its support for navigability and refactoring across multiple languages (Java, JSP, JSF, HQL, Spring config in my case) is also an absolutely great feature for productivity. And of course I have to add it credits for being a Czech product [1] (interestingly enough, NetBeans also comes from the Czech Republic [2]; it's a pity Eclipse hasn't this link too) :-).
My main issue with IntelliJ is its performance. First, running tests is slow because IntelliJ only does (re)compile the test/source when you hit the run button as opposed to Eclipse' incremental compilation. And that makes TDD very painful. (I tried to use the old Eclipse Mode plugin but it has problems with IntelliJ 9/10.) Second, sometimes the UI freezes* and you have to wait seconds or tens of seconds for it to respond again (even after disabling most plugins and some analysis). It doesn't happen too often but often enough to be noticed, to be annoying, and to interrupt the development flow.
*) Update: UI freezes may be a specific issue of Mac 64b 1.6 JDK
So I guess I'll use either Eclipse or IntelliJ with respect to the needs of the project at hand and hope for IntelliJ to resolve its performance issues (as NetBeans did).
Continue reading →
Only a Masochist Would Write Unit Tests in Java. Be Smarter, Use Groovy (or Scala...).
I like writing unit tests but Java doesn't make it particularly easy. Especially if you need to create objects and object trees, transform objects for checking them etc. I miss a lot a conscise, powerful syntax, literals for regular expressions and collections, conscise, clojure-based methods for filtering and transforming collections, asserts providing more visibility into why they failed. But hey, who said I have to write tests in the same language as the production code?! I can use Groovy - with its syntax being ~ 100% Java + like thousand % more, optional usage of static/dynamic typing, closures, hundreds of utility methods added to the standard JDK classes and so on. Groovy support for example in IntelliJ IDEA (autocompletion, refactoring ...) is very good so by using it you loose nothing and gain incredibly much. So I've decided that from now on I'll only use Groovy for unit tests. And so far my experience with it was overwhelmingly positive (though few things are little more complicated by the positives more than compensate for them). Read on to find out why you should try it too.
(The arguments here focus on Groovy but I guess similar things could be said about JRuby, Scala etc. - with the exception of Java code compatibility, which you only get in Groovy.)
Few examples
Some of the example below use some Groovy magic but don't be scared. You can write Groovy just as if it was Java and only learn and introduce its magic step by step as you need it.Bean construction:
def testBean = new Customer(fname: "Bob", sname: "Newt", age: 42)
// Java: c = new Customer(); c.setFname("Bob"); c.setSname("Newt"); c.setAge(42);
(Of course this starts to pay of if either you don't want to create a constructor or if there are "many" properties and you need to set different subsets of them (constructor with 4+ arguments is hard to read).)
Reading a file:
assert test.method() == new File("expected.txt").getText()
// Java: buffered reader line by line ...; Note: == actually uses equals()
Checking the content of a collection/map:
assert customerFinder.findAll().collect {it.sname}.sort() == ["Lizard","Newt"]
// Java: too long to show here (extract only surnames, sort them, compare ...)
assert getCapitalsMap() == ["UK" : "London", "CR" : "Prague"]
Regular expressions:
assert ("dog1-and-dog2" =~ /dog\d/).getAt([0,1]) == ["dog1", "dog2"]
- Or more fail-safe regexp:
assert ("dog1-and-dog2" =~ /dog\d/).iterator().toSet() == ["dog1", "dog2"].toSet() - With a match group:
assert ("dog11-and-dog22" =~ /dog(\d+)/).iterator().collect({it[1]}).toSet() == ["11", "22"].toSet()
Continue reading →
Intro: Java Webapp Monitoring with Hyperic HQ + How to Alert on Too Many Errors in Logs
Continue reading →
Aggregating Error Logs to Send a Warning Email When Too Many of Them - Log4j, Stat4j, SMTPAppender
Continue reading →
hasProperty, the Hidden Gem of Hamcrest (and assertThat)
assertThat
Continue reading →
Spring: Make an Externally Created Object Available to Beans in applicationContext.xml
Java: Configure ApplicationContext with an Injected Bean
Continue reading →
Tools for Renaming the Package of a Dependency with Maven
- Uberize plugin (latest - org.fusesource.mvnplugins:maven-uberize-plugin:1.20) - originally inspired by the Shade plugin, intended to overcome some of its limitations. Intended primarily to merge your code and dependencies into one jar.
- Shade plugin
- package-rename-task, Ant-based Maven plugin - I'm not sure whether this is further maintained
Continue reading →