Archive for the ‘Scripting’ Category
Accessing RESTful WebServices with Prototype.js
We can make Ajax requests using Prototype.js (version 1.6.0.3) thus:
var url = ...;
new Ajax.Request(
url,
{
method:'DELETE',
onComplete:function doMessage(response){
alert(response.status);
}
});
While working on this code, we found out that the method parameter accepted only GET or POST requests. When we give any other request type like DELETE or PUT, the Prototype.js library converted the request to POST.
Arun Jeganath found this post where the same issue is discussed. The problem was solved when we commented these lines from the Prototype.js code:
if (!['get', 'post'].include(this.method)) {
//simulate other verbs over post
params['_method'] = this.method;
this.method = 'post';
}
37 Signals Launches Sprockets
Sprockets (site) is described thus: Sprockets is a Ruby library that preprocesses and concatenates JavaScript source files. This is not a new idea, I have seen similar compiler in Liferay source for aggregating CSS files. Since this is sponsored by 37 Signals (creators or Ruby on Rails), Sprockets’s syntax can become a kind of standard. Already Prototype and Script.aculo.us JavaScript libraries (two OpenSource JavaScript libraries popular in RoR) comply to Sprockets’s syntax.
Google CDN for popular JavaScript libraries
Google is hosting versions of popular OpenSource JavaScript libraries (as a CDN–Content Delivery Network). The list of libraries include Prototype, jQuery, Scriptaculous, YUI and others. These can be directly linked to the Google URL. The advantages:
- Bandwidth saving: these files need not be hosted in local webservers, saving local bandwidth.
- Effective client side caching: if a person visits 100 sites using Prototype library version 1.6.0.3, and if all these sites link to the Google CDN, then the script will be downloaded to the user’s system only once.
Now the common fear among people: what if the URL changes? What happens when newer version of the libraries come up? Google’s promise (from the site):
Google works directly with the key stake holders for each library effort and accepts the latest stable versions as they are released. Once we host a release of a given library, we are committed to hosting that release indefinitely.
JEdit Macro for XML/HTML Special Character Conversion
One of the common requirement I face often when posting text to blog/forum/Wiki etc. is character conversion:
| & | & |
| < | < |
| > | > |
| " | " |
| ' | ' |
I developed a small JEdit Macro for doing this. This macro can be executed from JEdit menu Macros > Run Other Macro..., or can be installed by copying to: ${user.home}/.jedit/macros/ (later executed from the menu Macros). This macro operates on selected text.
Search for the perfect Ajax auto-complete library
Yesterday we (Krithika and myself) spent some time finding a perfect Ajax auto-complete solution for one of our internal projects. We wanted to have a tag search box with auto-complete functionality. We had created a front-end layer for our Java tagging API (developed by Arun) using RESTful interface. This exposed searched result in JSON. So our need was for a Ajax library which provided auto-complete feature which satisfied following parameters:
- The code we need to incorporate for enabling auto-complete should be minimal.
- Should not be flashy.
- Should consume JSON content.
This seemed to be a trivial task, but it took quite some time to find and finalize on AutoComplete 1.2 by Beau Scott. This script was simple to integrate, and did not require us to configure any sophisticated CSS. It allowed us to consume our RESTful service without any modification.
During our search, we were surprised to find how badly certain popular Ajax libraries implemented this oft-used functionality. The famous Scriptaculous library’s implementation has the implementation detailed here: http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter. If you go through this document, you will see that the script requires the server to return data in this format:
<ul>
<li>your mom</li>
<li>yodel</li>
</ul>
This is bad design. A server code returning data as HTML. This cannot be consumed effectively by other clients. The next one which we picked up was YUI Autocomplete. The amount of configuration effort needed from our side scared us. We didn’t plunge deeper!
Another one which we tried was DevBridge’s Auto Complete. This looked simple to implement, and the look and feel was simplistic. But it had an issue: the call to the server-side code was passed as a query string (query=). We were using RESTful URL and we cannot modify our backend-code to comply to the requirements of the UI layer. But I did a little hack and made this script compliant to our requirement. But finally, we decided against using this patched-script because it had additional dependencies like images and CSS styles to be specified.
As said earlier, the script which matched all our requirements was AutoComplete 1.2 by Beau Scott.
The only worry for me from this exercise was the divide between the front-end developers and backend developers. Such a common functionality was not being addressed by popular frameworks without sacrificing functionality and addressing usability–and, more importantly, complying to established enterprise patterns like consuming data (like JSON and XML instead of HTML snippet) and support for RESTful URLs.
Hope 2009 annihilates this divide
JEdit, powerful search and replace using BeanShell
JEdit is my favorite text editor. And today I was pleased to find some powerful scripting capability in its search and replace functionality. Basically I wanted to enclose a RegularExpression pattern with:
<a href="">PATTERN</a>
The Search and Replace dialog provided an option Return value of a BeanShell snippet. So whatever RegularExpression pattern grouping I provided, I was able to access them using the BeanShell variable _1 to _9. So my final replace statement became:
"<a href\"\">" + _1 + "</a>"
Cool solution to a simple problem.

JavaScript: Dynamically Creating and Manipulating DOM Elements
I was pleasantly surprised to see that JavaScript now supports XML-DOM methods for manipulating JavaScript DOM trees. A quick look at the features:
Init
Before we proceed with the examples, the setup part. All the examples that follow assume the existence of this in the HTML page:
<div id="placeholderId"/>
Creating new element
Let us assume the requirement of placing <br/> element inside the placeholder. The code:
var e = document.getElementById('placeholderId');
var eBr = document.createElement('br');
e.appendChild(eBr);
Adding attribute
Suppose we want to add the attribute id="brId", we would write:
eBr.setAttribute('id', 'brId');
Deleting attribute
eBr.removeAttribute('id');
Deleting element
var e = document.getElementById('brId');
var eParent = e.parentNode;
eParent.removeChild(e);
Creating elements with text element
Consider that we want to have the following paragraph element inside the placeholderId <div>:
<p align="right">Hello World!</p>
It can be achieved thus:
var e = document.getElementById('placeholderId');
var ePara = document.createElement('p');
ePara.setAttribute('align', 'right');
var eTxt = document.createTextNode('Hello World!');
ePara.appendChild(eTxt);
e.appendChild(ePara);
Happy hacking with this info
Python 3.0 Released
My language of preference after Java, has a new release: 3.0. This is an interesting release as it breaks backwards compatibility. A conversion tool for 2.0 code migration to 3.0 is also made available by the community.
Beautiful Closures
One of the irritating things when writing code in Java is when managing files or database resources. We have to write so much redundant code:
File f = new File("/etc/passwd");
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(f));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
}
catch(IOException ex){
...
}
finally{
if(br != null){
try{
br.close();
}
catch(IOException ex){
...
}
}
}
So much redundancy is ground for human errors. Issues like these are beautifully solved using programming concept called Closures. For example, in the newly released 2.6 version of Python, the same would be written as:
with open('/etc/passwd', 'r') as f:
for line in f:
print line
In the above code, even when an exception is raised during file read, the file is gracefully closed when the control exits with block. A similar example in Groovy:
File f = new File("/etc/passwd")
f.eachLine{
line ->
println line
}
Martin Fowler has written a short introduction to Closures.