Your favourite IDE has a powerful debugger which you can use to debug your programs. If you are new to programming, chances are that you are aware of it’s existence, but never use it.

The problem

Here is an example method, which has a problem. (It actually does nothing of value, but demonstrates the problem case). The method doSomething is called with a parameter, but the expected result is not returned.

This is one of the most crude ways to debug a program. Unfortunately it’s quite common between junior developers. Note that if logging needs to be performed (for monitoring or historical purposes) a proper logging framework has to be used.

Things get interesting when the developer forgets to delete those System.out.println statements. The application is deployed, in a servlet container which hosts more applications, featuring code “debugged” in this way.
It’s not rare to see catalina.out logs which look like this:

The solution

Learn to use your debugger. All you have to do is go to the line you want debugging to start, set a breakpoint (CTRL+F8 in Netbeans) and start the debug process. You will either debug the whole application (F5) or that single file/unit test (CTRL+SHIFT+F5).
You can set watches, see the stacktrace and examine the contents of all the local variables at any time in the program execution. You get orders of magnitude more power, in less time; for free!

Unit testing not only ensures that the code you write is correct, but also helps you develop your code. This can be achieved by testing unimplemented methods and functionalities first, and then “filling in” the code to satisfy the tests. This is the “test first” rule that your XP coworker will always remind you, at any occasion. (You do have an XP coworker, don’t you? :)

The Requirement

Suppose you have a webapp which displays some data from a database. Some of those texts are long, and you are asked to be able to truncate them at predefined lengths on some particular views. So instead of printing “Lorem ipsum dolor sit” you should be able to fit that in 12 chars and print “Lorem ips…”.

Wait

The first worst thing you could do there would be to stick that logic straight into the view (JSP, velocity or whatever templating engine you use). You will not be able to test that piece of logic, nor easily reuse it in some other project. You will need to do this in a Java class and then find a way to call it from the template.

The second worst thing you could do would be to implement this functionality yourself, as it already exists in commons lang. You should know what APIs exist out there and try to reuse as often as possible. But anyhow, we’ll assume that you want to do it yourself.

Think

You start by thinking of where to place this method and whether it will be a helper (static?) method or part of a full fledged class with state etc. Then you choose a good method name and what parameters it will accept. Think of how you would like to use this method.

This is a standard idiom for testing that an exception should be thrown. If this method is called with a negative length parameter, we’d like an IllegalArgumentException to be thrown. It is not mandatory to test for things like these, but some people like to seal their methods from really bad usage.

Conclusion

This implementation might not be the best in the world, but right now this doesn’t matter. The code runs, and it’s robust. Whenever you feel like, you can refactor it and make it perform better. The test will be there to guide you.

p.s What we’ve omitted when we wrote the signature of this method, was to write Javadoc. It is very important to document your API, and we’ll discuss that in another post.

New developers will sometimes complain about how Unit Testing requires a lot of time. How much it slows them down, and how they cannot see any good in writing tests for their code.
There are many scenarios which prove that unit testing is necessary. These include speed of development, ability to refactor easily, test-driven development, testing without the need of web container, testing with mock objects etc.

My favorite though is the “client calls to report something weird” scenario. I’ve seen it many times and it goes something like this:

Scenario:

Your webapp is deployed, weeks ago, and you’ve moved on with a new, exciting project. Everything is feels good, as you’ve completely forgotten about sins of the past (not writing tests)

Client calls you to report “something weird”.

You stop whatever you are doing at that moment to switch to that project.

You connect (VPN or whatever) to the remote server to see possibly logged exceptions.

If the above scenario feels OK, and you need some hints on why you should try to minimize such cases, have a look at the costs involved:

Costs:

All of these actions need time. Your time.

Most of them require a context switch. Not only you lose X minutes from your previous work, but also need Y minutes to get back into the flow (mind state) you had previously.

Some of these steps might not be what you really want to be doing (talking directly to the client).

You become a slow worker producing bad code.

People will never trust you with that mission critical application, because your code has a tendency to develop “random features” on runtime (usually involving exciting names such as NullPointerException).

Facts:

This scenario can definitely happen for tested code. Bugs will always creep into your code no matter what. The point is try to at least minimize the stupid ones. Cases which can easily be covered by unit tests.
Unit testing is important (if not mandatory). If you feel that it needs time, you have to press yourself and do it. It’s a matter of weeks until you become test infected and experience how your software becomes better in less time.

JBoss Web is a web server and servlet container at the same time. It’s promise is that it can serve static and dynamic content, very fast, without the need of an Apache HTTPD fronting it. If that’s true, its party time, and I personally live for the day where it will be easy to get Java 5 enabled hosting for ~5USD/month (as it is the case today with LAMP stacks).

JBoss Web uses APR and native extensions in order to achieve better utilization of the resources of the O/S. Note that APR is also available for Tomcat now.

I’ve decided to give JBoss Web a try, locally, and stress test it against a regular Tomcat. Note that what I did was done for pure fun (and out of curiosity). I do not own a lab, I am definitely not a stress test expert and I do not understand many things at the low level (I/O, threads etc).

Test info

JMeter was used and it was running on the same machine with the servers tested.

During tests JMeter would use ~30% of cpu, and the server would consume the rest ~70%.

