Archive for the Hint Category

Those who have completed the SCJP exam would recall some of the challenges faced while tackling weird looking code problems aimed at thoroughly testing your understanding of the Java language. While the SCWCD exam has minimal code related questions, which are easier to interpret, it does have its own series of challenges to overcome. Preparation is one of them and can be quite daunting for those new to JEE.

Before I begin, I would like to highlight some of the advantages I experienced after obtaining the certification. Firstly, it provides you with an in-depth knowledge of the JEE platform. Your mind may not retain much of what you studied over the passing months but the strong fundamentals do help you to question best practices when working on a project. Secondly, it also allows you to formulate solutions based on what JEE has to offer and thirdly, the fundamentals could also aid you to spot similarities with other web technologies on the market and eventually become proficient in them.

To ensure that your preparation is effective, it is very important to choose a good study guide. For this, I chose the Head First: Servlets and JSPs book. There are two reasons that made me use this book. Number one, it was an advice from my colleague Glen Worsley, who had already taken and passed the exam. Number two, Head First books market themselves as “Brain Friendly” guides. I cannot stress enough the importance of having a brain friendly guide for something rather complex like JEE. Most textbooks are crammed with words and too much details. The simple diagrams and humorous examples (it’s good to be idempotent!) do help the reader to retain important bits of information. There is plenty to remember and selecting an exam date is as tough as hitting a moving target as I came to learn later.

Progress was slow. The original plan was to complete a chapter a week. An ideal plan it was, but I only managed to read through about 2 or 3 chapters within a month. I dutifully did the questions in the book after each chapter and found them rather tough which is for my own good. I did reasonably well on the first few but I was having a really difficult time when I got to the chapters on expression language and JSTL. There are several ways to accomplish the same thing and one of the difficulties is in trying to remember the JEE APIs taught in the earlier chapters as well as the various JSTL/action tags, which exist for similar goals. A handy tip would be to memorise and understand the various possible tags within the deployment descriptor by heart. Doing so would mean that you have studied a few portions of several chapters in the book. Six months had passed by the time I finished the book and the chapter questions.

While searching the Internet for good SCWCD training tools, I eventually came across Enthuware’s software. Its a really affordable exam simulator with about 8 mock exams and various questions for each chapter. Questions are categorized by their level of difficulty. I attempted the questions for all the chapters and found them not as tough as the ones in the book. Nevertheless, those questions were good practice as it helped me to gauge my strengths and weaknesses. These were presented as graphs and they are a good indicator of which chapters to re-study.

The mock exam questions found at the back of the Head First book is the penultimate gauge to indicate your level of preparedness. It should be done only once and when you truly feel that you know JEE kung-fu. Doing the mock exam too many times can lead to inaccurate results and a false sense of security which may lead to a severe defeat on exam day. Another technique I developed while revising for the exam is to tackle questions from random chapters in the book. This indicates that you are well trained to handle any surprise attacks which you may not see coming. It also means that you have kept the study material from both the early and late chapters close to your heart.

I eventually picked a good date to sit for the exam and passed with a good score. As usual, I marked the unsure questions and did the ones I knew. I had about an hour of extra time by the time I finished my first run of the questions. I then used the remaining time to ponder on the marked questions. Months of preparation had finally paid off and I was able to enjoy a healthy balance of work and personal life once again. As with most exams, the preparation does require some amount of sacrifice to personal time, but the returns and benefits are rewarding.

One of my pet hates in software development is repetitive tasks: a complicated deployment process, tricky configuration of an application, repetitive editing motions that are just a little too messy for a find/replace. All of the above have, in the past, killed my concentration, dulled my senses and otherwise numbed my brain. I quickly realized that learning the ins and outs of a few powerful tools can take away a lot of the drudgery that sometimes crops up in my day-to-day work. Further, combining these tools makes it possible to automate just about everything that I need to do on a regular (or even not-so-regular) basis.

What’s important about everything that follows isn’t necessarily the process/tools itself, but what you get out of learning them. This is just what works for me, what has accumulated over a few years.

0. Pick a Good Editor (or IDE)

This first point is a half-hearted gesture because I don’t actually expect anyone to listen to me.

Use vim.

In all seriousness, if your editor doesn’t support basic macros and/or keyboard recording you’re going to encounter situations where you get slowed down by dull, repetitive editing. Even in an IDE that supports refactoring, macros will save you time and brain-dead copy/pastes. Automating repetitive tasks in editing source code is one of the simplest ways you can help yourself.

1. Learn Your Shell (or Learn Your IDE)

I think the Pragmatic Programmer said it well before I even knew what a “shell” was: the command-line is powerful.

Becoming very familiar with a powerful shell is one of the best things you can do for yourself as a developer. Yes, the syntax can be funky and the semantics confusing but over time you come to love it. For me, it’s the Unix shell: in *nix, the shell becomes the glue between all the other tools you use to get work done — including custom scripts and programs that take care of the heavy lifting for you. Windows users might be interested in PowerShell, which is a similar offering from Microsoft — you have the power of the .NET framework at your fingertips.

I understand, too, that folks accustomed to IDEs tend to get a little irked by shell programming. I still strongly recommend giving it a go, but scripting or extending your IDE to automate certain tasks you perform on a regular basis is a great start. If you find you lose a lot of time uploading and modifying configuration files to various servers, you may want to write an Eclipse plugin to make that process as simple as the click of a button.

Whatever path you choose — learning the more exotic aspects of a shell or the plugin API of your favourite IDE — learn it well. The only way to learn it well is to use it all the time.

2. Learn a Dynamically Typed Programming Language

If your shell scripts start to look like a train wreck when you need to perform complex operations, you may want to consider falling back to a scripting language: Perl, Python and/or Ruby are all great choices — bonus points if you mix the three to meet your needs. Languages like these will give you a more structured environment in which to express what you’re trying to achieve (at the cost of it being slightly more difficult to invoke external processes than, say, Bash — a standard Unix shell).

I think it’s important to note that I mention “dynamically typed” languages here because they generally don’t have a separate compilation step: bytecode compilation occurs as part of the execution of a Perl/Python/Ruby program. Thus, a small change doesn’t require an ant/make call to pull your code together again. Remember: you’re trying to automate a process, not create more process. Build management is overhead.

By the same token, if your program needs low-level access to hardware or raw speed for processing large quantities of data — don’t be afraid to fall back to a language like C or Java if you’re sure of your reasons for doing so. Needless to say, situations such as this are rare but not impossible.

3. Appreciation of the Supporting Cast

ssh, scp, rsync, svn/cvs/git, diff, patch, wget, sed, grep, find … the list of handy *nix command-line tools goes on and on. These are smaller tools that — with a good shell — can easily be combined to automate more complicated process. The output of these programs can also be piped into a script of your own doing to perform more complicated operations; then, the output of that program can be piped into another and so on.

This is the big thing I miss when working in Windows: even with PowerShell in play to alleviate the pain that is DOS, it has terrible tool support out of the box. Having the .NET framework on hand is great, but even that’s no substitute for the *nix command-line tools mentioned above. Rant aside, there are ways around most of the shortcomings in Windows and it’s possible to emulate some of the more useful command-line *nix tools. It just means you may need to put in more effort than a *nix counterpart at times.

For folks interested in automating with their IDE, your “supporting cast” might mean third party Java/.NET libraries which your automation plugin(s)/scripts can use to perform more complicated operations.

4. Invest Time in Learning Your Tools

Really, it all comes down to learning the tools from steps 1-3 backwards. Windows, Linux or OSX — you should be an expert in how your tools work and ideally use them on a daily basis. Really getting to know your tools might mean stepping out of your comfort zone a little to learn the nuts and bolts of how your shell ticks, or taking some time out of your day to learn certain esoteric API calls, or the semantics of some new construct in your scripting language of choice.

The goal of such practice is to surround yourself with an easily extensible suite of tools where every action feels like it’s an obvious choice. These tools will help to take away some of the unavoidable “noise” on the fringes of any software development project, and let you get on with getting your job done.

5. Write Lots of Scripts to Automate Common Tasks

This is at the core of automation: combine the above tools to get things done. Copy files to a server using scp, have your script extract and install it via ssh, manipulate configuration files using sed, grep and perl before finally starting the application and storing the process ID in a file with a quick shell command. All without you typing much more than “deploy”.

