Archive for category tutorials

Downloading a file through a servlet on a cluster

Funkiness rating ★★★☆☆ 
Devviness rating ★★★☆☆ 

Let’s say you have a servlet that reads a file from the file system and streams it to the HTTP response that goes back to the client, like this:

BufferedInputStream bis = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(f));
		} catch (FileNotFoundException fnfe) {
			logger.error(fnfe.getMessage());
			return;
		}
 
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			while((bytesRead = bis.read(buf)) != -1) {			
				os.write(buf, 0, bytesRead);				
			}
			os.flush();
			bis.close();
			os.close();
		} catch (IOException ioe) {
			logger.error(ioe.getMessage());
			return;			
		}

Let’s say you deploy the servlet on your local machine and test it extensively with every major browser, and it works, so you deploy it on the production clustered server, test it again and…bam!

Explorer doesn’t work, it keeps hanging before starting the download, in the “Requesting file information” phase.

To add even more WTF, if you connect directly to one of the clustered servers instead of going through the load balancer everything works perfectly

If you’re in this situation, panic is an accepted reaction.

Luckily (at least, for you), someone has already been in the same situation, and that would be me, so i can easily spare you a couple of afternoons of digging and investigation: fire up your Firebug - God bless it forever and ever and ever - and, using the “Net” tab, check that the HTTP response headers are the same when going through the load balancer and when directly connecting to a clustered server.

In my case - surprise! - they weren’t.

My load balancer was misteriously adding “Cache-Control: no-cache” to every HTTP response.

“So, what does ‘Cache-Control’ have to do with downloading files?”

Of course, nothing, but it seems IE has a problem downloading files when the response has “Cache-Control: no-cache”.

So, here are the lessons learned that i will kindly pass on to all my loving readers without having them experience the rage i had in the last few days and that sum up the content of this post:

  • IE sucks (didn’t you know?)
  • IE can’t download files if the HTTP response has “Cache-Control: no-cache”
  • Firebug is a great gift of the gods to us mortals
  • Deploying on a clustered server requires extensive HTTP response testing, as the load balancer may mess up your responses



All’s well, that ends well.

Add This! Blogmarks BlogMemes BlueDot BlogLines co.mments Connotea del.icio.us de.lirio.us Digg Diigo Facebook Google Google Reader icio.de IndianPad Leonaut LinkaGoGo Linkarena Linkter Magnolia MyShare Yahoo! MyWeb Netscape Newsgator Newsvine reddit Rojo Segnalo Shadows Simpy SlashDot Spurl Startaid StumbleUpon TailRank Technorati ThisNext

, , ,

No Comments

From String to any primitive type in 4 lines of code

Funkiness rating ★★★★★  Devviness rating ★★★★☆ 

 

Problem: i have some data in a text file, which contains 2 java.lang.Strings: the first one contains my data value, and the second one is the data type, i.e. “java.lang.Long”, “java.lang.Double”, etc.

How do i construct an object of the appropriate type containing the value in my text file?

Crappy solution: a loooong chain of if-else-if scanning through every supported type for choosing the appropriate parse* (Integer.parseInt, Double.parseDouble, etc.) method.

Why is this so crappy? Simply, because adding a supported type requires extending the if-else-if chain which may easily become too long and unreadable.

Funky solution: use the mighty powers of Java reflection!

Class objClass = Class.forName(type);
Class[] prototype = {String.class};
Constructor ctor = objClass.getConstructor(prototype);
return ctor.newInstance(new Object[]{value});

So what do these 4 lines do?
We get an instance of the Class object representing the class identified by the “type” String (the second string in our data file) and then we get the constructor which takes a single String as parameter, aka the constructor whose prototype is the one identified by our “prototype” variable; finally, we execute the constructor passing the value string.

Why is this so funky?

First of all, because it does in 4 lines of code what was done in a whoooole lot of lines in the crappy solution, but the very funky aspect of this solution is that it works not only with primitive types such as Integer, Long or Double, but also with any type which can be constructed with a String!

Veeeeeeeery funky!

Add This! Blogmarks BlogMemes BlueDot BlogLines co.mments Connotea del.icio.us de.lirio.us Digg Diigo Facebook Google Google Reader icio.de IndianPad Leonaut LinkaGoGo Linkarena Linkter Magnolia MyShare Yahoo! MyWeb Netscape Newsgator Newsvine reddit Rojo Segnalo Shadows Simpy SlashDot Spurl Startaid StumbleUpon TailRank Technorati ThisNext

5 Comments

Filtering an Access report for exporting

Funkiness rating ★☆☆☆☆ 
Devviness rating ★★★☆☆ 

Ok, time for some un-funkiness, that goes by the name of MS Access: we love to have fun while coding, but as we still have to eat sometimes we may happen to come across such irritating technologies, and the funky way of dealing with them is sharing pieces of the arcane knowledge required.

So, let’s say you have a MS Access db and you want to export a distinct MS Word file for every record shown in a form, which may be, for example, a letter to send to every client displayed by your form.

MS Access, very kindly, provides the built-in macro command DoCmd.outputTo that allows to export anything in it, be it a form, a query, a table or a report in any format chosen among Xls, Rtf, Txt and Html: sounds exactly like what we need, doesn’t it?

We should just put somewhere in our form a button that does DoCmd.outputTo when clicked and everything should be ok, right?

Of course not, we’re still working with MS Access, an environment where “expected” is far from reality.

The button we just added doesn’t export the data shown in our form, it exports the whole table, which is definitely wrong; how do we solve this?