I stress tested 10 URLs of a very small webapp with a front controller delegating to cached freemarker views. No logging, no persistence or database calls. JBoss’ CONSOLE appender’s threshold was changed to FATAL, to avoid any logging output which would slow down things. The most interesting operations in the webapp would be the GZIP filter, and multipart request using commons fileupload.

Warm up of the servers was performed. I found out that even for small amount of concurrent threads hitting the server, if these all start immediately, it’s most likely you’ll get some 500s at the beginning. The warm up would be anything between 2500-5000 requests until the server throughput was stabilized.

When the server was warmed up, I would get my sample from the next 5000-10000 requests.

The “threads” column in the results table, is the amount of concurrent threads which where hitting the server.

An http cookie manager was used on JMeter, so 10000 sessions were not being created.

Results

threads

Tomcat 5.5.23

JBoss Web 1.0.1

50

95 requests/sec

88 requests/sec

75

105 requests/sec

95 requests/sec

100

123 requests/sec

100 requests/sec

125

75 requests/sec

104 requests/sec

150

110 requests/secat this point I had to increase the maxThreads

110 requests/sec

200

62 requests/sec

97 requests/sec

300

115 requests/sec

108 requests/sec

400

n/aat this point JMeter would block.[25 seconds per page]

80 requests/sec

500

n/a

75 requests/sec

600

n/a

84 requests/sec

700

n/a

55 requests/sec[10 seconds per page]

800

n/a

48 requests/sec[13 seconds per page]

1000

n/a

n/aat this point JMeter would block

Findings

Even this test can be considered rudimentary, JBoss Web looks very good. The biggest problem with the whole procedure is that JMeter was on the same machine as the servers. JMeter supports Remote Testing and Distributed Testing which would have produced more accurate results.

Your front controller will now attempt to serve all URLs, and this is something you don’t want. Static content (png, html, ico, css…) are being served by a default servlet. In tomcat that is org.apache.catalina.servlets.DefaultServlet, and has been configured for you in conf/web.xml with the name “default”.

So, in order to exclude all static content from the catch-all of your front controller, you have to map static content to the default servlet, before the mapping of the front controller:

That works nicely, when deploying in Tomcat, Jetty and JBoss Application Server.
On Resin, deployment fails with the following message:WEB-INF/web.xml:89: `default’ is an unknown servlet-name. servlet-mapping requires that the named servlet be defined in a <servlet> configuration before the <servlet-mapping>.</servlet-mapping></servlet>
Resin’s static content servlet is com.caucho.servlets.FileServlet and until 3.0 was mapped using the name “file”. Then, on 3.1, and after some people complained that they couldn’t have a servlet called “file”, the name was changed to “resin-file”.
So, there are 2 solutions to make your application function properly. You can either change all references from “default” to “resin-file” in your web.xml, or change the FileServlet’s name from “resin-file” to “default” in Resin’s conf\app-default.xml.

This is an abstract class; it could have also been an interface. We want to add more behaviour now with Groovy code, so we are going to extend it and define the isAllowedToDriveCar method:Person.groovy

This test gets an instance of the PersonGroovy class, casts it to the known type of Person and we are ready to go. The isAllowedToDriveCar method is available because we defined it in the abstract superclass. The tests pass.

Note that the way I’ve presented parses the groovy file every time we call loadGroovyObject which is slow. You can cache the class.

Session Impersonation is an attack which works for webapps and dynamic websites. Someone steals your session cookie (possibly by using XSS – Cross Site Scripting), injects it into his browser visits the site and suddenly appears to be you. If you happened to be logged in as the single superadmin of the system, then he is a superadmin as well.

One of the ways to avoid this problem is by storing a hash (or token) the first time the http session is created. That hash will contain the user’s IP address and his user agent (the browser he uses). On each following request, the hash is being recalculated, and must match the hash previously stored in the http session. If it does not match, any of the 3 things might have happened:

Client has changed his IP.

Client has changed his user agent String.

Client is using another clients session (session impersonation attack).

Changing you IP is hard (unless your ISP is AOL or you use an anonymity service such as TOR). Changing browsers will initiate a new http session anyway, and changing your user-agent String is rare. It can be done in Firefox using the about:config page but that’s not a thing that users do everyday.

Note that session impersonation protection is hard (impossible?) to do when people use the same IP. That can be the case in universities, companies and netcafes.

Here is the doFilter method of an http filter which you can use to protect your application from session impersonation attacks. It will invalidate the session when this happens.

Code conventions are important to programmers for a number of reasons:

* 80% of the lifetime cost of a piece of software goes to maintenance.
* Hardly any software is maintained for its whole life by the original author.
* Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

Some people tell me that they cannot change their style, because that’s how they are used to coding. Fair enough. Do whatever you want when coding alone, in your home. But not in a professional environment. If you can’t be bothered, do us a favour and leave. Resign. Start selling popcorn. Whatever.

I have a serious problem working with people who commit Java code which looks like this:

public class persons {

public void PersonSave(persons p) {

package foo.bar.personUtils;

public static final String foo = "whatever";

whatever()
{
// do stuff
}

Seriously, please try to read the following piece of code found in a real life project. Does this look like Java?

You are building a webapp. You want database connectivity. You want pooling (because its an expensive resource). You start building your own database connection pool. STOP!!!

Who told you that you can do it well? Why did you hack your own connection pool implementation, which is seriously broken, spawns thousands of threads and turns the server into a miserable piece of shit that needs restart every 24h?

Wrong choice my friend. Next time do us all a favour and use one of the following: