Unfamiliarity Causes Rejection

Recently I listened to a talk given by an ex-ThoughtWorker, Simon Harris. One of the things that Simon talked about was how we, developers (and generally speaking – human beings) sometimes tend to reject what is unfamiliar to us. Within software development context it can be an existing/legacy application or a module that we need to extend, and which is difficult to understand.

Really, how many times we looked at someone else’s work (eg:. a developer that has left the company a long time ago) and thought “Dude, this is so weak … come one”?

Instead of just pointing fingers, maybe we should stop for a moment, try to think and understand, what were the reasons for producing that mediocre piece of code? Look at the current software’s state from a different angle. Sure, sometimes a poorly written software is simply just that – a poorly written software without a particular reason. But at other times, perhaps there were unknown variables in the equation that prevented developers produce something of a higher quality: technical limitations? Some internal politics? Tight deadlines? Environment?

Understanding the historical/current state of an application, can only help us to come up with better results in the long run. I really enjoyed Simon‘s talk, he clearly draws from his extensive experience.

LateX – Transparent Watermark Image

If you want to add a watermark image to your LaTeX document, you can achieve it easily using three packages: graphicx, tikz and eso-pic:

Graphicx package allows to load images into documents. If you want to add transparency to your image, you need also to use tikz package. Tikz is used for producing vector graphics from a geometric/algebraic description, but is also allows to play with opacity levels.

Eso-pic package provides hooks to inserts the images on one or more pages as a background (in other words – a watermark).

\\usepackage{graphicx}
\\usepackage{tikz}
\\usepackage{eso-pic}

\\newcommand\\BackgroundPicA{\\put(270,440){{%
\\begin{tikzpicture}\\node[opacity=0.1]{%
\\includegraphics[scale=0.80]{letter-watermark.jpg}};%
\\end{tikzpicture}%
}}}

\\newcommand\\BackgroundPicB{\\put(-80,-40){{\\reflectbox{%
\\begin{tikzpicture}%
\\node[opacity=0.1]{%
\\includegraphics[scale=0.80]{letter-watermark.jpg}};%
\\end{tikzpicture}%
}}}}

\\makeatletter%
\\AddToShipoutPicture{\\BackgroundPicA}%
\\AddToShipoutPicture{\\BackgroundPicB}%
\\makeatother

\\begin{document}
.
.
\\newpage
.
.
\\end{document}

I have attached a final result as PDF, so you can see the output: PDF with semi-opaqued watermark.

LateX – Style Section Title With a Color Filled Box

I was playing with LaTeX in order to create a resume template for my self. I was looking for a way to style title generated by the \section command. My goal was to generate color filled box with some text inside and some padding.

This is what I have came up with:

\\definecolor{gray}{RGB}{186,186,186}
\\section{\\fcolorbox{black}{gray}{\\color{black}%
{\\parbox{6.5in}{\\vspace{.03in}\\hspace{.03in}\\LaTe X{ is really cool}\\vspace{.03in}}}}}

Which produced the following result:

LaTex - Style section title with a colored filled box

I Have Joined the ThoughtWorks Camp

I have some good news: I am going to be a ThoughtWorker. After two or three weeks of interviews, I have recently accepted their offer and going to start with the company in August.

I am really looking forward to it, since many bright, passionate and talented people work for ThoughtWorks. The company is known for its cutting-edge technology development and being one of the global leaders in enterprise Agile development services. In other words, I am really happy :)

I will keep writing updates from time to time about my experience at ThoughtWorks. Stay tuned.

Write Operations in DWR

Write operations are not allowed with the default session setting for the OpenViewInSession filter which is commonly defined in web.xml as a hibernate filter. If you want to enable write operations when using DWR (Direct Web Remoting), one of the ways is to declare a filter for DWR urls. Put the following configuration in your web.xml, also please note the url pattern in filter-mapping element.


