Tuesday, February 5, 2008

One template file for all pages using Servlets and JSP

One of my recent tasks was making a new skin for one of our websites. the site had a common header, left side area and right side area that are to be shared among all pages. we used to include file for "header", "left side", "right side" in each of the pages.. it wasn't that pretty i know.

I wanted to think of something better where i can define the template in exactly one file and i do not have to include that file on every new page i add. something pretty much close the RubyOnRails "<% yield %>' directive to import the page content inside the template. i finally managed to do it.

I'll use two simple pages to illustrate the concept:

mahmoud.jsp


and index.jsp



what we want is to have each of the two pages displayed in a layout where is one header, banners and so. which will look like the following.





I was able to do this using a servlet that intercepts the request. and loads the template jsp file and pass the desired page to as a parameter to be included.

The template file is called template.jsp will look like:


The only line that matters in the template code is where we make the jsp:include page="<%request.getParameter("targetPage")%>"

The servlet intercepts http requests and loads this template using RequestDispatcher and passes the original desired page as a parameter:



The Servlet and servlet mapping in web.xml will look like



A note to be mentioned is that I had to configure my template to be initiated with requests to html pages (i can choose to work on any extension except jsp). When I configure my servlet mapping to be associated with jsp URLs, i get stuck in an infinite loop as since including the page inside the template results in a new jsp request.

The idea is simple. You are free to create your own template and to work on any file extensions in the url, but you have to specify a type other than jsp to avoid the infinite loop trap.

Bon appetite

Sunday, January 6, 2008

Restful Pagination in Rails

Have you ever tried to cache your paginated lists? Sadly, vanilla Rails wont help much as they ignore the url query parameters when caching and hence the page=x value is not honored and Rails caching (action or page caching) will simply stick to the first page rendered for all requests.

One might come with a solution that overrides the cache key generation to incorporate the query string, which will work, but will result in very long and ugly hash keys.

Luckily there is a better approach, if you simply defined routs for pages (for the paginated resources) and name them page parameter with the same name you give it in the paginator then Rails will pick up the route when creating paginated links.

In your routes.rb

map.resources :users
map.paged_users '/users/pages/:page'
map.formatted_paged_users '/users/pages/:page.:format'

once the above routes are in place, all you need is to make sure your paginators are using 'page' as the page parameter name and you will see the pagination links created like this:

/users/pages/1
/users/pages/2

Don't forget the formatted route to support pagination with various formats so you can use routes like:

/users/pages/1.xml

These urls are very cache friendly and adhere to REST much more than the default parameters based ones.

Happy caching (with pagination)

Saturday, November 3, 2007

Installing Windows, Ubuntu7.10, Mac OS 10.4.10 on MacBook (Triple Boot)


I am happy with my MacBook with its running Mac OS X 10.4.10. I can't stand working on windows any more, I feel more comfortable with Mac OS.

My master Thesis is running on linux environment(basically Fedora, but I successfully turned it to be Ubuntu)
My current project delivery should be done on windows. An easy solution costing 60$ would be to purchase Fusion.
Although Fusion looks very interesting, I didn't submit to this solution, for the following reasons:
  1. Running virtual machines consumes more memory, in this case I will loose some performance which is something I will certainly need during development.
  2. More memory usage, means more power consumptions, hence less battery life time. in normal cases I enjoy having ~4hrs battery life time with my lovely Mac. this is sthg i don't stand to loose.
  3. to overcome the first problem, I can extend my RAM. this will make the virtual software costs me almost (60+90)$....I really can't afford this for now. (I didn't get paid for salary 3 months ago)
So, I decided to to create a triple boot on my MacBook. It was a very risky step for me..But here we go, I have nothing to loose anyway (keeping in mind 150$ :S, 900 LE when converted to our local currency!!!!!! )

My MAC specs are:
Processor: 2.16GHz Intel Core 2 Duo
Memory: 1 GB 667 MHz DDR2 SDRAM
MAC OS X: 10.4.10

The target is to install Ubuntu 7.10 and WinXP SP2 on MacBook.
steps:
  1. Get BootCamp: I think it may force you to update to Mac 10.5. (luckily I installed it 1 month ago before leopard is released)
  2. Update your Mac OS.
  3. Install rEFIT.
  4. run BootCamp assistant and follow instructions to burn driver CD for windows. (don't proceed with installing steps)
  5. Backup your data. (you may not loose your data if things go smoothly)
  6. Check your disk partitions and identify the Mac Partion. I most cases it is /dev/disk0s2. but if you are not sure, you can verify this by running a shell command using the diskutil:
    $ diskutil list
    resize your HDD using Diskutil by running the following command. first you specify the volume to be resized, and its new size, then the type, and the name of the new volumes followed by their size.
    $ diskutil resizeVolume /dev/disk0s2 70G "Linux" "Linux" 20G "MS-DOS FAT32" "Windows" 20G
  7. insert your XP SP2 CD and hold down the "ALT" key.
  8. install XP on the valid partition, just give it a quick FAT32 format.
  9. you should now have a dual boot(windows with Mac).
  10. insert your Ubuntu 7.10 Live CD.
  11. run the installation normally. You should set up the partition manually. Don't mount the EFI system partition. you need only to mount / to the drive you allocated to your linux installation. I didn't make a SWAP file, I just don't need this for now, I relied on my 1GB RAM.
  12. Continue through the installation steps.
  13. When you reboot, you should have triple boot.

Why Software Developers Leave...

i read a nice article with the title "Software Team Turnover: Why Developers Leave (And What You Can Do About It)".

In this article, the writer, Aaron Reed, discussed the negative impact of the fact that some software developers leave their teams and what makes them do that. it is worth to read.
Aaron specified three main reasons that causes developers to leave:

Money
Like any person in any field, Software Developers too are in need for Money to fulfil their human needs. a developer being paid below the market average might be an unhappy unsatisfied developer. and in general, a Developer can increase his income by jumping to a new place more that he can by getting a raise in the same place.

being happy with what they do
Developer can work in some place or on some project even under paid, if they love what they are working on. in other words.. they also can leave for somewhere else (even paying less) if they were unhappy about they current projects/place/team, if they were bored, or if they were not learning more and not getting experience. actually this is a key reason for developers to move to a new place. the need for getting new experiences and new challenges.

Burnout
Software development is not an easy job. It is like having a hard exam for at least 8 hours per day/ 5 days per week. sometimes the developer gets overloaded by working in some project, and due to his experience in that project or field, and due to the fact that resources are need for that project. management do not move the developers to another project. which makes leaving the whole place is the only get away for the developer. i have seen this more than once before.

i totally Agree with Aaron Analysis of the issue. but i also need to add "Politics" as a candidate cause itself. a broken promise from the management side is fatal from the developer's prospective. disharmony among team members or people in the same work place may cause some of them to be unhappy to the extent that they may not want to stay in that place any more. of course that last reason is not specific to software developers, but it matters and do worth mentioning. actually all of the reason aren't specific to them.

Wednesday, October 31, 2007

Effective Java Programming

Effective Java Programming, by Addison Wesley, is one of nice books i have read in software development material. and i recommend it to any developer developing in Java, starter or senior.

programming by nature is very flexible. you have many choices. it is like creating a statue using clay. You choose at every point; Class names, methods and variable names. public methods, internal implementation algorithms, structure of the package classes,.. all of those and others are left for the programmer to choose.

Effective Java programming comes to introduce a lot of the best practices for Java programmers; to enhance the stability, readability, clarity, reusability and maintainability of their code. it also has guides to the proper use of a lot of the java standard classes.

A note inside the book really draw my attention; in item 8, chapter 3, Wesley was talking about overriding the hashCode method, he stated an example of a phone number class and an implementation of a suggested hashCode, then he said "Writing such hash functions is a topic of active research and an activity best left to mathematicians and theoretical computer scientists.". Wesley encourages his readers to use the state-of-art code. that's the goal of the book.

Actually i was thinking about the classes of the open source libraries we use as i proceeded reading the book. the kind of code that shall be used by thousands of programmers all around the world.

Thursday, September 27, 2007

To AJAX or Not to AJAX? That is the question!

When faced with a new web project these days you typically hear the clients listing AJAX as one of the must haves in their brand new web application. Pretty cool as you might be accustomed yourself to AJAX to the extent that you can hardly imagine returning back to the page reload per click days. But, if you are more sensible (or better yet, your clients are so) you would think twice before entirely abandoning the normal site browsing model for an AJAX based one.


Why? I hear you say. Many reasons, including the fact that we live in the early 21st century, where – get ready for this – not all Internet access devices are equipped with state of the art browsers that can consume your AJAX interfaces or whatever Javascript or CSS magic you throw at them. Many mobile phones (millions to say the least) can hardly parse plain old HTML, some can do CSS but not Javascript


Ok, you tell me. “I will have to do two versions, one that is full of AJAX effects and one old boring HTML only version.” STOP IT, I say, you can't be more wrong. Thank God there could be more elegant solutions to the problem than just writing another application around the same database. I present to you my humble take on the problem. Using the Ruby on Rails Framework (you can apply similar thoughts in other frameworks if you like, and many ideas can be copied easily as they only involve Javascript)

First off, the controllers. The controllers are responsible for receiving requests and sending responses. What we need to do is make them intelligent enough to understand different types of requests and respond accordingly. This is done using Rails magical method “respond_to”

class IssuesController < ApplicationController
def index
...
respond_to do |format|
format.html { # do something }
format.js { # do another thing }
format.json { # and another thing }
format.xml { # ok, enough }
end
end
...
end

In the above example we see that each format will have a different response. This is great for a start, that way we can implement slightly varying responses for the AJAX and the none AJAX calls. To make things easier on us we will implement a very simple case of AJAX. Each rhtml view is rendered in a DIV tag within an rhtml layout. In the none AJAX model, pages are rendered by rendering both the layout and the inner view. In the AJAX model, only the inner view is rendered and is sent back to the browser to replace whatever resides in the content DIV.

So, our controllers will work as follows:

class IssuesController < ApplicationController
def index
...
respond_to do |format|
format.html # will render index.rhtml
format.js { render :layout => false }
# the above line will render index.rhtml but without the layout
end
end
...
end

The above lines made our controller ready to respond to normal or AJAX requests (given that AJAX requests will have the .js format). In the former case it will return back the whole page but in the latter it will omit rendering the layout and only send the content.

Ok, but what we still need two views. I hear you, and fear not, you will have to change nothing. Actually it's only a trivia to adapt your views to this model. Let's see how this can be done.

Here's a normal view code sample, and pardon me, I won't use the link_to helper method for clarity purposes:

...
<div id=”content”>
...
<ul>
<li><a href=”url1”>Link1</a></li>
<li><a href=”url2”>Link2</a></li>
<li><a href=”url3”>Link3</a></li>
</ul>
...
<form target=”url4”>
...
<input type=”submit”>
</form>
...
</div>
...

The above fragment shows a list of links and a form. All should behave in the normal way and reload the page when clicked. Now let's imagine that the user is using a Javascript capable browser. What effect could this coming fragment have on his experience?


<!-- Warning, this fragment requires prototype.js -->
<script>
function ajaxifyLinks(){
// check if there is AJAX support
if(!Ajax.getTransport())return false;
// loop on all links
$$('a').each(function(link){
// attach an event observer to each link's 'onclick' event
Event.observe(link, 'click', function(event){
// call the original url (with .js added) with AJAX
new Ajax.Updater('content',link.href+”.js”);
// stop the browser from following the link
return false;
});
});
// loop on all forms
$$('form').each(function(form){
// attach an event observer to each form's 'onsubmit' event
Event.observe(form, 'submit', function(event){
// send the form contents via AJAX
new Ajax.Updater('content',form.action+”.js”,
{params:Form.serialize(form),
method:'post'});
// stop the browser from submitting the form
return false;
});
});
}
</script>

The above code will transform EVERY link and form in the page to AJAX, that is, in case that the browser supports both Javascript and AJAX. Otherwise links and forms will remain untouched and they will behave as usual.

Of course this is a minimalistic example. We knowingly avoided touching on any special case but, in another installment of this article we will get more intimate with the subject and may be we can handle more aggressive ... techniques!

Sunday, July 22, 2007

Zimbra, violating Open Source terms

Not all pretenders are Open source... This is true for zimbra at least which claims it is open source, but actually I see everythg they r doing is against open source. check this for detailed discussion abt zimbra as open source.
I am still in my battle field working on Zimbra.
We upgraded to the new zimbra version now....
In this new version I found sthg in the code that made my nerves; all variables are written in this format "_158", "_140".
I found this hilarious...