The solution is really tricky, unelegant and unmaintainable, but it works and that is enough: basically, we have to add a dummy, empty query and set it as our report’s data source, then we have to dynamically inject the appropriate SQL for our query:

Dim qd As DAO.QueryDef
Set qd = CurrentDb.QueryDefs("QueryTestReport")
qd.SQL = "Select * from people where id_person = " & idPerson

Where, of course, “QueryTestReport” is the dummy query we just added.

We’re halfway through our journey, then: we still need to produce a separate file for every record in our form’s RecordSet, but that’s quite easy, since MS Access forms expose their own recordset allowing us to loop through it:

Dim rs As Recordset
Set rs = Me.RecordsetClone
while not rs.EOF
   idPerson = rs("id_person")

Voila :)

Add This! Blogmarks BlogMemes BlueDot BlogLines co.mments Connotea del.icio.us de.lirio.us Digg Diigo Facebook Google Google Reader icio.de IndianPad Leonaut LinkaGoGo Linkarena Linkter Magnolia MyShare Yahoo! MyWeb Netscape Newsgator Newsvine reddit Rojo Segnalo Shadows Simpy SlashDot Spurl Startaid StumbleUpon TailRank Technorati ThisNext

,

No Comments

Building a paged image gallery with jQuery

Funkiness rating ★★★★★  Devviness rating ★★☆☆☆ 

One of the funkiest features of jQuery is the enormous amount of plugins developed by the community: as every good developer knows, most problems have already been solved by someone else, so a good community of developers providing solutions to known problems is a key feature of any framework.

Today, we’ll see how to build a cool-looking paged image gallery using two jQuery plugins in combination: Galleria for image displaying and Pagination for (surprise!) pagination.

First of all, let’s build a single-page image gallery, we’ll add paging support later; Galleria is incredibly easy to use, you just have to put the images in an <ul> and then call  .galleria() on it:

<script type="text/javascript"></script>
<ul id="gallery">
	<li><img src="foo.jpg" alt="" /></li>
	<li><img src="bar.jpg" alt="" /></li>
</ul>

The result will look somehow like this (given some CSS tweaking):

galleria

Notice that the currently active image is displayed full-size and the rest of the images in the <ul> is displayed as a clickable thumbnail.

Of course Galleria provides some options to customize your image gallery rendering, and the most notable are:

  • The possibility to use your own CSS style for every element of the image gallery
  • The possibility to attach a callback to the event fired when a thumbnail is clicked and when a thumbnail is hovered
  • The choice weather to enable or not browser history, allowing the user to use the ‘back’ button in his/her browser

Let’s try adding some fancy animation effects on the thumbnails: for example, we want to have the hovered thumbnail highlighted and the selected image appear fading in, as in the demo:

function imageCallback(image, caption, thumb) {
	image.css('display','none').fadeIn();
	if(image.width() &gt; 500) {
		var ratio = image.width() / 500;
		image.css('width', '500px');
		image.css('height', image.height() / ratio);
	}	
 
	// fetch the thumbnail container
	var _li = thumb.parents('li');
		// fade out inactive thumbnail
	_li.siblings().children('img.selected').fadeTo(500,0.3);
		// fade in active thumbnail
	thumb.fadeTo('fast',1).addClass('selected');
}
 
function thumbCallback(thumb) {
	var _li = thumb.parents('li');
	var _fadeTo = _li.is('.active') ? '1' : '0.3';
	thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
	thumb.hover(
	function() { thumb.fadeTo('fast',1); },
	function() { _li.not('.active').children('img').fadeTo('fast',0.3); }
	)
}
 
$('ul.gallery').galleria({onImage: imageCallback, onThumb: thumbCallback});

And that’s it, fancy graphic effects on both images and thumbnails!

Now, on to pagination: let’s say you have a huge bunch of images in your gallery and having a single list with all the thumbnails is crappy…having just a dozen thumbnail tops for each page would be better…so how do we paginate our images?

With the pagination plugin :)

First of all, we need to store all our image paths and names in a javascript array:

    var images = [
        ['images/foo.jpg', 'foo'],
        ['images/bar.jpg', 'bar'],
        ['images/quux.jpg', 'quux']
    ];

The array will be handled by the pagination plugin which will internally deal with appropriate indices.

How do we do it? easy!

We add a div, with id=”Pagination”, that will contain page numbers, and then do

$("#Pagination").pagination(images.length, {callback: pageSelectCallback});

Is everything done, then?

No, but we just miss a small point: the pageSelectCallback.

function pageselectCallback(page_index, jq){
	var items_per_page = 2;
	var max_elem = Math.min((page_index+1) * items_per_page, images.length);
	var newcontent = '';
	for(var i=page_index*items_per_page;i
 
';
	}
	$('#imagelist').html(newcontent);
	$('#mainimage').html('');
	$('ul.gallery').galleria();
	return false;
}

Basically, we are calculating the array indices of the images in the current page, and then injecting the appropriate <li> items in the gallery <ul>, calling galleria() again to refresh the current page gallery.

You can see a very basic demo of this tutorial here…have fun!

Add This! Blogmarks BlogMemes BlueDot BlogLines co.mments Connotea del.icio.us de.lirio.us Digg Diigo Facebook Google Google Reader icio.de IndianPad Leonaut LinkaGoGo Linkarena Linkter Magnolia MyShare Yahoo! MyWeb Netscape Newsgator Newsvine reddit Rojo Segnalo Shadows Simpy SlashDot Spurl Startaid StumbleUpon TailRank Technorati ThisNext

12 Comments