<filter>
<filter-name>dwrWriteHibernateFilter</filter-name>
<filter-class>
some.package.name.OpenWriteSessionInViewFilter
</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>dwrWriteHibernateFilter</filter-name>
<url-pattern>*.dwr</url-pattern>
</filter-mapping>

The filter class as follows:

// more imports
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;

public class OpenWriteSessionInViewFilter extends OpenSessionInViewFilter {

protected Session getSession(SessionFactory sessionFactory)
throws DataAccessResourceFailureException {
Session session = super.getSession(sessionFactory);
session.setFlushMode(FlushMode.COMMIT);
return session;
}

protected void closeSession(Session session, SessionFactory factory) {
session.flush();
super.closeSession(session, factory);
}
}

Is TDD Only for … Junior Developers??

Just before the Easter holidays, I had a discussion with two senior developers from my project about TDD. These guys are experienced software engineers that have been around for some time: they have 11 and 20 years of experience in software development under their belts.

I don’t claim to be an advocate for TDD. Currently, I do not practice it (yet), but I do recognize and appreciate its importance. TDD really “forces” you to have clear understanding about the business requirements to be implemented. You cant implement what you do not understand, right? Because you have to write the test first, your code becomes more solid, less bug prune and you have better test coverage.

Sure, writing the test first its an interesting concept: You start writing a test, and you discoverer that you need a class, and possibly a function. You create the class, function and keep writing the test. Basically, you write few lines of test, and few lines of code, few more lines of test and few more lines of code etc. etc.

Ok, I think I diverted a bit, back to the topic :) The discussion took an interesting turn, and I still keep thinking about it. My question to them was – what do you think about TDD? The responses I received totally surprised me.

One of the claims supported by them, was that TDD does not serve much purpose, and a developer will end up re-factoring the unit tests eventually anyway as a result of re-factoring the concrete classes as the development goes on. So if latter is the case, my colleagues argued that there is no point writing unit tests first. Its better to finish writing concrete class, before attempting to write any unit tests.

Also, one of the developers claimed that many books and articles written on TDD discuss examples that are quite simple to implement, and in reality it is quite difficult to use TDD for complex business scenarios.

Another claim was that TDD should be used to teach junior developers the importance of unit testing, the experienced developers don’t really need to use it. The developers should follow KISS principles instead.

I respected their opinions about it, but it seemed fundamentally wrong to me that such experienced developers claim that TDD is basically overrated. The feeling that I got from them was that a lot of developers and software engineers in IT industry really got it wrong.

It got me wondering how, after more than ten years of experience in the industry, one does not appreciate one of the best software engineering practices around …

Offcourse, having said all that, I must point out that TDD is not suitable for every case. TDD can be effective only when it is clear what need to be implemented and there is a deep understanding of requirements.

Jquery UI: Add a Shadow Line Around a Dialog Box

I really like the style of Facebook (or LinkedIn) Javascript popup dialogs – a thin semi-transparent shadow line around the dialog. It looks nice and from the usability point of view it has a purpose, as it is attracts user’s attention to the important component on the screen.

There are many examples of custom Javascript dialogs on the Internet that explain how to achieve this. While many solutions are really good, I wanted to make use of the dialog provided by jQuery UI library by default.

I have came up with a solution that works, but I don’t think it is the most elegant way to do it (CSS is not my strong side). The solution is quite simple, and pretty straight forward (I think :) ). The following are the final results as tested in FF3, IE8, Opera 10 and Chrome 10, please note the shadow line around the dialog:

Firefox - jQuery dialog box with semi-transparent shadow around it

Firefox 3.6.16

Internet Explorer - jQuery dialog box with semi-transparent shadow around it

Internet Explorer 8.0.76

opera-10.63

opera-10.63

chrome-10.0.648

First I defined a CSS class that’s going to have properties for the background shadow (the bg_dialog_modeless_mask.png is an 8×8 gray square image)

.dialog-mask {
 -moz-border-radius:5px 5px 5px 5px;
 -webkit-border-radius: 5px;
 border-radius: 5px;
 background:url("../images/bg_dialog_modeless_mask.png") repeat scroll left top transparent;
}