Automated tasks should be easy to kick off, require little-to-no input from you and — ideally — be fast, so you don’t have to wait long to determine if anything went haywire.

Automate at the First Sign of Resistance

Once you become accustomed to your tools — and again, by no means am I implying that those described here are the best or the only — you’ll step back when you start feel some resistance performing a task throughout your day:

Hmm. I don’t want to have to go through that 12-step deployment process all over again.

It becomes second nature to whip up a script that not only does the complicated deployment but verifies that the application is up and running as expected, checking a process exists and scanning the logs for hints indicating that everything’s fine. Over time you should find your automated tasks are easier to write and “feel” much more reliable than any manual process.

And, hopefully, you’ll be happier for it. :)

duke-study1.pngHaving accomplished one of my main short term goals in life, I thought I would reflect on the recent events that earned me my first certification outside of Uni.

You might be thinking, whats the big deal about answering a couple of Java questions, nabbing the cert and moving on with life. Besides, we all sat for the tricky test tailored by Shine that got us this job. The only way to answer your question is to try the questions in the diagnostic exam by Whizlabs or head over to the Java Ranch website and try their mock exams.

A couple of us sitting for the exam tried out the questions on Whizlabs and had our butt kicked. Things we thought we knew about Java. The hardest part about achieving our goal was the preparation. Our initial plan was to pass the exam by December last year, however, other commitments at the client site threw our schedule off course. By the time we got back to studying which was around February, our knowledge of the first few chapters were stale. To make it worse, I had to regain my motivation to put in additional hours into the preparation which is seperate from Shine’s training time.

February was rather short and as March approached I was entering panic mode. By this time, I had covered about five chapters which left me with another five more to go. The next few weeks were spent flying through the remaining chapters and trying out the self-tests that came with at the end of each chapter. I tried out the Whizlabs exam to get an estimate of where I am at and I was rather disappointed with my score of 30%. The good thing is, I get to study the questions I got wrong and work on my weak points. I tried the questions on the CD that came attached with the SCJP book I was studying and I found the questions much tougher and trickier. The whole objective is to thoroughly test your knowledge.

I decided to stop doing the questions on the CD as the results I was getting were rather demoralizing. I spent Easter finishing up the last chapter and doing some practice exams with Whizlabs. One of the things that I look out for while doing an exam, is the clock. For example, if you had 72 questions to answer within 3 hours, you would have about 2.5 minutes to answer every one of them. I adopted an approach of answering the “easy” questions that I am confident with first and “Marking” those that I could not answer or I was unsure off. If you still have about an hour left after your first run, you can relax a little and review those questions that you have not answered. Try your best to give an answer and since its multiple-choice, analyze each answer and deduce which one feels right. You should still have abit of time left after answering your questions, so go back to the ones that you have marked. From personal experience, I found that I was able to tackle the questions that I was unsure about after I had answered the rest of them. Some tough questions really do not mix well with stress and you will be amazed at your ability to tackle them after the initial hurdle.

I was really nervous at the actual exam but the valuable experience gained with Whizlabs gave me that confidence to see it through. The questions are actually easier than the Whizlab’s ones but they are designed to keep you engrossed! So whatever you do, watch the clock, mark tough questions and review!

P.S. I have never passed a practice exam on Whizlabs before. Nearly did, but not counted as a pass. I scored 70% on the actual exam and its the first exam I ever passed. If you are coping well with the Whizlabs exams, you know you are doing well.

Ruby on Rails comes with a lot of nice helper methods for generating the JavaScript driving the AJAX calls to your controllers. Handling the responses from the HTTP server becomes a snap too, with Rails providing a few simple callbacks to handle the response from the server:

But what if the server doesn’t get a chance to respond at all? What if the user’s browser has been unexpectedly disconnected from the Internet? What if your server - god forbid - has crashed?

Most AJAX applications in the wild will simply sit there forever waiting for a response. Certainly, that’s what happened to us when we first tested such a scenario. This is unacceptable: if the browser is unable to communicate with the server, we need to let the user know somehow.

