<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-465312893224516648</id><updated>2011-07-29T00:17:13.451-07:00</updated><title type='text'>Flexing Your Code</title><subtitle type='html'>A blog on development and design patterns</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>17</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-5791318534558718663</id><published>2010-07-09T11:44:00.000-07:00</published><updated>2010-09-03T08:49:26.333-07:00</updated><title type='text'>Blistering Pace Development using: DDD, DI, AOP, AGILE and some CLEAN CODE</title><content type='html'>I recently managed and jointly developed a system which evolved into the culmination of several methodologies and practices.&amp;nbsp;We were severely short-staffed being a band of 3 and weren't the&amp;nbsp;strongest technical team either.&lt;br /&gt;&lt;div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"&gt;&lt;br /&gt;Managing this group proved to be a challenge, and i had to pull out a few improvisations and tricks&lt;/div&gt;&lt;div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"&gt;to get the team to work together effectively and efficiently. Being a true techie at heart, management is the last thing i prefer to do, yet the team decided i should ... and i was dubbed.&lt;/div&gt;&lt;br /&gt;We chose to follow the ICONIX process, which proved to fit in well with achieving a domain-driven-design.&lt;br /&gt;More disciplined than XP and in some cases reminded me of my Waterfall experience. Yet very iterative in nature and yet we were able to produce a system at a&amp;nbsp;blistering&amp;nbsp;pace.&amp;nbsp;&amp;nbsp;Needless to say this post will be on my reflection on our technical achievements while understaffed and not on any particular process.&lt;br /&gt;I'm convinced&amp;nbsp;that a process is not a SILVER BULLET at all, in fact i believe a process should only facilitate the quest a team&amp;nbsp;decides to undertake. I'ts like an adventure with Robin Hood or the Three Muskateers,&lt;br /&gt;you decide which road to undertake, the process only facilitates to keep marble under your feet.&lt;br /&gt;&lt;br /&gt;The first essential component to speeding up development was to understand the problem correctly.&lt;br /&gt;Placing things into context and building a &lt;b&gt;common understanding of the problem with your client&lt;/b&gt; was&lt;br /&gt;the first requirement. Below is an excerpt from a write-up I recently made ... i added it since it captures&lt;br /&gt;the gist of what i think a DDD should accomplish.&lt;br /&gt;&lt;br /&gt;"In the pursuit of a proper solution for a problem, the problem to address needs&lt;br /&gt;to be understood correctly and thoroughly. An incorrect comprehension of a&lt;br /&gt;problem domain could degrade an otherwise elegant solution to become substandard.&lt;br /&gt;Consequently, placing software requirements in context of the real&lt;br /&gt;world is an essential exercise.&lt;br /&gt;By expressing real world phenomena within a software application itself not&lt;br /&gt;only aligns it closer to the needs and requirements of a client, but also assists&lt;br /&gt;in the establishment of a ubiquitous language amongst different stake-holders.&lt;br /&gt;A software construct not only communicates directly to a machine, but also&lt;br /&gt;serves as a platform for communication amongst developers and future maintainers&lt;br /&gt;of a system. A software construct that utilize a glossary build from an&lt;br /&gt;established ubiquitous language would not only serve its purpose as an interface&lt;br /&gt;between developer and machine, but also increase effective communication&lt;br /&gt;between developer and client." - Michael (2010)&lt;br /&gt;&lt;br /&gt;The second requirement to achieve blistering pace development was to establish&lt;br /&gt;similar collaboration and mutual understanding amongst the team members. Sure&lt;br /&gt;enough a DDD will assist, but more is required. A &lt;b&gt;common understanding of high-level design and&lt;/b&gt;&lt;br /&gt;&lt;b&gt;architecture &lt;/b&gt;keeps everyone in the loop. We have vision, we all know where we're heading.&lt;br /&gt;A visual representation of your vision whether it be an&amp;nbsp;architectural&amp;nbsp;view or a couple of robustness analysis&lt;br /&gt;diagrams stimulates creativity ... put your PC aside ... to achieve a great design requires lateral thinking&lt;br /&gt;and developers that are kept in the loop. A developer's feedback keeps everyone in touch of technical&lt;br /&gt;feasibility and estimates (some design might be easy for us to implement, it does not however imply that the individual tasked with that design would find it easy... u need to put design in context of technical abilities).&lt;br /&gt;A complex design might be highly modifiable and flexible, yet a simpler solution&lt;br /&gt;could take far quicker and easier to accomplish technically. Yes we all know developers can give&lt;br /&gt;management the moon, however&amp;nbsp;that&amp;nbsp;doesn't imply we'll have the moon ready for you next month !!&lt;br /&gt;My answer, cut off what you can early on but don't neglect the domain. Whatever you do above all else,&lt;br /&gt;&amp;nbsp;KEEP YOUR DOMAIN LAYER UP TO DATE !!!&lt;br /&gt;Tackling business complexity is highest priority, technical extensions are easy to add later on. Of course establishing a commonly understood technical language by naming new design patterns and old ones alike, assist in establishing a ubiquitous "techie" language.&lt;br /&gt;&lt;br /&gt;The third requirement to achieve blistering pace was to&amp;nbsp;&lt;b&gt;streamline technicalities&lt;/b&gt;.&lt;br /&gt;Infrastructure and interface code we've all written over and over and over again.&amp;nbsp;Surely we can encapsulate that recurring pattern, it will save soooo much time.&amp;nbsp;My answer to this is the culmination of frameworks, dependency injection and aspects.&amp;nbsp;Choosing your framework is critical, don't fall into a trap hole.&lt;br /&gt;Some frameworks give excellent speed-ups at first but severely limit flexibility later on.&lt;br /&gt;IMHO a framework should provide support&amp;nbsp;for some kind of DI though.&amp;nbsp;Delegation and strategies are just so much easier to accomplish using DI, and the best part is that it keeps code clean, which of course is my next point.&lt;br /&gt;&lt;br /&gt;Writing clean code is essential to increase maintainability and progress.&amp;nbsp;A code base that is self explanatory is much easier to follow and extend than a mesh of spaghetti.&amp;nbsp;By avoiding puddles of mud you save multitudes of wasted brain cycles trying to grasp context of surrounding code, and facilitate focus on expressions of system behaviour instead.&lt;br /&gt;Aspects is an effective way to delineate boundaries and enforce code policies or conventions.&lt;br /&gt;Why use static analysis tools in a continuous integration system while you could have prevented it @ code time using aspects instead ? Time savers like that and pragmatic approaches to solving difficult hurdles just help so much in the long run. Of course one should not neglect conventional tools and methodologies like continuous integration, test driven development, test \ production environments, effective development environments (IDE, screen multiplicity, pc performance, spreadsheet timers, build tools and so on etc. etc. etc. they all assist to speed up development bit-by-bit.&amp;nbsp;Standardization&amp;nbsp;on tools also help, but watch out not to stifle creativity in the process. Too much red tape is not a nice atmosphere to work in (well that's valid for me, others might experience it differently).&lt;br /&gt;&lt;br /&gt;And then there was the final ingredient required for achieving blistering speed. I know this post shouldn't be about the process, but yet it's so crucial. A great process applied incorrectly steers you off the marble road, instead of keeping you on it !! I would group the chosen process, the technical abilities and skills of the team and the developer-client relationship into a big bag called the &lt;b&gt;X-Factor&lt;/b&gt;. Why do i do that ? Well everything in this bag depends on everything else. You see, it all depends, and it's an art to establish which process would fit your circumstances and which not. Sure enough you could have on your team one or more star programmers, but there's not such&amp;nbsp;caliber of highly skilled developers lurking everywhere and on every corner. Besides, what are the odds that your entire team consists of gurus and you've got this great big budget to support your adventures. Well if you work for Apple or Microsoft, maybe, but for the rest of us you'll need to improvise, adapt. And that's why i'm not going to go into detail with this last requirement ...&lt;br /&gt;&lt;br /&gt;And those are the things we did as a team. It worked out very well in the end and the exercise was extremely productive.&amp;nbsp;I'm not advocating that an iterative process and a pragmatic approach toward effective&lt;br /&gt;development is the conclusive answer for shipping products faster, but i think that all these elements are essential&amp;nbsp;in achieving that purpose. With a thorough understanding of the problem, by avoiding analysis paralysis, improving team communication and effectively modelling the business domain did speed up delivery manifold in our case.&lt;br /&gt;&lt;br /&gt;Anyway, that's my post for July. Been a while but at least still alive ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-5791318534558718663?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/5791318534558718663/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=5791318534558718663' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5791318534558718663'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5791318534558718663'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2010/07/blistering-pace-development-using-ddd.html' title='Blistering Pace Development using: DDD, DI, AOP, AGILE and some CLEAN CODE'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-4147590149061694448</id><published>2010-05-07T16:08:00.000-07:00</published><updated>2010-05-11T16:23:20.885-07:00</updated><title type='text'>Code Mess: Is research a culprit ?</title><content type='html'>Sure enough, code affects the quality of other code. &lt;br /&gt;&lt;blockquote&gt;"If he didn't care why should I ?"&lt;/blockquote&gt;But ... could current research be encouraging it ? &lt;br /&gt;&lt;br /&gt;I attended the last day of ICSE Cape Town today, and was horrified to find new developments to assist in understanding poorly written code. A code summarizer could help us in navigating large code piles, but should it be used to understand poorly written code too ?&lt;br /&gt;&lt;br /&gt;I believe we're suppose to learn from mistakes, and not neglect its consequences. Understanding the consequences of a poor choice, give us a reason for making a better decision next time. How could we ever fully comprehend the reason for doing things differently, if we ignore the repercussions ? &lt;br /&gt;&lt;br /&gt;What did I do last time ? What is my next step again ? Ohh cum on ... what was I thinking ?&lt;br /&gt;Questions like these arise&amp;nbsp;either&amp;nbsp;because:&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;You neglected to write your ideas down. Or...&lt;/li&gt;&lt;li&gt;You wrote such a complicated mesh of spaghetti code, you got lost in your own puddle of mud.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;I conform to a different idea...&lt;br /&gt;I believe code should be written so expressive that its intent is understood with ease. &lt;br /&gt;&lt;br /&gt;&lt;b&gt;Too many classes to navigate ? &lt;/b&gt;&lt;br /&gt;How does the package structure look like ? Are the class names clear  ? Have you used common patterns to express yourself ?&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Maybe the application is becoming too large ?&lt;/b&gt; &lt;br /&gt;You could decompose your app into smaller modules using OSGi, compile different apps and have them communice using web services, or consider using a service bus.&lt;br /&gt;&lt;br /&gt;There's a reason for software nuasence. It's implying that we find a more elegant solution, a better implementation.&lt;br /&gt;Simple manual tasks like appending different text files, or capturing data from documents into objects can be automated.&lt;br /&gt;There's a reason many developers are  called lazy, we don't want to continually repeat ourselves.&lt;br /&gt;Many would use an automation tool when faced with the perils of repeating tasks.&lt;br /&gt;&lt;br /&gt;The same applies to poor code. If a developer understands the pain, he should be able to understand the reason for cleaner code. He will start appreciating elegant solutions. Some might cultivate an affinity toward the art of expression.&lt;br /&gt;Some learn, some don't, but most would learn that  hacking away doesn't help in achieving the deadline.&lt;br /&gt;&lt;br /&gt;Code summarizers are great tools, but will it cause us to be lazy for the WRONG reasons. Spending that extra few seconds finding an expressive name, used to pay off and be respected. Are we solving the pain and avoiding the cause ? &lt;br /&gt;&lt;br /&gt;You used to find yourself refactoring an unmaintainable code base. Will a code summarizer allow us to comprehend garbage faster and give us a reason to lazily give garbage back ?&lt;br /&gt;Maybe the answer is not the research, nor the technology its based on, not even the code itself.&lt;br /&gt;&lt;br /&gt;Expression is an art, and the artist will continually review his creations until it achieves its cause.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-4147590149061694448?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/4147590149061694448/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=4147590149061694448' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/4147590149061694448'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/4147590149061694448'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2010/05/code-mess-is-research-culprit.html' title='Code Mess: Is research a culprit ?'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-3591392301183017851</id><published>2010-02-15T12:17:00.000-08:00</published><updated>2010-02-15T15:51:44.803-08:00</updated><title type='text'>Maintainable Code</title><content type='html'>&lt;span style="font-weight: bold;font-size:150%;" &gt;&lt;b&gt;What is it ?&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;Writing something useful for your fellow programmers.&lt;br /&gt;Code that is easily understood and is self-explanatory (the intent should be obvious).&lt;br /&gt;A good approximation of where future enhancements will occur (you'll need a holistic view of the system for this one).&lt;br /&gt;Design patterns used in the right places and at the right times.&lt;br /&gt;Code that is efficient, ROBUST and elegant. Elegance improves and stimulates creativity.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:150%;" &gt;&lt;b&gt;The benefits.&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;It flattens the cost curve of your project. The projects' viability affects everyone.&lt;br /&gt;Saves a lot of frustration and unproductive hours. &lt;br /&gt;Eliminates ambiguous rules and the possibility of wrong interpretations. No "guessing" work. &lt;br /&gt;Less time spend on poorly written constructs, more time spend on creative solutions.&lt;br /&gt;Improves your reputation. The code you write is your legacy.&lt;br /&gt;Saves a lot of wasted "development time". You've got a plan, and your code is evolving toward its intended design. Less time spend on rework and re-factoring.&lt;br /&gt;Better adapts to changing client requirements.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:150%;" &gt;&lt;b&gt;How do I get there ?&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;Good place to start is the essence of your program, the code itself.&lt;br /&gt;I am a firm believer of using &lt;b&gt;meaningful&lt;/b&gt; variable names. &lt;br /&gt;I try to write code like a poet would, we're writing a story after all.&lt;br /&gt;Simple example:&lt;br /&gt;&lt;pre name="code" class="java"&gt;if ((ivar == 3) &amp;&amp; !(username == 'Tsepo') &amp;&amp; !(username == 'Mandla')) {&lt;br /&gt;// ....&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;What does that mean ?!? Why are we excluding 'Tsepo' and 'Mandla' ?&lt;br /&gt;And what does 'ivar' represent, and when is the state 3 ? &lt;br /&gt;Simply put, nobody knows what this construct is trying to accomplish.&lt;br /&gt;&lt;br /&gt;Here is the same construct reworked:&lt;br /&gt;&lt;pre name="code" class="java"&gt;if (isValidUser(username)) {&lt;br /&gt;// ....&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Now that's a lot clearer, and it makes sense. &lt;br /&gt;That would be my first rule of writing sensible, maintainable code.&lt;br /&gt;&lt;span style="font-weight: bold; color: rgb(51, 204, 0);" &gt;Group logic into their appropriate blocks or paragraphs.&lt;/span&gt;&lt;br /&gt;The same rule applies to function arguments. More than 2 arguments makes&lt;br /&gt;the function increasingly difficult to understand or comprehend.&lt;br /&gt;&lt;br /&gt;If you end up having too many function arguments it either means:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;You didn't apply object orientation correctly or thoroughly enough.&lt;/li&gt;&lt;li&gt;If you're not able to group argument state in an appropriate class, you might want to consider the Builder pattern.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;The same goes for selector arguments. Like the one below to calculate the final result of a student:&lt;br /&gt;&lt;pre name="code" class="java"&gt;public int calculateFinalResult(boolean fullTime) {&lt;br /&gt;// ...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;At the time there might only be two conditions for a student 'full time' and 'part time' fulfilling the boolean requirement. However, later we might want to add combined states like 'repeater part time', 'repeater full time' or even more elaborate states like 'part time repeater with disabilities'. All the different states implies different rules for computing a student's final result. A student with disabilities might be graded differently than others.&lt;br /&gt;&lt;br /&gt;We could add more parameters to the function as necessary (repeater - first time) or pass an enum to clarify all possible disabilities. That's a bad idea. The more conditions and enumerations are passed as arguments, the larger, more complex and intricate the function becomes. It's better to keep functions focusing on a single task each (Single Responsibility Principle).&lt;br /&gt;&lt;br /&gt;Surely the arguments exemplify dynamic behaviour, and from my previous post on design patterns &lt;a href="http://flexingcode.blogspot.com/2009/02/how-to-discover-new-design-pattern.html"&gt;&lt;/a&gt;&lt;br /&gt;we would like to dis-entangle this "dynamic" logic from our code base.&lt;br /&gt;&lt;br /&gt;The result; several smaller functions that are more flexible, easier to maintain and extend. The extracted functions might look something like this:&lt;br /&gt;&lt;pre name="code" class="java"&gt;public Result calculateFinalResult(SubjectResults results) {&lt;br /&gt;// ...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;pre name="code" class="java"&gt;public SubjectResults buildSubjectResults() {&lt;br /&gt;// ...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;The second rule I would call aesthetic finishing.&lt;br /&gt;&lt;span style="font-weight: bold; color: rgb(51, 204, 0);" &gt;Make it readable, understandable and beautiful.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;That would include the following:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Writing sensible and useful comments. &lt;br /&gt;That is, avoid tight coupling comments to your code base (refer to concepts, ideas and theorems instead of implementation details).&lt;/li&gt;&lt;li&gt;Deleting redundant code and comments the moment you find them.&lt;/li&gt;&lt;li&gt;Using clear and understandable names. The length of names are coupled to its scope, large functions will have longer names. Useful hint: whenever you have a conjunction in your name it probably gestures a violation of the SRP principle. E.g. A function with name calculateAndEmailFinalResult() is doing more than one task, in fact it calculates &lt;b&gt;AND&lt;/b&gt; emails the result.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Finally, the last part: &lt;br /&gt;&lt;span style="font-weight: bold; color: rgb(51, 204, 0);" &gt;Make it easily extend-able and reusable.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Identify points in the code base that are currently duplicated or bound to change frequently from changing requirements.&lt;br /&gt;&lt;br /&gt;Changing requirements are either still immature or very visual to the client.&lt;br /&gt;If requirements are still under an early stage of development and unclear, its bound to change sometime in the future. &lt;br /&gt;&lt;br /&gt;The visual parts of the system can be made more maintainable by utilizing the MVP, MVC or similar "separation of logic" pattern [see &lt;a href="http://flexingcode.blogspot.com/2009/06/test-driving-swing.html"&gt;&lt;/a&gt;].  &lt;br /&gt;&lt;br /&gt;The unclear requirements can be catered for, by using a strong object-oriented approach and useful design patterns. Writing clean and understandable code also makes re-factoring easier.&lt;br /&gt;It's very important to make ample use of tests in such a scenario. Since you'll be doing a lot of re-factoring you want functionality BEHAVIOUR to remain the same in unaffected parts of your system.&lt;br /&gt;&lt;br /&gt;If requirements are changing so often, you can hardly keep up, it might be wise to re-examine the software process model you're using for the project. You're model would lie somewhere between the more Crafted (Agile methodologies) towards the more Controlled models (E.g. Waterfall process). Choosing the perfect model depends on the environment, size of the project and organisation, the level of skills available, deadlines, market conditions, internal politics, external forces like our current recession and many others ... But all that is due for a separate post on its own.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:150%;" &gt;&lt;b&gt;Further reading&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;Structure, aesthetics and flexibility. That sums up todays post.&lt;br /&gt;&lt;br /&gt;For further information on:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Aesthetics: Clean Code, by Robert C. Martin; [ A real code-changing experience, highly recommend, also contains very useful smells &amp; heuristics list in appendix. ]&lt;/li&gt;&lt;li&gt;Flexibility: Head First Design Patterns [ An easy read, a good introduction to the world of patterns. ]&lt;br /&gt;Elements of Reusable Object-Oriented Software [An old time classic.]&lt;br /&gt;Head First OOA&amp;D [An easy intro to object orientation. ]&lt;/li&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-3591392301183017851?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/3591392301183017851/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=3591392301183017851' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/3591392301183017851'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/3591392301183017851'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2010/02/maintainable-code.html' title='Maintainable Code'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-2395888246390868222</id><published>2009-06-04T01:04:00.000-07:00</published><updated>2009-06-04T02:34:35.838-07:00</updated><title type='text'>Test Driving Swing</title><content type='html'>Recently I ended up test driving the front-end for my SCJD project. The easiest way to test drive a view technology, such as Swing, would be to move as much logic (business and view related) from your view as possible.&lt;br /&gt;&lt;br /&gt;Why do I say that? The thinner and simpler a view is, the easier it is to test. The model-view-presenter architectural pattern by Martin Fowler does just that. I have to note that, the model-view-presenter now comes in two major forms "The passive view" and the "Supervising controller" patterns, with several other variations out there. &lt;br /&gt;&lt;br /&gt;Anyway, I decided to use the "Supervising Controller" pattern with Abbot as my testing framework. The "passive view" seemed a bit "overkill", and I humbly acknowledge that it's still a pattern that I don't "get" at the moment ... haha.&lt;br /&gt;&lt;br /&gt;The mvp works somewhat like this:&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SieHnKh0CeI/AAAAAAAAADI/ZUEEIF0hsIE/s1600-h/model_view_presenter_small.bmp"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 320px; height: 309px;" src="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SieHnKh0CeI/AAAAAAAAADI/ZUEEIF0hsIE/s320/model_view_presenter_small.bmp" border="0" alt=""id="BLOGGER_PHOTO_ID_5343388589809207778" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;This leaves us with only two transitions to test, numbers (1) and (3). Transition (2) is not something we'll test. It's not contained in the view layer and would most probably be a call to some underlying service method. This service method would be tested separately. So we can create a mock object of the service method, assuming that it would perform the business logic correctly.&lt;br /&gt;&lt;br /&gt;The two distinct tests we need to perform on the view are:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Test that the listener is working correctly (transition 1)&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Test that the view's update method is working correctly (transition 2)&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Sure, we could also test the layout, color, and font-size as well. But those things change all the time... Updating tests every time a cosmetic change is made, is just a royal waste of time. In my opinion, it's better to test the underlying "functionality" of your view. A back button that's not working is a horrible bug YOU DON'T WANT TO MAKE !!&lt;br /&gt;&lt;br /&gt;To test the listener, I created a test-double. My view interface looks like this:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public interface ContractorSearchView {&lt;br /&gt;&lt;br /&gt; void registerSearchListener(ContractorSearchListener listener);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Remember, code to interfaces not implementations!! The listener interface looks like this:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public interface ContractorSearchListener {&lt;br /&gt;&lt;br /&gt; public void searchCriterionAdded(String criterion);&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I started my test class by implementing the search listener, thus acting as a test double:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public class TestContractorSearchViewEventListener extends AbstractContratorTestFramework&lt;br /&gt;  implements ContractorSearchListener {&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The abstract test framework was something I wrote to ease the testing ... &lt;br /&gt;It provides methods for creating mock data to simulate my tests with. However, in the end it's just an extension of the Abbot testing framework:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public abstract class AbstractContratorTestFramework extends AbstractSwingTestFramework&lt;br /&gt;&lt;br /&gt;public abstract class AbstractSwingTestFramework extends ComponentTestFixture&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As my test class was implementing the searchListener interface, I had to implement the following method:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; private String addedSearchCriterion;&lt;br /&gt; &lt;br /&gt; public void searchCriterionAdded(String criterion) {&lt;br /&gt;  addedSearchCriterion = criterion;&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To set it all up, I had to create an implementation of the view interface, instantiate it, and then add my test class as the listener to it.&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; @Override&lt;br /&gt; protected void setUp() throws Exception {&lt;br /&gt;  super.setUp();&lt;br /&gt;  addedSearchCriterion = null;&lt;br /&gt;  ContractorSearchViewImplementation view = new ContractorSearchViewImplementation();&lt;br /&gt;  view.registerSearchListener(this);&lt;br /&gt;  showFrame(view);&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I then wrote my test case:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; public void testSearchEventGetsTriggered() throws Exception {&lt;br /&gt;  // Given a search value is entered&lt;br /&gt;  String criterion = "Search Me";&lt;br /&gt;  typeIntoTextField("search_textfield", criterion);&lt;br /&gt;  System.gc();&lt;br /&gt;  &lt;br /&gt;  // When the search button is clicked&lt;br /&gt;  getTester().actionClick(namedComponent("search_button"));&lt;br /&gt;  &lt;br /&gt;  // Then expect the registered listener to receive the event&lt;br /&gt;  assertEquals(criterion, addedSearchCriterion);&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The getTester() and typeIntoTextField(...) are helper methods I wrote that use the underlying Abbot framework. They're declared in the super class of my custom &lt;span style="font-style:italic;"&gt;AbstractContratorTestFramework&lt;/span&gt;.  &lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public abstract class AbstractSwingTestFramework extends ComponentTestFixture {&lt;br /&gt;&lt;br /&gt; private ComponentTester tester = new ComponentTester();&lt;br /&gt; &lt;br /&gt; protected ComponentTester getTester() {&lt;br /&gt;  return tester;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; protected void typeIntoTextField(String name, String value) throws Exception {&lt;br /&gt;  tester.actionKeyString(namedComponent(name), value);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; protected Component namedComponent(String name) throws Exception {&lt;br /&gt;  return getFinder().find(new NameMatcher(name));&lt;br /&gt; } &lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Of course the test didn't pass first time round, and I had to add some components in the view implementation...&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public class ContractorSearchViewImplementation extends JPanel implements ContractorSearchView {&lt;br /&gt;&lt;br /&gt; private static final long serialVersionUID = 5752335740287943677L;&lt;br /&gt; private ContractorSearchListener searchListener;&lt;br /&gt; private JTextField searchField;&lt;br /&gt; private JButton searchButton;&lt;br /&gt;&lt;br /&gt; public ContractorSearchViewImplementation() {&lt;br /&gt;  createWidgets();&lt;br /&gt;  add(searchField);&lt;br /&gt;  add(searchButton);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private JButton createWidgets() {&lt;br /&gt;  searchField = createTextField("search_textfield");&lt;br /&gt;  searchButton = new JButton();&lt;br /&gt;  searchButton.setName("search_button");&lt;br /&gt;  searchButton.addActionListener(new ActionListener() {&lt;br /&gt;   public void actionPerformed(ActionEvent event) {&lt;br /&gt;    String criterion = searchField.getText();&lt;br /&gt;    searchListener.searchCriterionAdded(criterion);&lt;br /&gt;   }   &lt;br /&gt;  }&lt;br /&gt;  );&lt;br /&gt;  return searchButton;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private JTextField createTextField(String name) {&lt;br /&gt;  JTextField field = new JTextField();&lt;br /&gt;  field.setName(name);&lt;br /&gt;  return field;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void registerSearchListener(ContractorSearchListener listener) {&lt;br /&gt;  this.searchListener = listener;&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Testing transition (2) or the view's update method, ended up being a little trickier.&lt;br /&gt;The tricky part was that, I was using a table to display my search results. So I had to re-render / refresh my JTable every time the model was updated.&lt;br /&gt;Thankfully Swing has a method that redraws the JTable if its data changed, the &lt;span style="font-style:italic;"&gt;fireTableDataChanged()&lt;/span&gt; event...&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; public void updateSearchResults(List&lt;Contractor&gt; searchResults) {&lt;br /&gt;  ContractorTableModel tableModel = (ContractorTableModel) searchResultsTable.getModel();&lt;br /&gt;  tableModel.setData(searchResults);&lt;br /&gt;  tableModel.fireTableDataChanged();&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;My complete test class for testing the view's update method looked like this:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public class TestContractorSearchViewModelUpdate extends AbstractContratorTestFramework {&lt;br /&gt; &lt;br /&gt; private ContractorSearchViewImplementation view;&lt;br /&gt; private JTable resultsTable;&lt;br /&gt; &lt;br /&gt; protected void setUp() throws Exception {&lt;br /&gt;  super.setUp();&lt;br /&gt;  resultsTable = null;&lt;br /&gt;  view = new ContractorSearchViewImplementation();&lt;br /&gt;  showFrame(view);&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public void testSearchResultsUpdated() throws Exception {&lt;br /&gt;  // Given a list of search results&lt;br /&gt;  List&lt;Contractor&gt; searchResults = new ArrayList&lt;Contractor&gt;();&lt;br /&gt;  searchResults.add(returnMockContractor_IT());&lt;br /&gt;  searchResults.add(returnMockContractor_PLUMBING());&lt;br /&gt;  &lt;br /&gt;  // When the update method on view is called&lt;br /&gt;  view.updateSearchResults(searchResults);&lt;br /&gt;  System.gc();&lt;br /&gt;  &lt;br /&gt;  // Then the expected results should be displayed&lt;br /&gt;  resultsTable = (JTable) namedComponent("results_table"); &lt;br /&gt;  assertITContractor();&lt;br /&gt;  assertPlumbingContractor();&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; private void assertITContractor() {&lt;br /&gt;  int rowIndexForITcontractor = 0;&lt;br /&gt;  Contractor ITContractor = returnMockContractor_IT();&lt;br /&gt;  assertEquals(ITContractor.getName(), returnDisplayedContractorNameAtRow(rowIndexForITcontractor));&lt;br /&gt;  assertEquals(ITContractor.getLocation(), returnDisplayedContractorLocationAtRow(rowIndexForITcontractor));&lt;br /&gt;  assertEquals(ITContractor.getHourlyCharge(), returnDisplayedContractorHourlyRateAtRow(rowIndexForITcontractor));&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private void assertPlumbingContractor() {&lt;br /&gt;  int rowIndexForPlumbingContractor = 1;&lt;br /&gt;  Contractor PlumbingContractor = returnMockContractor_PLUMBING();&lt;br /&gt;  assertEquals(PlumbingContractor.getName(), returnDisplayedContractorNameAtRow(rowIndexForPlumbingContractor));&lt;br /&gt;  assertEquals(PlumbingContractor.getLocation(), returnDisplayedContractorLocationAtRow(rowIndexForPlumbingContractor));&lt;br /&gt;  assertEquals(PlumbingContractor.getHourlyCharge(), returnDisplayedContractorHourlyRateAtRow(rowIndexForPlumbingContractor));&lt;br /&gt; } &lt;br /&gt; &lt;br /&gt; private String returnDisplayedContractorNameAtRow(int rowIndex) {&lt;br /&gt;  return (String) resultsTable.getModel().getValueAt(rowIndex, ContractorTableColumn.NAME_COLUMN.getCode());&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private String returnDisplayedContractorLocationAtRow(int rowIndex) {&lt;br /&gt;  return (String) resultsTable.getModel().getValueAt(rowIndex, ContractorTableColumn.LOCATION_COLUMN.getCode());&lt;br /&gt; } &lt;br /&gt; &lt;br /&gt; private Double returnDisplayedContractorHourlyRateAtRow(int rowIndex) {&lt;br /&gt;  return (Double) resultsTable.getModel().getValueAt(rowIndex, ContractorTableColumn.HOURLY_CHARGE_COLUMN.getCode());&lt;br /&gt; } &lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;With my view's implementation like so...&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public class ContractorSearchViewImplementation extends JPanel implements ContractorSearchView {&lt;br /&gt;&lt;br /&gt; private static final long serialVersionUID = 5752335740287943677L;&lt;br /&gt; private ContractorSearchListener additionListener;&lt;br /&gt; private JTextField searchField;&lt;br /&gt; private JButton searchButton;&lt;br /&gt; private JTable searchResultsTable;&lt;br /&gt; &lt;br /&gt; public ContractorSearchViewImplementation() {&lt;br /&gt;  createWidgets();&lt;br /&gt;  add(searchField);&lt;br /&gt;  add(searchButton);&lt;br /&gt;  add(searchResultsTable);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private JButton createWidgets() {&lt;br /&gt;  searchField = createTextField("search_textfield");&lt;br /&gt;  searchResultsTable = createJTable("results_table");&lt;br /&gt;  searchButton = new JButton();&lt;br /&gt;  searchButton.setName("search_button");&lt;br /&gt;  searchButton.addActionListener(new ActionListener() {&lt;br /&gt;   public void actionPerformed(ActionEvent event) {&lt;br /&gt;    String criterion = searchField.getText();&lt;br /&gt;    additionListener.searchCriterionAdded(criterion);&lt;br /&gt;   }   &lt;br /&gt;  }&lt;br /&gt;  );&lt;br /&gt;  return searchButton;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; private JTable createJTable(String name) {&lt;br /&gt;  JTable table = new JTable(createTableModel());&lt;br /&gt;  table.setName(name);&lt;br /&gt;  return table;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private JTextField createTextField(String name) {&lt;br /&gt;  JTextField field = new JTextField();&lt;br /&gt;  field.setName(name);&lt;br /&gt;  return field;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; private TableModel createTableModel() {&lt;br /&gt;  ContractorTableModel tableModel = new ContractorTableModel();&lt;br /&gt;  return tableModel;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public void registerSearchListener(ContractorSearchListener listener) {&lt;br /&gt;  this.additionListener = listener;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void updateSearchResults(List&lt;Contractor&gt; searchResults) {&lt;br /&gt;  ContractorTableModel tableModel = (ContractorTableModel) searchResultsTable.getModel();&lt;br /&gt;  tableModel.setData(searchResults);&lt;br /&gt;  tableModel.fireTableDataChanged();&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It's important to remember that we only tested the two transitions that effect the view, namely transition (1) and transition (3). The next step would be to test the presenter and then the service method used to retrieve/update the results.&lt;br /&gt;&lt;br /&gt;But how does the presenter fit into the entire picture? Well as its constructor the presenter would take two arguments. One would be the view you're updating, the other would be the model object received from the view (if no data capturing took place, then the model would be the same from the last call to the view's update method).&lt;br /&gt;&lt;br /&gt;The presenter then adds the listener to the view object. Important... there is no concrete implementation for the listener, it's created inside the presenter as an anonymous inner class.&lt;br /&gt;&lt;br /&gt;Then whenever an event occurs, the presenter invokes the service method, and then makes a call to the view's update method, to update itself with the latest data.&lt;br /&gt;To end off, here's an example of how it's done. In this scenario I had no data to update from my view, I merely needed to display search results given the passed criteria...&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public class ContractorSearchPresenter {&lt;br /&gt;&lt;br /&gt; private ContractorService contractorService;&lt;br /&gt; private ContractorSearchView contractorSearchView;&lt;br /&gt; private List&lt;Contractor&gt; searchResults;&lt;br /&gt; &lt;br /&gt; public ContractorSearchPresenter(ContractorSearchView givenContractorSearchView) {&lt;br /&gt;  this.contractorSearchView = givenContractorSearchView;&lt;br /&gt;  contractorSearchView.registerSearchListener(new ContractorSearchListener() {&lt;br /&gt;&lt;br /&gt;   public void searchCriterionAdded(String criterion) {&lt;br /&gt;    searchResults = contractorService.searchByName(criterion);&lt;br /&gt;    updateView();&lt;br /&gt;   }&lt;br /&gt;   &lt;br /&gt;  });&lt;br /&gt;  updateView();&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; private void updateView() {&lt;br /&gt;  contractorSearchView.updateSearchResults(searchResults);&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public void setService(ContractorService givenContractorService) {&lt;br /&gt;  this.contractorService = givenContractorService;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So that's how to test drive your Swing application front-end :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-2395888246390868222?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/2395888246390868222/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=2395888246390868222' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2395888246390868222'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2395888246390868222'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2009/06/test-driving-swing.html' title='Test Driving Swing'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_9n5tyt6Sfwc/SieHnKh0CeI/AAAAAAAAADI/ZUEEIF0hsIE/s72-c/model_view_presenter_small.bmp' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-5447087825342657202</id><published>2009-04-16T08:13:00.000-07:00</published><updated>2009-04-16T13:30:25.297-07:00</updated><title type='text'>JUnit for Jasper Reports</title><content type='html'>Finally ... today I had a chance, between hectic schedules, to write our first JUnit for Jasper reports. GOOGLE wasn't friendly this time, so had a clean canvas to work from :)&lt;br /&gt;&lt;br /&gt;The repeating hurdle I faced was that I'm required to design and develop a report well before any of the database structures or data is captured within the system. It's like trying to extract a report on something that doesn't exist yet ... how funny ...&lt;br /&gt;&lt;br /&gt;To make matters worse, the database table structure is like a spiders web. Finally, although unfortunate, I had a chance to work in Brian's Big Balls of Mud &lt;a href="http://www.laputan.org/mud/"&gt;http://www.laputan.org/mud/ &lt;/a&gt;scenario. Pre-populating database tables with "dummy" data is close to impossible in my case. Our report query's end up having a norm of 14 inner joins ... not a pretty sight at all.&lt;br /&gt;&lt;br /&gt;The TDD approaches the problem from a different perspective. My idea was to pass a collection of expected results to the report, and then assert the output. I like to think of it as a black box ... by sending some input, and knowing the expected output values, you should be able to assert that the black box is functioning correctly ...&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_9n5tyt6Sfwc/Sed8QGrAiKI/AAAAAAAAACQ/JgkOKxyF3tM/s1600-h/black_box.bmp"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 320px; height: 120px;" src="http://2.bp.blogspot.com/_9n5tyt6Sfwc/Sed8QGrAiKI/AAAAAAAAACQ/JgkOKxyF3tM/s320/black_box.bmp" alt="" id="BLOGGER_PHOTO_ID_5325361700499654818" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;From the diagram, &lt;span style="font-weight: bold;"&gt;X&lt;/span&gt; would be the input values, &lt;span style="font-weight: bold;"&gt;Y&lt;/span&gt; the results that I expect to receive, and &lt;span style="font-weight: bold;"&gt;T(x)&lt;/span&gt; the report that I'm testing.&lt;br /&gt;&lt;br /&gt;I started off by first creating a new report. The report contains a single text field that get's populated by a data-source. The other text boxes all contain static text and won't change given different input values. The report is shown below:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_9n5tyt6Sfwc/Sed-slYlBaI/AAAAAAAAACY/T5O3hBsvVJ4/s1600-h/report_template.bmp"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 320px; height: 100px;" src="http://1.bp.blogspot.com/_9n5tyt6Sfwc/Sed-slYlBaI/AAAAAAAAACY/T5O3hBsvVJ4/s320/report_template.bmp" alt="" id="BLOGGER_PHOTO_ID_5325364388803446178" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In Jasper there is two different types of input, one would be report parameters (mostly used to filter query results of a report), the second, field values (values retrieved from the database, using the report query).&lt;br /&gt;&lt;br /&gt;I started off by creating a java.util.Map containing field values. This would be analogous to the data retrieved from a SQL query run by the report.&lt;pre name="code" class="java"&gt;private static Map&lt;string, object=""&gt; data;&lt;br /&gt;private static List&amp;lt;Map&amp;lt;String, Object&amp;gt;&amp;gt; dataCollection = new ArrayList&amp;lt;Map&amp;lt;String,Object&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;{&lt;br /&gt;data = new HashMap&amp;lt;String, Object&amp;gt;();&lt;br /&gt;&lt;/string,&gt;&lt;br /&gt;&lt;string, object=""&gt;// Add expected field data&lt;br /&gt;data.put("POST_ADDR", "THE ADDRESS");&lt;br /&gt;&lt;br /&gt;// Add the Hash-map data to a collection&lt;br /&gt;dataCollection.add(data);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/string,&gt;&lt;/pre&gt;The Map of field values are added to a collection, which in turn is used to populate a Jasper data-source.&lt;pre name="code" class="java"&gt;    // Setup the data-source with expected data values&lt;br /&gt;dataSource = new JRMapCollectionDataSource(dataCollection);&lt;br /&gt;&lt;/pre&gt;I created a parameter as well ...&lt;pre name="code" class="java"&gt;// Construct required parameters for the report&lt;br /&gt;parameterNameToValue = new Hashtable&lt;string, object=""&gt;();&lt;br /&gt;parameterNameToValue.put("PRINT_IT", new Long(1L));&lt;br /&gt;&lt;/string,&gt;&lt;/pre&gt;I then added the "mock" data-source and parameter to Jasper's fill manager ...&lt;pre name="code" class="java"&gt;// Given the setup data-source and parameter mappings&lt;br /&gt;// When the report is run&lt;br /&gt;String jasperReport = "C:\\DEV_WORKSPACE\\TextExporter\\src\\templates\\classic.jasper";&lt;br /&gt;JasperPrint print = JasperFillManager.fillReport(jasperReport, parameterNameToValue, dataSource);&lt;br /&gt;&lt;/pre&gt; I then ran the test ...&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SeeG0M5M7UI/AAAAAAAAACg/46PBJCzRScU/s1600-h/test_run_A.bmp"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 400px; height: 200px;" src="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SeeG0M5M7UI/AAAAAAAAACg/46PBJCzRScU/s400/test_run_A.bmp" alt="" id="BLOGGER_PHOTO_ID_5325373315761368386" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The awesome part to specifying the reports' data-source inside the unit test, was that it temporarily ignores any data-source specified in the report itself. To illustrate this I first ran the report inside iReport &lt;a href="http://www.jaspersoft.com/JasperSoft_iReport.html"&gt;http://www.jaspersoft.com/JasperSoft_iReport.html&lt;/a&gt;,&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_9n5tyt6Sfwc/SeeIXLiHYpI/AAAAAAAAACo/01_Qk5CGlBc/s1600-h/pdf_report_DBdatasource.bmp"&gt;&lt;img style="cursor: pointer; width: 400px; height: 32px;" src="http://1.bp.blogspot.com/_9n5tyt6Sfwc/SeeIXLiHYpI/AAAAAAAAACo/01_Qk5CGlBc/s400/pdf_report_DBdatasource.bmp" alt="" id="BLOGGER_PHOTO_ID_5325375016203149970" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The text field accurately displayed the contents inside the database, namely &lt;span style="font-weight: bold;"&gt;PO BOX 515&lt;/span&gt;.&lt;br /&gt;I then ran the same report inside the unit test, using the "mock" data-source ... the result was&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_9n5tyt6Sfwc/SeeJQt57dJI/AAAAAAAAACw/PNLl8NkwFQY/s1600-h/pdf_report_CUSTOMdatasource.bmp"&gt;&lt;img style="cursor: pointer; width: 400px; height: 29px;" src="http://3.bp.blogspot.com/_9n5tyt6Sfwc/SeeJQt57dJI/AAAAAAAAACw/PNLl8NkwFQY/s400/pdf_report_CUSTOMdatasource.bmp" alt="" id="BLOGGER_PHOTO_ID_5325376004682380434" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;which corresponds to the field value I specified in the unit-test.&lt;br /&gt;&lt;br /&gt;Even though its good to visually inspect your report, we're writing a unit test, and would like to assert that these values are correct inside the unit test. I accomplished just that, by inspecting the JasperPrint objects' &lt;span style="font-weight: bold; font-style: italic;"&gt;page&lt;/span&gt; and &lt;span style="font-weight: bold; font-style: italic;"&gt;element&lt;/span&gt; values. Since we only have one page, I only needed to retrieve elements on the first page. &lt;pre name="code" class="java"&gt;&lt;br /&gt;List&lt;jrprintpage&gt; pages = print.getPages();&lt;br /&gt;JRPrintPage pageToTest = pages.get(0);&lt;br /&gt;List&lt;jrprintelement&gt; pageElements = pageToTest.getElements();&lt;br /&gt;&lt;/jrprintelement&gt;&lt;/jrprintpage&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Every Jasper element has a key value. The text field I was testing against had the key name &lt;span style="font-weight: bold;"&gt;'textField-1'&lt;/span&gt;. I iterated inside a loop until I found the element &lt;pre name="code" class="java"&gt;&lt;br /&gt;for (Iterator iterator = pageElements.iterator(); iterator.hasNext();)   JRPrintElement element = (JRPrintElement) iterator.next();&lt;br /&gt; if(element.getKey().equals("textField-1")) {&lt;br /&gt;&lt;/pre&gt; and then asserted the expected value is displayed &lt;pre name="code" class="java"&gt;&lt;br /&gt;textField = (JRTemplatePrintText) element;&lt;br /&gt;Assert.assertEquals("THE ADDRESS", textField.getText());&lt;br /&gt;&lt;/pre&gt; I ran the test case again and it passed !!&lt;br /&gt;&lt;br /&gt;The power from asserting display values inside a unit-test is when we want to test against some decision logic inside the report. I added a print condition on the text field. I did this using the parameter specified in the unit-test.&lt;pre name="code" class="java"&gt;&lt;br /&gt;parameterNameToValue = new Hashtable&lt;string, object=""&gt;();&lt;br /&gt;parameterNameToValue.put("PRINT_IT", new Long(1L));&lt;br /&gt;&lt;/string,&gt;&lt;/pre&gt; Inside iReport we would need to specify the parameter as well. This was done like so:&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SeeOoQ7bv2I/AAAAAAAAAC4/q391nf3GnHE/s1600-h/print_condition.bmp"&gt;&lt;img style="cursor: pointer; width: 305px; height: 320px;" src="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SeeOoQ7bv2I/AAAAAAAAAC4/q391nf3GnHE/s320/print_condition.bmp" alt="" id="BLOGGER_PHOTO_ID_5325381906779062114" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;The print condition was added to the text field like so:&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_9n5tyt6Sfwc/SeeQKjx5ugI/AAAAAAAAADA/K-JBwphfpqk/s1600-h/print_condition_spec.bmp"&gt;&lt;img style="cursor: pointer; width: 320px; height: 195px;" src="http://1.bp.blogspot.com/_9n5tyt6Sfwc/SeeQKjx5ugI/AAAAAAAAADA/K-JBwphfpqk/s320/print_condition_spec.bmp" alt="" id="BLOGGER_PHOTO_ID_5325383595466537474" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Since the &lt;span style="font-weight: bold;"&gt;PRINT_IT&lt;/span&gt; was given a value of 1 in the unit-test, the test passed again.&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SeeG0M5M7UI/AAAAAAAAACg/46PBJCzRScU/s1600-h/test_run_A.bmp"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 400px; height: 200px;" src="http://2.bp.blogspot.com/_9n5tyt6Sfwc/SeeG0M5M7UI/AAAAAAAAACg/46PBJCzRScU/s400/test_run_A.bmp" alt="" id="BLOGGER_PHOTO_ID_5325373315761368386" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;Changing the parameter value to 0 instead, caused it to fail as expected.&lt;br /&gt;&lt;br /&gt;My sample prototype was working and it was time to expand on my morning endeavors. So during the afternoon, I re-factored the code. I created a base test class from which all future unit-tests can be based on:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;import net.sf.jasperreports.engine.JRPrintPage;&lt;br /&gt;import net.sf.jasperreports.engine.JasperFillManager;&lt;br /&gt;import net.sf.jasperreports.engine.JasperPrint;&lt;br /&gt;import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;&lt;br /&gt;import net.sf.jasperreports.engine.fill.JRTemplatePrintText;&lt;br /&gt;&lt;br /&gt;import org.junit.Assert;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class JasperPrintTest extends TestCase {&lt;br /&gt;&lt;br /&gt; private Map&amp;lt;String, Object&gt; data;&lt;br /&gt; private List&amp;lt;Map&amp;lt;String, Object&amp;gt;&amp;gt; dataCollection;&lt;br /&gt;&lt;br /&gt; private JRDataSource dataSource; &lt;br /&gt; private Map&amp;lt;String, Object&amp;gt; parameterNameToValue;&lt;br /&gt; private String jasperReport;&lt;br /&gt; private Exporter exporter;&lt;br /&gt; private JasperPrint print;&lt;br /&gt;&lt;br /&gt; public void setUp() throws Exception {&lt;br /&gt;&lt;br /&gt;  // Add the hash-map of Field values to the collection&lt;br /&gt;  dataCollection = new ArrayList&amp;lt;Map&amp;lt;String,Object&amp;gt;&amp;gt;();&lt;br /&gt;  dataCollection.add(data);&lt;br /&gt;&lt;br /&gt;  // Setup the data-source with expected data values&lt;br /&gt;  dataSource = new JRMapCollectionDataSource(dataCollection);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; /**&lt;br /&gt;  * &lt;br /&gt;  * @param expectedResults Map of key-value pairs&lt;br /&gt;  * @throws Exception&lt;br /&gt;  */&lt;br /&gt; @SuppressWarnings("unchecked")&lt;br /&gt; public void testPrint(Map&amp;lt;String, Object&amp;gt; expectedResults) throws Exception {&lt;br /&gt;&lt;br /&gt;  // Given the setup data-source and parameter mappings&lt;br /&gt;&lt;br /&gt;  // When the report is run  &lt;br /&gt;  print = JasperFillManager.fillReport(jasperReport, parameterNameToValue, dataSource);&lt;br /&gt;&lt;br /&gt;  // Then assert that the result has the expected value&lt;br /&gt;  List&amp;lt;JRPrintPage&amp;gt; pages = print.getPages();&lt;br /&gt;  for (Iterator iterator = pages.iterator(); iterator.hasNext();) {&lt;br /&gt;   JRPrintPage pageToTest = (JRPrintPage) iterator.next();&lt;br /&gt;   List&amp;lt;JRPrintElement&amp;gt; pageElements = pageToTest.getElements();&lt;br /&gt;&lt;br /&gt;   JRTemplatePrintText textField = null;&lt;br /&gt;   for (Iterator element_iterator = pageElements.iterator(); element_iterator.hasNext();) {&lt;br /&gt;    JRPrintElement element = (JRPrintElement) element_iterator.next();&lt;br /&gt;    if(expectedResults.keySet().contains(element.getKey())) {&lt;br /&gt;     textField = (JRTemplatePrintText) element;&lt;br /&gt;     Assert.assertEquals(expectedResults.get(element.getKey()), textField.getText());&lt;br /&gt;     break;&lt;br /&gt;    }&lt;br /&gt;   }&lt;br /&gt;  }  &lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void exportResults(int height, int width, String fileName) throws JRException {&lt;br /&gt;  exporter.export(print, height, width, fileName);  &lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void setData(Map&amp;lt;String, Object&amp;gt; data) {&lt;br /&gt;  this.data = data;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void setParameterNameToValue(Map&amp;lt;String, Object&amp;gt; parameterNameToValue) {&lt;br /&gt;  this.parameterNameToValue = parameterNameToValue;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void setJasperReport(String jasperReport) {&lt;br /&gt;  this.jasperReport = jasperReport;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void setExporter(Exporter exporter) {&lt;br /&gt;  this.exporter = exporter;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public Map&amp;lt;String, Object&amp;gt; getData() {&lt;br /&gt;  return data;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt; The idea is to pass the expected results (or output) to this underlying class from your unit test. I successfully wrote a test case (using this custom base class) for the most recent report I had to design. Below is the entire test case, testing several scenarios in each test method.&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;import java.util.HashMap;&lt;br /&gt;import java.util.Hashtable;&lt;br /&gt;import java.util.Map;&lt;br /&gt;&lt;br /&gt;import org.junit.Before;&lt;br /&gt;import org.junit.Test;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class SORSupplementaryPrintTest extends JasperPrintTest {&lt;br /&gt;&lt;br /&gt; Map&amp;lt;String, Object&amp;gt; fieldData;&lt;br /&gt;&lt;br /&gt; @Before&lt;br /&gt; public void setUp() throws Exception {&lt;br /&gt;  fieldData = new HashMap&amp;lt;String, Object&amp;gt;();&lt;br /&gt;  fieldData.put("EXAM_CENTRE", "centre");&lt;br /&gt;  fieldData.put("CIRCUIT", "circuit");&lt;br /&gt;  fieldData.put("REGION", "region");&lt;br /&gt;  fieldData.put("EXAM_PERIOD_DESC", "                    ");&lt;br /&gt;  fieldData.put("EXAM_CENTRE_POST_ADR", "                    ");&lt;br /&gt;  fieldData.put("EXAM_CENTRE_POST_CODE", "                    ");&lt;br /&gt;  fieldData.put("PROVINCE", "                    ");&lt;br /&gt;  fieldData.put("PROV_CODE", "                    ");&lt;br /&gt;  fieldData.put("SOR_NUMBER", new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("EXAMINATION_NUMBER", new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("ID_NUMBER", "88778");&lt;br /&gt;  fieldData.put("PASSPORT_NUMBER", "002900");&lt;br /&gt;  fieldData.put("IMMIGRANT", new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("DATE_OF_BIRTH", new oracle.sql.TIMESTAMP());&lt;br /&gt;  fieldData.put("CANDIDATE", "candidate");&lt;br /&gt;  fieldData.put("CANDIDATE_SURNAME", "surname");&lt;br /&gt;  fieldData.put("POSTAL_ADDRESS", "postal address");&lt;br /&gt;  fieldData.put("POSTAL_CODE", "postal code");&lt;br /&gt;  fieldData.put("SUBJECT_CODE", "subject code");&lt;br /&gt;  fieldData.put("ALPHA_CODE", "alpha code");&lt;br /&gt;  fieldData.put("SUBJECT_NUMERIC_CODE", new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("SUBJECT_DESC", "subject description");&lt;br /&gt;  fieldData.put("SUBJECT_TABLE_LID", new java.math.BigDecimal(1));&lt;br /&gt;  fieldData.put("ENROLLMENT_ID", new java.math.BigDecimal(1));&lt;br /&gt;  fieldData.put("WORDS_PER_MINUTE", new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("DEC_PERC" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("MARKSHEET_STATUS_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("ACTIVE_IRREGS" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("GUILTY_IRREGS" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("SUPL_PERC" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("RESULT_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("CERTIFICATE_LANGUAGE_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("PAPER_LANGUAGE_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("PROMOTION_TYPE_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("ENROL_WITH_SPECIAL_CONDITIONS" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("QUALIFIES_FOR_SUPLEMENTARY" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("REGION_CODE", "                           ");&lt;br /&gt;  fieldData.put("CIRCUIT_CODE", "                           ");&lt;br /&gt;  fieldData.put("CEN_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("EXAM_CENTRE_CODE", "                           ");&lt;br /&gt;  fieldData.put("IS_MAIN_REG" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("MAIN_RESULT_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("SUPL_RESULT_ID" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("SUBJECT_PERC_ROUNDED" , new java.math.BigDecimal(0));&lt;br /&gt;  fieldData.put("EXAM_YEAR", new java.math.BigDecimal(2009));&lt;br /&gt;  super.setData(fieldData);&lt;br /&gt;  &lt;br /&gt;  Map&amp;lt;String, Object&amp;gt; parameterNameToValue = new Hashtable&amp;lt;String, Object&amp;gt;();&lt;br /&gt;  parameterNameToValue.put("LOCATION_ID", new Long(1L));&lt;br /&gt;  parameterNameToValue.put("EXAM_PERIOD_ID", new Long(1L));&lt;br /&gt;  super.setParameterNameToValue(parameterNameToValue);&lt;br /&gt;  &lt;br /&gt;  super.setJasperReport("C:\\DEV_WORKSPACE\\MARCH_BRANCH\\src\\server\\prod\\com\\magnafs\\iecs\\reports\\StatementOfResults\\SupplementaryStatementOfResultsPerLocText.jasper");&lt;br /&gt;  super.setExporter(new TextExporter());&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void testShouldPrintMarchDateAchievedForSupplementaryRegistration() throws Exception {&lt;br /&gt;  &lt;br /&gt;  // Given an improved promotion status&lt;br /&gt;  // Given it is a supplementary registration&lt;br /&gt;  super.getData().put("RESULT_ID", new java.math.BigDecimal(100084)); &lt;br /&gt;  super.getData().put("SUPL_RESULT_ID", new java.math.BigDecimal(100086));&lt;br /&gt;  super.getData().put("IS_MAIN_REG", new java.math.BigDecimal(0));&lt;br /&gt;  super.setUp();  &lt;br /&gt;&lt;br /&gt;  // Expect these results &lt;br /&gt;  Map&amp;lt;String, Object&amp;gt; expectedResults = new HashMap&amp;lt;String, Object&amp;gt;();&lt;br /&gt;  expectedResults.put("textField-33", "MAR 2009");&lt;br /&gt;  &lt;br /&gt;  // When the report is generated&lt;br /&gt;  super.testPrint(expectedResults);&lt;br /&gt;  &lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; @Test&lt;br /&gt; public void testShouldPrintMarchDateAchievedForGreaterSupplementaryResult() throws Exception {&lt;br /&gt;  &lt;br /&gt;  // Given an improved promotion status&lt;br /&gt;  // Given it is a main registration&lt;br /&gt;  // Given the supplementary result is greater than the December result &lt;br /&gt;  super.getData().put("RESULT_ID", new java.math.BigDecimal(100084)); &lt;br /&gt;  super.getData().put("SUPL_RESULT_ID", new java.math.BigDecimal(100086));&lt;br /&gt;  super.getData().put("IS_MAIN_REG", new java.math.BigDecimal(1));&lt;br /&gt;  super.getData().put("DEC_PERC", new java.math.BigDecimal(27));&lt;br /&gt;  super.getData().put("SUPL_PERC", new java.math.BigDecimal(96));&lt;br /&gt;  super.setUp();  &lt;br /&gt;&lt;br /&gt;  // Expect these results &lt;br /&gt;  Map&amp;lt;String, Object&amp;gt; expectedResults = new HashMap&amp;lt;String, Object&amp;gt;();&lt;br /&gt;  expectedResults.put("textField-33", "MAR 2009");&lt;br /&gt;  &lt;br /&gt;  // When the report is generated&lt;br /&gt;  super.testPrint(expectedResults);&lt;br /&gt;  &lt;br /&gt; }  &lt;br /&gt; &lt;br /&gt; @Test&lt;br /&gt; public void testShouldPrintNovemberDateAchievedForGreaterDecemberResult() throws Exception {&lt;br /&gt;  &lt;br /&gt;  // Given an improved promotion status&lt;br /&gt;  // Given it is a main registration&lt;br /&gt;  // Given the December result is greater than the supplementary result &lt;br /&gt;  super.getData().put("RESULT_ID", new java.math.BigDecimal(100084)); &lt;br /&gt;  super.getData().put("SUPL_RESULT_ID", new java.math.BigDecimal(100086));&lt;br /&gt;  super.getData().put("IS_MAIN_REG", new java.math.BigDecimal(1));&lt;br /&gt;  super.getData().put("DEC_PERC", new java.math.BigDecimal(56));&lt;br /&gt;  super.getData().put("SUPL_PERC", new java.math.BigDecimal(48));&lt;br /&gt;  super.setUp();  &lt;br /&gt;&lt;br /&gt;  // Expect these results &lt;br /&gt;  Map&amp;lt;String, Object&amp;gt; expectedResults = new HashMap&amp;lt;String, Object&amp;gt;();&lt;br /&gt;  expectedResults.put("textField-33", "NOV 2008");&lt;br /&gt;  &lt;br /&gt;  // When the report is generated&lt;br /&gt;  super.testPrint(expectedResults);&lt;br /&gt;  &lt;br /&gt;  // Test view the report results&lt;br /&gt;  super.exportResults(64, 100, "C:\\DEV_WORKSPACE\\TextExporter\\src\\results\\exportResults.txt");&lt;br /&gt; } &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-5447087825342657202?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/5447087825342657202/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=5447087825342657202' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5447087825342657202'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5447087825342657202'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2009/04/junit-for-jasper-reports.html' title='JUnit for Jasper Reports'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_9n5tyt6Sfwc/Sed8QGrAiKI/AAAAAAAAACQ/JgkOKxyF3tM/s72-c/black_box.bmp' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-6598210461923311799</id><published>2009-04-08T04:38:00.000-07:00</published><updated>2009-04-08T05:37:43.418-07:00</updated><title type='text'>Where to log exceptions ? How to handle them ?</title><content type='html'>While working on my SCJD project, I encountered a hurdle in the road. SUN explicitly gives us an interface which we must implement for database operations. We're not allowed to change it or deviate from this interface. &lt;br /&gt;&lt;br /&gt;The interface methods declare exceptions for a record not found. However, some third party classes like the RandomAcessFile class, throw additional exceptions like FileNotFoundException, IOException and EOFException. Throwing a IOException doesn't necessarily mean that the record couldn't be found ... &lt;br /&gt;&lt;br /&gt;Basically, there are three tiers (or levels) to log your exceptions in:&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;    &lt;li&gt;&lt;span style="font-weight:bold;"&gt;Bottom level tier:&lt;/span&gt; Logging the exception where it first occurred (somewhere at the Data Access layer ... or even lower maybe ?).&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;&lt;span style="font-weight:bold;"&gt;Middle level tier:&lt;/span&gt; Logging higher up the call stack, where more information is available (probably at the services or business layer).&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;&lt;span style="font-weight:bold;"&gt;Top level tier:&lt;/span&gt; Propagating your exception all the way to the GUI (all the display details in the MVC architecture).&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;Logging at the bottom level may cause problems. For example, if SUN's RandomAcessFile were to handle the FileNotFoundException internally, there would be no way for me to know what caused the problem in the first place. If an exception was thrown in the data access layer, and it get's swallowed up, what do I tell the user ? Even worse ... what if ... while performing a write or update on the database, a database exception is thrown? Surely, a roll back needs to happen? Do I retry the database operation, or do I propagate it higher up the call stack?&lt;br /&gt;&lt;br /&gt;Logging higher up will allow you to wrap the exceptions and add additional information as it's propagated up the call stack. It might help putting exceptions into perspective. This component called this one, which called component X that threw the exception.&lt;br /&gt;&lt;br /&gt;In my opinion, propagating exceptions all the way to the top level of the stack, should only happen if you need to display a relevant message to the user. Handling exceptions at the top level, is a means of dealing exceptions centrally at one place. However, so would using AOP as well &lt;a href="http://flexingcode.blogspot.com/2008/10/how-to-audit-your-code.html"&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In my case, for the project, adding AOP is overkill to implement from scratch (We're not allowed to use anything besides the standard Java API). I don't think that having a fixed interface is that uncommon. Working on a project, with a fixed interface to another system is a reasonable and realistic scenario that may occur.&lt;br /&gt;&lt;br /&gt;From the &lt;span style="font-weight:bold;"&gt;SCJD Exam with J2SE 5 Platform&lt;/span&gt; I have 5 choices.&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;    &lt;li&gt;Swallow the exception: The exception is caught but not not dealt with (Neither logged or propagated).&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Just log the exception&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Wrap the exception within an allowed exception&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Wrap the exception within a RuntimeException&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Wrap the exception within a subclass of RuntimeException&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;So ... it boils down to ... ignoring the exception, logging it or just propagating it higher up the call stack. Ignoring the exception would be a NO outright. Choosing to either log or propagate the exception would probably come down to this:&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;    &lt;li&gt;Will the user want to know what occurred?&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Will the user be able to correct or rectify the situation?&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Is enough information available to log the exception in its context?&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;There might be more factors to consider than the three I mentioned, but it gives you a reasonable idea on what to do.&lt;br /&gt;&lt;br /&gt;To come back to my scenario, with the FileNotFoundException, I've decided to propagate all the way. Not having a database anymore (a file based system in this case) is a major problem ! At least if the user get's the exception, the DBA might have a look at it... :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-6598210461923311799?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/6598210461923311799/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=6598210461923311799' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/6598210461923311799'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/6598210461923311799'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2009/04/where-to-log-exceptions-how-to-handle.html' title='Where to log exceptions ? How to handle them ?'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-5286090049465861076</id><published>2009-04-04T13:25:00.001-07:00</published><updated>2009-04-06T14:01:30.290-07:00</updated><title type='text'>SCJD - Update</title><content type='html'>Finally !! ... I'm working on my SCJD project again. I recommend reading &lt;blockquote&gt;SCJD by Andrew Monkhouse and Terry Camerlengo&lt;/blockquote&gt; before you begin. It gives a good idea on what to expect.&lt;br /&gt;&lt;br /&gt;I've decided to follow the TDD (Test Driven Development) approach. It's preferred to write your first test case in the GUI layer. The GUI is high-level, abstract and it's the first thing the client will notice. Beginning at the graphics level sets client expectations, and allows for feature requests early-on during development.&lt;br /&gt;&lt;br /&gt;My first few minutes have been rewarding, helping me identify scenarios I'd probably never have thought of otherwise. I started writing a test method for one of the API methods specified by SUN (just to test the waters ... so to speak).&lt;br /&gt;&lt;br /&gt;The test case is used to test the reading of a record from the DB. I needed to create an implementation class for the API method. I wanted to use a design pattern right away ... but then realized again ... never use a design pattern if there's no need for it yet !&lt;br /&gt;&lt;br /&gt;First I wrote my story:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;// As a CSR&lt;br /&gt;// I want to retrieve an existing DB record&lt;br /&gt;// So that I can view the record data&lt;br /&gt;public class ReadRecordTest {&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Then I wrote the test:&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; @Test&lt;br /&gt; public void testReadExistingRecord() throws Exception {&lt;br /&gt;  &lt;br /&gt;  // Given a database file&lt;br /&gt;  File databaseFile = new File("test/suncertify/db/db-2x2.db");&lt;br /&gt;  &lt;br /&gt;  // When I call the DB read method&lt;br /&gt;  DBAccess dbAccess = new DBAccessImplementation(databaseFile);&lt;br /&gt;  String[] record = dbAccess.readRecord(1L);&lt;br /&gt;  &lt;br /&gt;  // Then a complete DB record should be returned&lt;br /&gt;  Assert.assertNotNull(record);&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;First try and it failed. I had a look at my implementation class, and realized it wasn't doing anything ...&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; @Override&lt;br /&gt; public String[] readRecord(long recNo) throws RecordNotFoundException {&lt;br /&gt;               return null;&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I made it pass by returning some fixed value instead, like so:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; @Override&lt;br /&gt; public String[] readRecord(long recNo) throws RecordNotFoundException {&lt;br /&gt;  String[] record = {"t", "g"}; &lt;br /&gt;  return record;&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Yes ... it's obvious that I'm "making" the test pass. That, however, is the mindset of TDD. Write a story and then test until you make it pass.&lt;br /&gt;&lt;br /&gt;The next step, was the inverse of the first.&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt; @Test(expected=RecordNotFoundException.class)&lt;br /&gt; public void testReadNonExistingRecord() throws RecordNotFoundException {&lt;br /&gt;  &lt;br /&gt;  // Given a database file&lt;br /&gt;  File databaseFile = new File("test/suncertify/db/db-2x2.db");&lt;br /&gt;  &lt;br /&gt;  // When I call the DB read method, for a non-existing record&lt;br /&gt;  DBAccess dbAccess = new DBAccessImplementation(databaseFile);&lt;br /&gt;  String[] record = dbAccess.readRecord(1L);&lt;br /&gt;  &lt;br /&gt;  // Then I expect an exception to be thrown&lt;br /&gt; } &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As expected, this test failed. I had to go back to the implementation and actually retrieve data for the tests to work. This was just a basic example of TDD. It helps you identify those code bugs that pass 90% of the time, but fail the rest.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-5286090049465861076?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/5286090049465861076/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=5286090049465861076' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5286090049465861076'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5286090049465861076'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2009/04/scjd-update.html' title='SCJD - Update'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-5196579240286228945</id><published>2009-02-01T02:21:00.001-08:00</published><updated>2009-02-02T01:51:54.094-08:00</updated><title type='text'>How to discover a new Design Pattern ?</title><content type='html'>Design Patterns are found after hard work and experience. Every situation is different, and good judgment is needed to know when to use one. &lt;br /&gt;&lt;br /&gt;Thankfully many patterns have been cataloged already. But what if you can't find a pattern for your problem ? The answer would be to discover a new one.&lt;br /&gt;&lt;br /&gt;Patterns aren't fixed in stone. You may combine them, alter them, and adapt them for your unique situation. Whether your new pattern utilizes existing ones doesn't matter, the underlying principles for finding the pattern still remains the same.&lt;br /&gt;&lt;br /&gt;I've made a list of principles for discovering a new design pattern below:&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;    &lt;li&gt;Encapsulate what varies&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Favour composition over inheritance&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Program to interfaces, not implementations&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;/span&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;&lt;span style="color: rgb(51, 153, 102);"&gt;&lt;span style="font-size: larger;"&gt;Encapsulate what varies&lt;/span&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;The idea is to capture code that changes often and make it a reusable component. First you'll need to determine what is changing all the time, and then later make logical groupings of the code that changes.&lt;br /&gt;&lt;p&gt;&lt;strong&gt;&lt;span style="color: rgb(51, 153, 102);"&gt;&lt;span style="font-size: larger;"&gt;Favour composition over inheritance&lt;/span&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;Beware of making everything an "IS-A" relationship. Sometimes a "HAS-A" relationship would be more beneficial. In fact it's better to favour "HAS-A" associations over "IS-A" associations whenever possible. Why do I say that ? Well ... "HAS-A" associations are related to encapsulations; you're capturing a sample of code and injecting it into another class as a property. If we were to make the property field an interface instead, we would be able to interchangeably inject several different implementations. This is an ideal property for creating reusable components. You might be thinking I'm refering to the strategy pattern in particular, however the underlying principle applies to all other patterns: "We want to make a seperate reusable component, which implies a seperate class with its own interface".&lt;br /&gt;&lt;p&gt;&lt;strong&gt;&lt;span style="color: rgb(51, 153, 102);"&gt;&lt;span style="font-size: larger;"&gt;Program to interfaces, not implementations&lt;/span&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;Whenever a composition is created, it makes logical sense to extract an interface (good object-oriented programming). Thus the opposite is also true; program to an interface and you'll end up with several small reusable components (in theory of course ;)&lt;br /&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-5196579240286228945?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/5196579240286228945/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=5196579240286228945' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5196579240286228945'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/5196579240286228945'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2009/02/how-to-discover-new-design-pattern.html' title='How to discover a new Design Pattern ?'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-3127420303873433064</id><published>2009-01-04T10:37:00.000-08:00</published><updated>2009-01-04T13:57:16.830-08:00</updated><title type='text'>Reflection: When to use it ... when NOT.</title><content type='html'>Code transparency, it's something we should ALL strive towards. Code transparency means you compartmentalize your code into separate regions of concern. The benefits ... change one part of the system and limit the damage done to the other parts. The lightweight (Model View Controller) pattern became famous for that very reason. However, the MVC is not the only way to make your code transparent.&lt;br /&gt;&lt;br /&gt;The Spring framework (along with the MVC pattern)  gave us a no-intrusion framework that uses XML configuration files to pilot the system where you want it to go. It also makes use of reflection and dependency injection,  in order to generalize and compartmentalize the framework code of the underlying system (so you don't need to embed horrible framework code &lt;span style="font-style: italic;"&gt;even if only annotated &lt;/span&gt;... EJB's blargghhh).&lt;br /&gt;&lt;br /&gt;The benefits of transparent code are endless, and reflection is a way and a means to achieve that goal. Using reflection we can build generalized services that will eliminate most of that terrible &lt;span style="font-style: italic;"&gt;copy - paste&lt;/span&gt; habits.&lt;br /&gt;&lt;br /&gt;Start by asking yourself: &lt;span style="font-style: italic;"&gt;is this a general need in the system, or, a specific one ?&lt;/span&gt; If you're unsure then your best bet is NOT to use reflection. Delaying your decision for using reflection could save you in the long run, especially after problem patterns and user requirements change.&lt;br /&gt;&lt;br /&gt;However, if you need to access an object's features in a general way, reflection becomes very useful. One such a scenario would be an XML emitter (like Castor). Maybe you're implementing a new Web Service technology from scratch and want to send over object state parsed to XML. To custom write XML for every object type (class) would be a very long, tedious and error prone approach. A much simpler solution would be to inspect a parsed in object, and build up your XML structure dynamically using the reflection API.&lt;br /&gt;&lt;br /&gt;Another scenario where you could make use of reflection is with persistence (Hibernate is an excellent example). By inspecting the return types, and field associations it's possible to build up the corresponding SQL statements dynamically. The point is that whenever you perform some general action on objects (whether only inspecting it, or even modifying it) , reflection becomes  handy. Yes ... there is still a performance penalty, but not so much as it use to. SUN MICROSYSTEMS have done an excellent job in improving reflection performance over the years (in particular, Java 6). These days, the benefits of reflection far outway the performance penalties when used appropriately.&lt;br /&gt;&lt;br /&gt;To get you started, below is a short intro to the reflection API.&lt;br /&gt;&lt;br /&gt;The reflection API allows you to inspect the definitions (including the names and modifiers) of:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Classes&lt;/li&gt;&lt;li&gt;Methods &lt;span style="font-weight: bold;"&gt;[java.lang.reflect.Method]&lt;/span&gt; , and&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Fields &lt;span style="font-weight: bold;"&gt;[java.lang.reflect.Field]&lt;/span&gt;&lt;/li&gt;&lt;/ol&gt;Start by importing the reflection API into your project: &lt;span style="font-weight: bold;"&gt;import java.lang.reflect.*;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold; color: rgb(51, 204, 0);font-size:130%;" &gt;Accessing the class&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Two ways to inspect a particular class, either use:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;       Class c = Class.forName("&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;className&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;")&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;or,&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;       Class c = obj.getClass();&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;where &lt;span style="font-weight: bold;"&gt;Object obj = new className();&lt;/span&gt; and &lt;span style="font-weight: bold;"&gt;c is of type className&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold; color: rgb(51, 204, 0);font-size:130%;" &gt;Accessing the method&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;You only need to have the class type (as determined above) in order to find all the methods of that class.  Calling &lt;span style="font-weight: bold;"&gt;getMethods()&lt;/span&gt; on the class type will return an array with ALL the supported methods of that class (including the ones inherited from its super class). The  &lt;span style="font-weight: bold;"&gt;getDeclaredMethods()&lt;/span&gt; method returns an array of only the methods DECLARED in that specific class. The returned value is an array of &lt;span style="font-weight: bold;"&gt;java.lang.reflection.Method&lt;/span&gt; types.&lt;br /&gt;&lt;br /&gt;It's also possible to determine the parameter types of a method by calling  &lt;span style="font-weight: bold;"&gt;getParameterTypes()&lt;/span&gt; on the java.lang.reflection.Method type you found above.&lt;br /&gt;&lt;br /&gt;Example below:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;public static void printMethods(Object obj) throws Exception {&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Class cls = obj.getClass();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Method[] methods = cls.getDeclaredMethods();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (int methodIndex = 0; methodIndex &amp;lt; methods.length; methodIndex ++) { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; Method inspectedMethod = methods[methodIndex ]; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; Log.info(&amp;quot;The method name is: &amp;quot;+inspectedMethod.getName());&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; Class[] parameterTypes = method.getParameterTypes();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; for (parameterIndex = 0; parameterIndex &amp;lt; parameterTypes.length; parameterIndex++) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; StringBuilder sb = new StringBuilder()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .append(&amp;quot; Parameter &amp;quot;) .append(parameterIndex)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .append(&amp;quot; is of type: &amp;quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .append(parameterTypes[parameterIndex].toString());&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; log.info(sb.toString()); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;}&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;/pre&gt; &lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold; color: rgb(51, 204, 0);font-size:130%;" &gt;&lt;br /&gt;Accessing the field&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Retrieve all the fields of a certain class by calling &lt;span style="font-weight: bold;"&gt;getDeclaredFields()&lt;/span&gt; on that method.&lt;br /&gt;This will return an array of &lt;span style="font-weight: bold;"&gt;java.lang.reflect.Field&lt;/span&gt; types. It's possible to go even one step further and determine the modifiers (static, volatile etc) of that field by calling &lt;span style="font-weight: bold;"&gt;getModifiers()&lt;/span&gt; on it.&lt;br /&gt;&lt;br /&gt;To determine the field type call &lt;span style="font-weight: bold;"&gt;getType()&lt;/span&gt; on that field. To get it's value is a two step process.&lt;br /&gt;First set its accessibility value so it can be accessed by the &lt;span style="font-weight: bold;"&gt;java.lang.reflect&lt;/span&gt; package even if it's a private field. This can be done so:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;   Field inspectedField = fields[i];&lt;br /&gt;   inspectedField.setAccessible(true);&lt;br /&gt;&lt;/pre&gt;  &lt;br /&gt;&lt;br /&gt;Then to retrieve the field value do this:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="java"&gt;&lt;br /&gt;   Object value = field.get(objInstance);&lt;br /&gt;&lt;/pre&gt;  &lt;br /&gt;&lt;br /&gt;, where objInstance is the object whose field value you'd like to know.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-3127420303873433064?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/3127420303873433064/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=3127420303873433064' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/3127420303873433064'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/3127420303873433064'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2009/01/reflection-when-to-use-it-when-not.html' title='Reflection: When to use it ... when NOT.'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-6473673027369057258</id><published>2008-12-24T12:57:00.000-08:00</published><updated>2008-12-24T13:20:43.140-08:00</updated><title type='text'>Pressure</title><content type='html'>12 hours. That is what I have to design, develop and test a report. Not an ordinary report, but that one that could drastically change the course of our nation.  Approximately 600 000 people are waiting for me to roll this out to live deployment (printing tomorrow night nationwide). The quality and correctness of this report, will in effect change the course and lives of 600 000 people. It WILL change the political landscape of an entire country. Can we move the deadline ... impossible ... there's no other way. It's then or never.&lt;br /&gt;&lt;br /&gt;Will it be a success, I don't know. Two things I'm sure of, one whatever the outcome, I tried my best. The other, well I can't let you know, it might just reach AM, PM, CNN, BCC and probably every major news station in the world. [That's not going to help at all ... not my career, nor anyone else with me].&lt;br /&gt;&lt;br /&gt;There is a problem though, the technology to use is not working. We can't change that now (it's too late ... LOL). Only one way out, try to find another way of doing it, another way of solving a problem that can't be solved [but what can't be solved ?!?]. Working in IT, working under pressure like that, it's not always that healthy. But darn, you can't say that you're not having any fun.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-6473673027369057258?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/6473673027369057258/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=6473673027369057258' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/6473673027369057258'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/6473673027369057258'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/12/pressure.html' title='Pressure'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-4017646621146804693</id><published>2008-10-31T00:33:00.000-07:00</published><updated>2008-10-31T00:59:26.995-07:00</updated><title type='text'>Debugging your GWT in Eclipse</title><content type='html'>Using your IDE's debugging ability just adds another tool to your set when writing software, and could become very handy at times.&lt;br /&gt;&lt;br /&gt;This example is based upon the Red Hat Developer Studio, which is basically some additional plugins to your normal Eclipse environment.&lt;br /&gt;&lt;br /&gt;The first step to setting up your debug ability is to create a new debugging scenario. Select the "Debug as ... " drop down and select "Open Debug Dialog". The screen displayed should look like the one below.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_9n5tyt6Sfwc/SQq2VyE_cAI/AAAAAAAAACE/YV4kBmEg9ow/s1600-h/DebugDialog.bmp"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 311px; height: 320px;" src="http://3.bp.blogspot.com/_9n5tyt6Sfwc/SQq2VyE_cAI/AAAAAAAAACE/YV4kBmEg9ow/s320/DebugDialog.bmp" alt="" id="BLOGGER_PHOTO_ID_5263219599872061442" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;At the project input, click the "Browse ..." button and select your project.&lt;br /&gt;&lt;br /&gt;[Still in progress - will complete this post a bit later]&lt;br /&gt;&lt;img src="file:///C:/DOCUME%7E1/mhm/LOCALS%7E1/Temp/moz-screenshot.jpg" alt="" /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-4017646621146804693?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/4017646621146804693/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=4017646621146804693' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/4017646621146804693'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/4017646621146804693'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/10/debugging-your-gwt-in-eclipse.html' title='Debugging your GWT in Eclipse'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_9n5tyt6Sfwc/SQq2VyE_cAI/AAAAAAAAACE/YV4kBmEg9ow/s72-c/DebugDialog.bmp' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-2404069048763505942</id><published>2008-10-30T10:51:00.000-07:00</published><updated>2008-10-30T11:31:30.590-07:00</updated><title type='text'>How to audit your code ?</title><content type='html'>Today I thought about this again. We're currently using DB triggers to log our audit data. We're going to rework the project, so yes, adding the audit structures is still on the TODO list. But anyway ... why not do it in the DB ? Well ... simply maintenance.&lt;br /&gt;&lt;br /&gt;Using AOP proves to be way better. Cutting across your entire application, and using Java's reflection API, you could write a nice Audit Interceptor to log all your activity.&lt;br /&gt;&lt;br /&gt;Storing your audit data in the DB is just going to increase your application's transaction overhead and degrade response time. Why everybody seems to be storing their log data in the DB, I don't really have a clue. Maybe it's all about reliability and securing your data ? Don't want to lose that very important audit file on your file system ... But, what happened to just assigning user privileges to your log files, or even making backups if you're really that paranoid ? Using that LogFactory proves to be useful for auditing after all.&lt;br /&gt;&lt;br /&gt;Anyhow, for those that don't know much about AOP ... yet ... here's a primer:&lt;br /&gt;&lt;br /&gt;I think of AOP as some kind of interceptor, a listener of sorts. Imagine a long line connecting two points in space. Information is travelling along this line, but you'd like to know more about the information. So you put some sort of listening device (called an &lt;span style="font-weight: bold;"&gt;advice&lt;/span&gt; in AOP terminology) at the line. Inside this &lt;span style="font-weight: bold;"&gt;advice&lt;/span&gt; your allowed to modify the content of the information, process it, or even use it to perform some other decision logic or tasks. The place where you connect your &lt;span style="font-weight: bold;"&gt;advice &lt;/span&gt;to the communication link is called your &lt;span style="font-weight: bold;"&gt;join point&lt;/span&gt;. Now imagine multiple data links, which ones you connect to with your &lt;span style="font-weight: bold;"&gt;advice&lt;/span&gt; is called your &lt;span style="font-weight: bold;"&gt;point cut&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;The great thing about AOP is that it's able to encapsulate the &lt;span style="font-weight: bold;"&gt;scattered&lt;/span&gt; code of your application. Whenever you've got some common functionality scattered across your entire application, consider using &lt;span style="font-weight: bold;"&gt;AOP &lt;/span&gt;or a &lt;span style="font-weight: bold;"&gt;Filter&lt;/span&gt;. A filter will be more useful for the communication link to the outside world of your application, while AOP would be more useful for the communication link inside it.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-2404069048763505942?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/2404069048763505942/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=2404069048763505942' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2404069048763505942'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2404069048763505942'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/10/how-to-audit-your-code.html' title='How to audit your code ?'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-2608708358348235761</id><published>2008-09-19T14:15:00.000-07:00</published><updated>2008-09-19T15:47:25.446-07:00</updated><title type='text'>JEE Pattern: The Intercepting Filter [part 1]</title><content type='html'>Logging, security, compression, network analysis, and even HTML decoration all make use of the request-response packets going from and to your application. When writing some component (maybe even with the intention of being reusable) to perform the task(s) at hand, you would probably end up with some "if-then-else" &lt;span style="font-weight: bold;"&gt;decision logic&lt;/span&gt;. This would control the packet stream's flow of execution. However, you'll probably end up with duplicate code in multiple (if not all) conditional branches of your control unit; all performing the same task. Furthermore, hard coding the flow of control will probably result in an application specific solution.&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-weight: bold;"&gt;dynamic behaviour&lt;/span&gt; in this context would be the individual/unique operations performed by each process unit for logging, security etc. The &lt;span style="font-weight: bold;"&gt;static behaviour&lt;/span&gt; in this context would be the packet stream itself. To write a reusable component we would need to capture the dynamic content and encapsulate it. Rather than having a component with decision logic to address every conceivable configuration or setup, we could instead use several smaller components that are declared declaratively. These components would then be declared in a configuration file, each one contributing to the application's specific need.&lt;br /&gt;&lt;br /&gt;The small individual components would add small features such as logging or security to the system, thus encapsulating the dynamic behaviour. For reusability, it is important to decouple these components from any application specific code. The best place to put these components would either be before or after the packet stream enters the application. This leads to the definition of the terms &lt;span style="font-weight: bold;"&gt;pre-processing&lt;/span&gt; and &lt;span style="font-weight: bold;"&gt;post-processing&lt;/span&gt; of an incoming HTTP request. The individual, reusable components are called &lt;span style="font-weight: bold;"&gt;filters&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;The Servlet Specification, version 2.3, includes a standard mechanism for building filter chains and unobtrusively adding or removing filters from those chains. To build up this chain of filters, some sort of filter-to-filter communication would be needed. How would a filter know which filter to send to next ? The solution is to use a filter manager. The filter manager will read an application's filter configuration file and use it to manage the filtering process. Each filter would then need to adhere to some common filter interface so that the manager would know how to invoke each one. This is called the &lt;span style="font-weight: bold;"&gt;Standard Filter Strategy&lt;/span&gt; and is only one of many strategy's for applying the Intercepting Filter pattern.&lt;br /&gt;&lt;br /&gt;The code below gives you an idea of how a filter looks like. The &lt;span style="font-weight: bold;"&gt;doFilter&lt;/span&gt; method will cause the next filter in the filter chain to be executed. A request would enter the first filter in the filter chain and move through consecutive filters until it enters the application itself. Upon return, the response would move through the same filters, but this time in the opposite order.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;/**&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;    * This code is from an example within "core J2EE PATTERNS, Best Practices and Design&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;    * Strategies".&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;  **/&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;public class BaseEncodingFilter implements javax.servlet.Filter {&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       private javax.servlet.FilterConfig filterConfig;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;  &lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       public void doFilter(javax.servlet.ServletRequest servletRequest,&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                                          javax.servlet.ServletResponse servletResponse,&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                                          javax.servlet.FilterChain filterChain) &lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                                          throws java.io.IOException, javax.servlet.ServletException {&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                filterChain.doFilter(servletRequest, servletResponse);&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       protected javax.servlet.FilterConfig getFilterConfig() {&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                return filterConfig;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       public void destroy() { }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       public void init(javax.servlet.FilterConfig filterConfig) &lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                                         throws javax.servlet.ServletException&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;                this.filterConfig = filterConfig;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;       }&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(153, 153, 153);"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In the subsequent parts, I will elaborate more on other Intercepting Filter strategies&lt;br /&gt;and the filter process overall to eventually write a complete Filter component.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-2608708358348235761?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/2608708358348235761/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=2608708358348235761' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2608708358348235761'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2608708358348235761'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/09/jee-pattern-intercepting-filter-part-1.html' title='JEE Pattern: The Intercepting Filter [part 1]'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-2098559900171261759</id><published>2008-09-16T11:01:00.001-07:00</published><updated>2008-09-16T11:57:07.998-07:00</updated><title type='text'>Entity Manager: Persistence in EJB3</title><content type='html'>The entity persistence manager for EJB is a common interface to your ORM of choice (allowing you to choose between Hibernate, Ibatis and others). When confronted with a situation where the EJB QL is not specific enough for your needs consider using a native query.&lt;br /&gt;&lt;br /&gt;The EJB framework allows several ways for creating a native SQL query:&lt;br /&gt;&lt;br /&gt;[1] If your table column names match the ones in your model object, then you could write your query like this:&lt;br /&gt;&lt;pre class="programlisting"&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;String sqlQuery = "select * from table_name where field = ?";&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;Query q = entityManager.createNativeQuery(sqlQuery, ObjectEntity.class);&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;Here your ORM will automatically populate your ObjectEntity bean with all the corresponding field values from the retrieved database result set. It's important that every field name in your bean class exactly corresponds with the table's column names.&lt;br /&gt;&lt;br /&gt;[2] If your table column names differ from your bean's field names, then you'll have to specify a mapping. When using the EJB QL this mapping is done for you by the underlying ORM. You'll have to specify this mapping using the javax.persistence SqlResultSetMapping annotation:&lt;br /&gt;&lt;pre style="font-family: arial; font-weight: bold;" class="programlisting"&gt;@SqlResultSetMapping(name="MyMappingName",&lt;br /&gt;   entities={&lt;br /&gt;       @EntityResult(name="package.ObjectEntity", fields = {&lt;br /&gt;           @FieldResult(name="id", column="table_column_id"),&lt;br /&gt;           @FieldResult(name="date", column="table_column_date"),&lt;br /&gt;           @FieldResult(name="area", column="table_column_area")&lt;br /&gt;       })&lt;br /&gt;   }&lt;br /&gt;)&lt;/pre&gt;"MyMappingName" is a unique name identifying the mapping declaration. The EntityResult annotation declares the particular bean to be populated with the database query data. Every nested FieldResult annotation maps a bean field name to its corresponding column name. The bean's field names are declared using the "name" property, while the "column" property declares the column name. Then instead of specifying the bean class you specify the mapping name within your native query like so:&lt;br /&gt;&lt;pre class="programlisting"&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;String sqlQuery = "select * from table_name where field = ?";&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;Query q = entityManager.createNativeQuery(sqlQuery, "&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;MyMappingName&lt;/span&gt;"&lt;span style="font-family: arial; font-weight: bold;"&gt;);&lt;/span&gt;&lt;/pre&gt; [3] Today I experienced a different problem. What if you'd like to populate a bean's fields with the query result, but the bean itself is not managed by the ORM. For scenarios [1] and [2], the assumption was made that ObjectEntity.class is a managed object (declared with an @Entity annotation or within the XML persistence configuration file). Hibernate provides for such a scenario with the ResultTransformer method. The data can be mapped and populated to the ObjectEntity bean using this format:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;session.createSQLQuery("select id, date, area from table_name")&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;                  .setResultTransformer(Transformers.aliasToBean(ObjectEntity.class))&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;However, (as I discovered today), standard EJB QL doesn't support a transformer like Hibernate does. In that case one would have to resort to populating the data oneself. The results of a native query is just an Object[]. Every column value is added sequentially in order (as indicated by the select statement) repeatedly for each row. To retrieve the data iterate over the result list, cast the individual column values to their respective types and use it to populate a new ObjectEntity for every new row:&lt;br /&gt;&lt;pre class="programlisting"&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;String sqlQuery = "select * from table_name where field = ?";&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;Query q = entityManager.createNativeQuery(sqlQuery&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;);&lt;br /&gt;List resultList = q.getResultList();&lt;br /&gt;&lt;br /&gt;// Declare a list for holding the rows of ObjectEntityData&lt;br /&gt;List&lt;objectentity&gt; listOfObjects = new ArrayList&lt;objectentity&gt;();&lt;br /&gt;&lt;br /&gt;// Iterate over the resultList using an Iterator&lt;br /&gt;...&lt;br /&gt;while( iterator.hasNext() ) {&lt;br /&gt;     Object[] columns = iterator.next();&lt;br /&gt;     ObjectEntity objectEntity = new ObjectEntity();&lt;br /&gt;     Long idValue = (Long) columns[0];&lt;br /&gt;     objectEntity.setId(idValue);&lt;br /&gt;     ...&lt;br /&gt;     listOfObjects.add(objectEntity);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-family: arial;"&gt;&lt;/span&gt;&lt;span style="font-family: arial;"&gt;That's it ! Now you can bypass the ORM alltogether for extracting data into your system.&lt;br /&gt;NOTE: The code i've written here wasn't tested and might contain syntax errors, but the principle works.&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-2098559900171261759?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/2098559900171261759/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=2098559900171261759' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2098559900171261759'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2098559900171261759'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/09/entity-manager-persistence-in-ejb3.html' title='Entity Manager: Persistence in EJB3'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-8893806436308505885</id><published>2008-09-15T10:20:00.000-07:00</published><updated>2008-09-15T12:00:40.061-07:00</updated><title type='text'>Abstract Factory Pattern</title><content type='html'>&lt;span style="font-weight: bold;"&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;As my first September post I've decided to write a bit about the Abstract Factory.&lt;/span&gt;&lt;br /&gt;Remember from the previous posts that the main idea of a reusable object is to capture your dynamic content. In the case of the Abstract Factory, the dynamic component might not seem obvious at first.&lt;br /&gt;&lt;br /&gt;It helps to compare this pattern to an "actual factory" e.g. a car factory. The factory produces cars and these cars may be grouped into categories (or products if you'd like). However, each category may consist of several versions of the "same" car (a different colour, different sound system, special add-ons), all tweaked and modified to fit a client's specific needs. Every car is built similar with four wheels, similar framework, and using the same materials.&lt;br /&gt;&lt;br /&gt;The same principle applies in software development. You might need to produce the same component (e.g. a window, scrollbar or a panel), but would like to have each component BEHAVE or LOOK differently on different platforms or situations (each one customised to fit the client's specific needs).&lt;br /&gt;&lt;br /&gt;The Abstract Factory is abstract, which implies that the actual behaviour or cosmetics is delegated to its implementation. The idea of the Abstract Factory pattern is to have the client code call a particular Concrete Factory implementation to produce the desired components. Each factory might produce windows, scrollbars and panels with a specific theme (e.g. one might produce grey windows while another creates windows that are blue). You end up having several Concrete Factories; each one adding its own touch to the products it produces.&lt;br /&gt;&lt;br /&gt;At first you might be tempted to use the Decorator pattern, but this pattern is more usefull in encapsulating extending functionality. It wraps over an existing object and adds more functionality. This could prove to be a better solution than simple subclassing in some scenarios, but the Abstract Factory scenario is different.&lt;br /&gt;&lt;br /&gt;A situation might arise where we would like to choose between several of these decorated objects (each one having just a small difference from the other). This would imply an explosion of objects that all look the same, act the same and are used in the same way. Instead of a complex system with thousands of objects, we could try to encapsulate the dynamic component which in this case is the small difference between the various object types or products (e.g. the colour difference between the different types of windows, scrollbars or panels). That is where the Abstract Factory pattern becomes usefull where each Concrete Factory produces its own family of products all using the same theme or colour schema.&lt;br /&gt;&lt;br /&gt;Some tips for using this pattern. Use an Abstract Factory:&lt;br /&gt;&lt;br /&gt;[1] When decoupling is needed between your system and some individual products. How the underlying components or products are created, composed and represented becomes independent of system behaviour. The system only interacts with abstract interfaces to the underlying components.&lt;br /&gt;&lt;br /&gt;[2] When the small differences (e.g. colour) are existent between entire families of products.&lt;br /&gt;&lt;br /&gt;[3] When the family of products is designed to be used together (because they're all using the same theme for example).&lt;br /&gt;&lt;br /&gt;[4] When you'd like to provide a library of products, but just reveal their interfaces and not their implementations to the system.&lt;br /&gt;&lt;br /&gt;Usually the Concrete Factory is instantiated as a singleton (since only one factory is required for every family). The individual products are instantiated using the factory itself and doesn't care whether the factory is a singleton or not. This is analogous to several cars produced in the same car factory (having only one factory doesn't mean you're obliged to produce only one car). On the other hand, you might have several different factories (Mercedes, BMW etc.) each producing their own "families" of cars.&lt;br /&gt;&lt;br /&gt;The main point is this: use an Abstract Factory to produce entire families of products or components with some special attribute that distinguishes them from the other families.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-8893806436308505885?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/8893806436308505885/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=8893806436308505885' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/8893806436308505885'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/8893806436308505885'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/09/abstract-factory-pattern.html' title='Abstract Factory Pattern'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-2592250076987189929</id><published>2008-08-08T12:03:00.000-07:00</published><updated>2008-09-19T15:48:23.461-07:00</updated><title type='text'>EL Functions, Tag Files, Custom Tags and TLD's</title><content type='html'>When adding dynamic behaviour (using tags) to your JSP pages,&lt;br /&gt;you'll probably come across 1 of 3 different techniques:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;EL functions&lt;/strong&gt;: When you'd like to perform some simple algorithm function using Java.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Classic Custom Tags&lt;/strong&gt;: Really old school. Rather make use of JSP 2 Simple Custom Tags if possible&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Simple Custom Tags&lt;/strong&gt;: Gives a little more power over EL functions. Like making use of the body content within the tag and customising the tag's behaviour.&lt;/li&gt;&lt;/ul&gt;It's always a good idea to create a TLD (tag library descriptor) whenever creating your new tag.&lt;br /&gt;I think of the TLD as: &lt;cite&gt;the thing that "describes" the behaviour of your tag to all your other components&lt;/cite&gt;.&lt;br /&gt;&lt;br /&gt;An EL function, is like invoking a Java function that would return a String value. The String result is then printed to your JSP page using the JspWriter. E.g. say you'd like to invoke a Java function that will return a given string attribute in upper case. Then your Java function might look like so:&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;// imports and package declaration here&lt;br /&gt;&lt;br /&gt;public class StringManipulation {&lt;br /&gt;public static String toUpperCase( String stringToModify ) {&lt;br /&gt;return stringToModify.toUpperCase();&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;One thing to note, is that the Java function for your EL Function has to be public and static, or you'll get compilation errors. Why static ? Well ... think of it this way. You're using an EL function, which means you'll call it just like any other EL as: ${value}. You're simply exporting a value, and by creating a new object instance for every call, would just be unnecessarily computationally expensive.&lt;br /&gt;&lt;br /&gt;The next step is to describe your new functions' behaviour in the TLD.&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;taglib ... &gt;&lt;br /&gt;&amp;lt;tlib-version&gt;1.0&amp;lt;/tlib-version&gt;&lt;br /&gt;&amp;lt;function&gt;&lt;br /&gt;&amp;lt;name&gt;upper&amp;lt;/name&gt;&lt;br /&gt;&amp;lt;function-class&gt;pckname.StringManipulation&amp;lt;/function-class&gt;&lt;br /&gt;&amp;lt;function-signature&gt;java.lang.String toUpperCase( java.lang.String ) &amp;lt;/function-signature&gt;&lt;br /&gt;&amp;lt;/function&gt;&lt;br /&gt;&amp;lt;/taglib&gt;&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;But, there's more. You might be moving your TLD around ... and besides, how will you be able to uniquely identify your tag from all the other millions of tags in the world ... ? Mmm ...&lt;br /&gt;&lt;br /&gt;That's where the use of a URI (Uniform Resource Identifier) comes into play. Have you noticed that every URL (Uniform Resource Locator) you type into your browser is unique. Well it had to be, otherwise which HTML page would be displayed ? So it's safe to say, that every URL is unique, but what about a component name ? Is it possible to declare a universally unique name for your function ? Well, that's exactly what the URI is used for, and usually it takes on the format of a URL (since the URL is unique of course).&lt;br /&gt;&lt;br /&gt;This tag mapping must be defined in your deployment descriptor (web.xml).&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;web-app ... &gt;&lt;br /&gt;...&lt;br /&gt;&amp;lt;servlet&gt;&lt;br /&gt;...&lt;br /&gt;&amp;lt;/servlet&gt;&lt;br /&gt;...&lt;br /&gt;&amp;lt;taglib&gt;&lt;br /&gt;&amp;lt;taglib-uri&gt;http://pckName/StringFunctions&amp;lt;/taglib-uri&gt;&lt;br /&gt;&amp;lt;taglib-location&gt;/WEB-INF/pckName/StringFunctions.tld&amp;lt;/taglib-location&gt;&lt;br /&gt;&amp;lt;/taglib&gt;&lt;br /&gt;...&lt;br /&gt;&amp;lt;/web-app ... &gt;&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;Now, all you need to do, is to import your tag's TLD using the specified URI in web.xml,&lt;br /&gt;and then you can use it !&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;%@ taglib prefix="myPrefix" uri="http://pckName/StringFunctions"%&gt;&lt;br /&gt;...&lt;br /&gt;${myPrefix:toUpperCase(param.stringToModify) }&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;URI's can be classified into 3 different categories:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Absolute URI&lt;/strong&gt;: Has a protocol, hostname etc. E.g. "http://www.whatever.com"&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Root Relative URI&lt;/strong&gt;: Starts with a '/', and is interpreted as relative to the document root. E.g. "/myLibrary" &lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Non-root Relative URI&lt;/strong&gt;: Doesn't start with a '/', and is interpreted as relative to the current JSP page or WEB-INF directory (depending on its location). E.g. "myLibrary".&lt;/li&gt;&lt;/ul&gt;Custom tags and EL functions have many similarities, other that with custom tags you're able to do more. You've got more control over the tag's life-cycle and how it deals with any "body-content", in between the opening and closing tag definitions.&lt;br /&gt;&lt;br /&gt;Whereas, the EL Function had a corresponding Java (public and static) function, a custom tag has a Java tag handler. This tag handler is where you'll write your Java code to perform whatever you'd like your tag to do.&lt;br /&gt;The TLD of a EL Function only required a "taglib-version" and "function" declaration. A custom tag must specify it's unique URI name, and a "tag" element. Rather than &lt;cite&gt;describing&lt;/cite&gt; function behaviour as with EL Functions, here we &lt;cite&gt;describe&lt;/cite&gt; tag behaviour instead. In this case, we can declare the behaviour of several tags with the same prefix, within a single TLD.&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;taglib&gt;&lt;br /&gt;&amp;lt;tlib-version&gt;1.0&amp;lt;/tlib-version&gt;&lt;br /&gt;&amp;lt;jsp-version&gt;2.0&amp;lt;/jsp-version&gt;&lt;br /&gt;&amp;lt;short-name&gt;prefixForTags&amp;lt;/short-name&gt;&lt;br /&gt;&amp;lt;uri&gt;http://www.whatever.com&amp;lt;/uri&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;tag&gt;&lt;br /&gt;&amp;lt;name&gt;aSpecificTagName&amp;lt;/name&gt;&lt;br /&gt;&amp;lt;tag-class&gt;pckName.TagHandlerClassName&amp;lt;/tag-class&gt;&lt;br /&gt;&amp;lt;body-content&gt;tagdependent&amp;lt;/body-content&gt;&lt;br /&gt;&amp;lt;description&gt;Accepts body content within tag as normal text. Performs some function as well.&amp;lt;/description&gt;&lt;br /&gt;&amp;lt;attribute&gt;&lt;br /&gt;&amp;lt;name&gt;user&amp;lt;/name&gt;&lt;br /&gt;&amp;lt;required&gt;false&amp;lt;/required&gt;&lt;br /&gt;&amp;lt;rtexprvalue&gt;true&amp;lt;/erexprvalue&gt;&lt;br /&gt;&amp;lt;/attribute&gt;&lt;br /&gt;&amp;lt;/tag&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;body-content&lt;/strong&gt;: Describe what body-content is allowed to be present between the opening and closing elements of your tag. 'empty'- No body content allowed. 'JSP'- Body content is treated as normal JSP code. 'tagdependent'-The body content is treated as normal text.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;required&lt;/strong&gt;: Describes that this attributes' name-value pair must be declared when using the specified tag element.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;rtexprvalue&lt;/strong&gt;: Describes that the value specified for the underlying attribute. It must be a literal (false) or may be a dynamic value as well (true).&lt;/li&gt;&lt;/ul&gt;Depending on the particular Tag interface you're implementing,&lt;br /&gt;you may be required to implement the following in your tag handler:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Setter methods for your tag's attributes.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;doStartTag()&lt;/strong&gt; method, executed as the beginning of your tag element declaration. Here you can specify any initialization code for your tag-handler. A return value of EVAL_BODY_INCLUDE says that the body content of your tag must be evaluated, and its output included in the response. A return value of SKIP_BODY says that the body content must not be processed.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;doAfterBody()&lt;/strong&gt; method (if implementing the iteration or body tag interfaces). It gives the tag handler to evaluate the body content again, only AFTER the first iteration. Can return EVAL_BODY_AGAIN to process the body content again, or SKIP_BODY to go on to the end of the tag. If implementing the body tag interface, EVAL_BODY_BUFFERED allows you to pre-process the body content, before anything is written to the response.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;setContentType()&lt;/strong&gt; method (if implementing the body tag interface). The JSP container calls this method to pass an instance of the body content to the tag handler.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;doInitBody()&lt;/strong&gt; method (if implementing the body tag interface). The container calls the doInitBody() method AFTER the setContentType() method, and allows the tag handler to initialize the body content object passed to it.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;doEndTag()&lt;/strong&gt; method is the last method that executes before the tag processing exits. Here you can specify whether the rest of the JSP page should be evaluated EVAL_PAGE, or should be skipped all together SKIP_PAGE.&lt;/li&gt;&lt;/ul&gt;The Simple Custom tag is very similar to the Classic Custom tag, except that instead you're only required to override a single method called "doTag()". For your simple tag handler, you must implement the &lt;strong&gt;SimpleTag&lt;/strong&gt; interface. The&lt;br /&gt;&lt;simpletag&gt;interface in return extends the &lt;strong&gt;JspTag&lt;/strong&gt; interface. The &lt;strong&gt;JspTag&lt;/strong&gt; interface was added in JSP 2, so that simple and classic tags could work together. See ... the JspTag is the "SUPER" interface for both simple and classic tags, so we could make use of polymorphism and use both tag types in the same JSP. But why are there 2 different types of tag handlers ? Well ... my guess is that SUN initially made a little of a mistake, by not allowing one to edit/process the body content of a tag at first. Making use of the body tag just added more complexity to the entire process, and the Simple tag method fixed it all.&lt;br /&gt;&lt;br /&gt;In fact, to pre-process the body content using a simple custom tag is simple. Only call the getJspBody() method to get the body content of the tag, and then you'll be able to process the content.&lt;br /&gt;&lt;br /&gt;Anyway, the life-cycle steps for a simple custom tag goes something like (in chronological order):&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;setJspContext(JspContext)&lt;/strong&gt;: Makes the JspContext available during tag processing.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;setParent(JspTag)&lt;/strong&gt;: Sets any parent tag of this tag, if available.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;setXXX(...)&lt;/strong&gt;: Then sets all your specified attributes into the tag handler.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;setJspBody(JspFragment)&lt;/strong&gt;: Makes the body content of the tag available for processing.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;doTag()&lt;/strong&gt;: This invokes your customised doTag() Java method.&lt;/li&gt;&lt;/ul&gt;The TLD for the simple custom tag looks the same as a TLD for a classic custom tag.&lt;br /&gt;&lt;br /&gt;To write the body content of a simple custom tag to the output simply call &lt;cite&gt;getJspBody().invoke(null);&lt;/cite&gt;. The invoke method requires an argument specifying the JspWriter that will receive the JspFragment's output. If 'null' is specified, then the output is directed to the JspWriter returned by getJspContext().getOut(), and is then written directly to the response. To alter the body content, you could also pass in your own &lt;strong&gt;java.io.Writer&lt;/strong&gt;, and use that to gain direct access to the body contents.&lt;br /&gt;&lt;br /&gt;Finally, there's also something called &lt;strong&gt;tag files&lt;/strong&gt; that you may use. A &lt;strong&gt;tag file&lt;/strong&gt; is made up of JSP code that has a &lt;strong&gt;.tag&lt;/strong&gt; or a &lt;strong&gt;.tagx&lt;/strong&gt; extension. The only elements that &lt;strong&gt;CANNOT&lt;/strong&gt; be used in &lt;strong&gt;tag files&lt;/strong&gt; are &lt;cite&gt;page attributes&lt;/cite&gt;. With &lt;strong&gt;tag files&lt;/strong&gt; no Java or TLD files are involved, except if the tag resides in a JAR (then a TLD is required). This is because, the container is only required (by specification) to look under the &lt;strong&gt;/WEB-INF/tags/..&lt;/strong&gt; directory, in order to find a tag file.&lt;br /&gt;&lt;br /&gt;To integrate tag files into a JSP involves 2 steps:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Add a &lt;strong&gt;taglib&lt;/strong&gt; directive to the JSP page with a &lt;strong&gt;prefix&lt;/strong&gt; attribute and the &lt;strong&gt;tagdir&lt;/strong&gt; attribute, indicating where your tag file resides (must be under /WEB-INF/tags/ ...).&lt;/li&gt;&lt;br /&gt;&lt;li&gt; Use the tag wherever on your page, containing the &lt;strong&gt;prefix&lt;/strong&gt; and the &lt;strong&gt;name&lt;/strong&gt; of the tag file.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;What happens, is that the container searches for the specified &lt;strong&gt;tag file&lt;/strong&gt; in the &lt;strong&gt;tagdir&lt;/strong&gt; directory. After the container finds the &lt;strong&gt;tag file&lt;/strong&gt; it automatically builds an implicit tag library and TLD for this directory and each subdirectory beneath it.&lt;br /&gt;&lt;br /&gt;If a tag resides in a JAR, then the &lt;strong&gt;tag file&lt;/strong&gt; must reside under &lt;strong&gt;/META-INF/tags&lt;/strong&gt;, and a relating TLD &lt;strong&gt;MUST&lt;/strong&gt; be created. Below is an example of a TLD for an archived &lt;strong&gt;tag file&lt;/strong&gt;:&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;taglib&gt;&lt;br /&gt;...&lt;br /&gt;&amp;lt;uri&gt;www.whatever.com/example&amp;lt;/uri&gt;&lt;br /&gt;&amp;lt;tag-file&gt;&lt;br /&gt;&amp;lt;name&gt;example&amp;lt;/name&gt;&lt;br /&gt;&amp;lt;path&gt;/META-INF/tags/example.tag&amp;lt;/path&gt;&lt;br /&gt;&amp;lt;/tag-file&gt;&lt;br /&gt;&amp;lt;/taglib&gt;&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;In this case, you cannot use &lt;strong&gt;tagdir&lt;/strong&gt; to locate the &lt;strong&gt;tag file&lt;/strong&gt; to be used inside the JSP. Instead you'll need to specify the &lt;strong&gt;tag file&lt;/strong&gt; location, using its URI, as in:&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;%@ taglib prefix="ex" uri="www.whatever.com/example" %&gt;&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;Your tag file is just normal JSP code. So you could liken it to the include page directive, if you'd like. However, it's a little different than a normal file inclusion. With tag files, you can specify attributes that are &lt;strong&gt;objects&lt;/strong&gt;, other than request parameters which are just &lt;strong&gt;String values&lt;/strong&gt;. Since we don't always need to declare a TLD for &lt;strong&gt;tag file&lt;/strong&gt;, how would it know what its attributes are, and how will it retrieve them ?&lt;br /&gt;To retrieve attributes you must specify an &lt;strong&gt;attribute directive&lt;/strong&gt; in your tag:&lt;br /&gt;&lt;strong&gt;&lt;code&gt;&lt;br /&gt;&amp;lt;%@ attribute name="myAttribute" required="true" %&gt;&lt;br /&gt;&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;&lt;strong&gt;OK ... so you now know more about the tags available at your disposal. But how do you decide which one to use, and when ?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;My philosophy is so. If you just like to set data or get data, then rather use &lt;strong&gt;EL&lt;/strong&gt; or &lt;strong&gt;Java beans&lt;/strong&gt;, but if you're going to have to do some Java processing on your data, then &lt;strong&gt;custom tags&lt;/strong&gt; are the way to go. If instead, you're algorithm for data processing is rather simple, and doesn't require complex interaction with the presentation layer, a simple &lt;strong&gt;EL function&lt;/strong&gt; should do the job. Finally, if you're requirements are primarily on manipulation on the presentation layer (such as CSS or some other container elements), then make use of &lt;strong&gt;tag files&lt;/strong&gt;, it will save you development time, effort, and in my opinion is the easiest to use of them all.&lt;br /&gt;&lt;br /&gt;So that was just a little primer about tags. They can be very useful if used appropriately.&lt;br /&gt;Enjoy !!&lt;/simpletag&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-2592250076987189929?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/2592250076987189929/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=2592250076987189929' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2592250076987189929'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/2592250076987189929'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/08/wrote-this-last-week.html' title='EL Functions, Tag Files, Custom Tags and TLD&apos;s'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-465312893224516648.post-4161674363142874652</id><published>2008-08-08T09:53:00.000-07:00</published><updated>2008-10-30T10:20:43.606-07:00</updated><title type='text'>Design Patterns: The STRATEGY pattern.</title><content type='html'>&lt;span style="font-family:arial;"&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;The strategy pattern is a way of thinking, a plan of action. Whether you might know it or not, you've probably implemented it already in some past project of yours :)&lt;br /&gt;&lt;br /&gt;I'll suggest going about like so:&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;ol&gt;&lt;li&gt;&lt;span style="font-family:arial;"&gt;&lt;span style="font-family:arial;"&gt;Classify your project up in parts. Try to identify the things that are more dynamic (the things that change more frequently in your application). Then identify the more static parts.&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style="font-family:arial;"&gt;&lt;span style="font-family:arial;"&gt; If some group(s) of your dynamic parts/components have something in common, well then you might have an opportunity to employ the strategy pattern !!&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ol&gt;&lt;span style="font-family:arial;"&gt;&lt;span style="font-family:arial;"&gt;Your strategy is the "interface" defining the common things in the group you've just made (step 2).&lt;br /&gt;By encapsulating the dynamic parts of your application into objects, you'll be able to break the inheritance layer structure. I've recently found that if you've got a heavy layered structure, consisting of several layers build on top of one another, re-factoring becomes a pain (TDD/XP). In that case consider the strategy pattern as a good alternative.&lt;br /&gt;&lt;br /&gt;Instead of your interface build on layers upon layers of code, try delegating objects to do the particular task for you. Inject them into your structure and see your overall structure being simplified.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/465312893224516648-4161674363142874652?l=flexingcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://flexingcode.blogspot.com/feeds/4161674363142874652/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=465312893224516648&amp;postID=4161674363142874652' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/4161674363142874652'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/465312893224516648/posts/default/4161674363142874652'/><link rel='alternate' type='text/html' href='http://flexingcode.blogspot.com/2008/08/design-patterns-strategy-pattern.html' title='Design Patterns: The STRATEGY pattern.'/><author><name>Michael Matthee</name><uri>http://www.blogger.com/profile/12411147880184566562</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