Somewhere on my HTML page, I defined a DIV that’s going to be the dialog holder:

<div id="popup-holder"></div>

I added jQuery dialog init statement in my global JS file:

$(document).ready(function(){

 $( '#popup-holder' ).dialog({
       autoOpen: false,
       height: 350,
       width: 530,
       modal: true,
       resizable: true,
       draggable: false,
       buttons: {
         Cancel: function() {
            $( this ).dialog( "close" );
            $( '#dialog-wrapper' ).remove();
         }
      },
      close: function() {
            $( '#dialog-wrapper' ).remove();
      },
      open: function() {
            wrapJqueryDialog($( this ));
      },
      resize: function() {
            wrapJqueryDialog($( this ));
      }
   });
});

The #dialog-wrapper is the ID of the DIV that holds the semi-transparent shadow which wraps the dialog. The wrapJqueryDialog function creates the shadow when dialog is opened, and handles the shadow resize when dialog is resized (it is also possible to add an event to drag the shadow when dialog has draggable option set to true).

Now the important part, the wrapJqueryDialog function:

function wrapJqueryDialog(dialogWidgetObj)  {
	//The width and height of the shadow line wrapping the dialog
        var shadowWidth = 20;

        //Lets remove the shadow holder to start clean
	$( '#dialog-wrapper' ).remove();

        //Gets the current dialog widget
	var widget = dialogWidgetObj.dialog( "widget" );

        //Create the shadow holder DIV that has the background shadow CSS class
	var dialogwrapper = $('<div id="dialog-wrapper" class="dialog-mask" />');

	//For IE, the holder must be appended to the body first before any manipulation.
	$('body').append(dialogwrapper);

        //Lets copy default inline styles from the dialog widget to the shadow holder
	dialogwrapper.attr("style", widget.attr("style"));

        //Lets position the shadow holder before and above the dialog widget
	dialogwrapper.css("top", parseInt(dialogwrapper.css("top")) - shadowWidth);
	dialogwrapper.css("left", parseInt(dialogwrapper.css("left")) - shadowWidth);

        dialogwrapper.css("position", "absolute");

	//Make sure that the dialog widget is infront of surrounding shadow box and overlay (if there is one set)
	widget.css("z-index", (parseInt(widget.css("z-index")) + 1));

	//Add to the shadow width default padding value from the class '.ui-dialog' and
	//default border width from the class '.ui-widget-content' (1px times two)
	var finalShadowWidth = shadowWidth + parseInt(widget.css("padding-top")) + 2;

	var widgetHeight = parseInt(widget.css("height"));
        //Lets extend the shadow holder height
	dialogwrapper.css("height", widgetHeight + (finalShadowWidth * 2));

	var widgetWidth = parseInt(widget.css("width"));
	//Lets extend the shadow holder width
        dialogwrapper.css("width", widgetWidth + (finalShadowWidth * 2));
}

That’s all when it comes to code (don’t forget to add to your HTML/JS code a dialog trigger, it can be a link or a button). I am really interested to hear your comments about it and suggestions. If you can suggest a better way of implementation – please do so, I am really keen to know :)

Java, Good Ways – A Book of Unwritten Rules, Tips and Gotchas

A colleague of mine, who is currently my tech lead, wrote a book.

The book Java, Good Ways is a collection of unwritten rules, tips and gotchas collected over a long period of time. The book comes to minimize the gap between university studies and what Java developers actually need to know.

Have a look, read through, let me know what you think or simply leave a comment on Java, Good Ways :)

Integrating Spring MVC with Hibernate Annotation-Based Validation

In this article, I would like to demonstrate how to integrate Spring MVC, Spring bean validation framework and hibernate validator using annotations. The Hibernate Validator project is implementation of JSR 303 – Bean Validation standard, which defines a metadata model and API for JavaBean validation. For the the purpose of this example, I used Spring Framework v3.0.5 and Hibernate Validator v4.1.0.

What I like about Spring + Hibernate validation, is that this combination eliminates the need to use validator classes in controllers for bean validation. In other words, less code, less classes, everything looks much cleaner.

I am not going to talk about how to build web application from scratch using Spring MVC. I assume that you already have something working in place. I am just going to show the important bits needed, in order to plug hibernate validation in to your code:

1. Define two following beans in your application context XML in your WEB-INF directory:

<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

The basic configuration above will trigger JSR-303 to initialize using its default bootstrap mechanism. A JSR-303 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically.

<bean id="messageSource"
     class="org.springframework.context.support.ResourceBundleMessageSource">
	<property name="basename" value="/WEB-INF/message-resources.bundle" />
</bean>

The bean above knows how to access resource bundles using specified basenames.

2. Create resource bundle (in this example it is “message-resources.bundle”) under WEB-INF. The resource bundle is where you should define your validation messages that the end user sees if his form submission fails validation. Please note that the bundle does not have to be at the root of WEB-INF, it can be placed also in a sub-directory of WEB-INF. The format for validation messages in your bundle should be as follows:

Annotation.bean-variable-name.bean-propery=validation error message.

For example:

NotBlank.someFormName.name=Name must not be blank,
Size.someFormName.name=Name must be less than or equal to {1} characters.
NotBlank.someFormName.street=Street name should not be blank. Please enter a value
NotEmpty.someFormName.selectedItem=Item selection is required

The example above describes four different validation messages for different validation rules. In case of a particular validation rule disobeyed, its respective validation message will be found based on the validation annotation, bean name and bean property name.

3. In your controller, in the method that validates bean from the POST request, annotate your bean with annotation @Valid. For example:

@RequestMapping(value = "/update.html", method = RequestMethod.POST)
 public String update (    @ModelAttribute("someFormName")
 @Valid SomeForm someFormName,
 BindingResult result,
 Model model)
 {

 if(result.hasErrors()) {
 // Return view name
 }

 // Do stuff

 // Return view name
 }

The @Valid annotation is part of the standard JSR 303 – Bean Validation API, and is not a Spring-specific construct. The Hibernate Validator instance invoked when a @Valid method argument is encountered.

Very important: your bean variable name in your controller method (in this case its “someFormName“) must match the bean variable name in your validation message resource bundle.

4. Annotate your bean member variables with annotations that tell Hibernate Validator what should be validated and what are the validation rules:

public final class SomeForm {

 @NotBlank
 @Size(min=0,max=20)
 private String name;

 @NotBlank
 private String street;

 @NotEmpty
 private String selectedItem;

 // Getters

 // Setters
}

As you can see from the above bean, the three fields that should be validated are annotated with @NotBlank, @NotEmpty and @Size. The validation rules are simple: the name property must not be blank nor longer than 20 characters, street property must not be blank, while selectedItem must not be empty.

By the way, you can have more complicated validation rules in place using annotations. It is possible to use expressions which decide whether validation rules should fire. Consider the following, which validate an email field:

@Email(applyIf="email is not blank")
@NotBlank
private String email;

You don’t want to display invalid email format error message when the filed is blank. Therefore that above expression in @Email annotation will have the rule fired only when the property is not blank. Expression can be especially very convenient when validating password fields:

@NotBlank
private String password;

@NotBlank(applyIf = "password is not blank")
@Expression(value = "confirmedPassword= password", applyIf = "password is not blank")
private String confirmedPassword;

Validation rules for confirmedPassword property will fire only when password field will not be blank.

That’s it :) If any rule(s) are disobeyed, the BindingResult result object will be populated with appropriate error messages, loaded from your message bundle. The error messages then can be displayed in your JSP using Spring tag:

<spring:hasBindErrors name="someFormName">
	<c:forEach items="${errors.allErrors}" var="error">
		<spring:message message="${error}"/>
	</c:forEach>
</spring:hasBindErrors>

And that is it! Feel free to post a comment if you run into problems and I iwll try to help you the best I can :)