Internally, Rails uses a cross-platform Javascript library called Prototype to do the heavy lifting when making AJAX calls. When you call a helper method like link_to_remote, Rails generates code to instantiate a Prototype Ajax.Request object (or a Ajax.Updater object in some cases) to make the remote call when a certain event occurs. In the case of link_to_remote, this will be when a user clicks on the generated link.

Many of the helper methods accept a common set of options which provide callbacks for handling success or failure using the following callbacks:

  • :success will be executed if the server responds to the AJAX request with any sort of 200 HTTP OK code.
  • :failure will be executed if the server responds to the AJAX request with anything *but* a 200 code.
  • :complete will be executed after the AJAX request has finished, irrespective of the result.

These callbacks can be mapped to corresponding callbacks in Prototype on a one-to-one basis. For the above callbacks, the corresponding Prototype callbacks are called onSuccess, onFailure and onComplete, respectively. Unfortunately, only the “complete” callback will be triggered if some fatal error occurs when communicating the server - “failure” will only be triggered if we get a response back from the remote host indicating a server-side. We have no way of determining what will happen if the browser is unable to communicate with the server at all.

So how do we detect server outage? Well it just turns out that if your browser is unable to communicate with the server, an exception will be thrown. We can actually use this as a basis for detecting server outages and other classes of errors that might occur browser-side. For this purpose, Prototype provides onException which is triggered by your browser if any sort of exception is thrown while the AJAX call is in progress. If we can tap into this callback, we can ensure our AJAX methods will dutifully report any problems that might occur.

Unfortunately Rails doesn’t yet provide access to this callback out-of-the-box, so there is no “:exception” callback available to the Rails helpers. We don’t want to clutter our templates with ugly JavaScript: we’d prefer to keep with the existing Rails conventions if we can. So what can we do?

PrototypeHelper#build_callbacks is used by remote_function to generate the Javascript responsible for making an AJAX call in helper methods like link_to_remote, form_remote_tag and others. It turns out that this little method exposes virtually all the callbacks available to Prototype *but* onException.

This is the hook we’re looking for: here we override and adapt the original code in PrototypeHelper#build_callbacks to add the following method to our ApplicationHelper:

include ActionView::Helpers::PrototypeHelper # ... def build_callbacks(options) callbacks = {} options.each do |callback, code| name = 'on' + callback.to_s.capitalize if CALLBACKS.include?(callback) callbacks[name] = "function(request){#{code}}" elsif callback == :exception callbacks[name] = "function(request,exception){#{code}}" end end callbacks end

This makes the :exception callback available to Rails using the familiar notation seen for the other types of callback. :exception is somewhat different in that it provides the exception object thrown internally available to your callbacks as the “exception” variable. Outside of that, it’s just like any other callback.

With this new callback available to us, we can then override the AJAX helper methods to include our error handling code in ApplicationHelper. As an example, here’s how we’d do it for form_remote_tag:

alias old_form_remote_tag form_remote_tag def form_remote_tag(options={}, &block) # In the event of a network failure (or some other error), we want to display an error message options[:exception] = (options[:exception] || '') + 'alert("Anerror occured while communicating with the server. Please try again later.");' + # Bubble the javascript exception up to prevent the caller from continuing execution (failure # to do this may result in multiple error messages being displayed!). 'throw exception;' old_form_remote_tag(options, &block) end end

With this code in place, any attempts to submit a form via AJAX will include our special error detection code, so we can rest at ease knowing our users will be notified if something goes horribly wrong at the network or language leve.

When using this technique to check, you have to be quite careful in your JavaScript code. Where any language- or browser-level exception that was thrown during the AJAX request was once ignored, it will be caught by the :exception callback. This means syntax errors in the response Javascript, bad content types (e.g. a content type of “text/javascript” with a body of HTML) or other errors will trigger the :exception callback. Unfortunately there doesn’t seem to be an obvious way to get more information about the nature of the error. For our purposes, however, this seemed to be enough if we were careful with the AJAX responses.

A further improvement to this approach might use a timeout mechanism to provide a hard limit for AJAX requests: if the server doesn’t respond with data within X seconds, abort the request and display an error. This would remove the reliance on the browser reporting errors via an exception, resulting in somewhat more robust code - the feedback may not be as immediate as if one were using exceptions, however.

Don’t leave your users out in the dark: keep them informed if things go wrong with an AJAX request.