Archive for November, 2008
Accessing WebDAV From Commandline
Linux has a wonderful commandline tool for accessing WebDAV resources. It is cadaver. To access any resource:
$ cadaver http://portale:8080/alfresco/webdav/Web%20Projects
If the resource requires authentication, cadaver will prompt for it. Then you may use the standard UNIX and FTP commands for navigating and manipulating content. Some of the common commands are: cd, pwd, ls, put, get, mput, mget, less, cat and delete. Similar to FTP commands, it has corresponding local commands too: lcd, lpwd and lls.
Edit In-line
To edit a file in-line in cadaver, just issue the edit <file-name> command. The default editor will open the file. To change the editor (to, say, emacs), issue the command: set editor emacs from cadaver prompt.
MetaWeblog API in Java
Recently we were assigned with the task of writing code to remotely insert an entry to a blog. And we had to select the Blogging software. So we started with the search for a blogging software which exposed its API. To our amazement, we found XML-RPC ruling the blogging API world. And one software independent standard for it is the MetaWeblog API.
After selecting the API, we had to find a software supporting this API. This assignment was for a demo we were to show. So we wanted a minimal blogging software with no configuration. We found Pebble (we used version 2.3.1). This software is cool. Installation is breeze, just put the WAR file in an application server, and you are ready to use it!
Now came the implementation part. I assumed the existence of a Java library implementing this MetaWeblog API. But did not find any. So the next obvious step: use some XML-RPC library in Java to implement the call. I had some bad opinion about Apache’s XML-RPC library. I had used it long back ago, and I hated the way it was implemented. Since then I have been using Python to access XML-RPC services. But, this time, the job required use of Java.
So we ventured to the next step: finding an alternative OpenSource Java XML-RPC library. We found RoX. We were happy because RoX was born out of frustration of using Apache’s XML-RPC engine. We implemented it. And RoX did not work for Pebble (still not able to figure out if it was a mistake on our part, or RoX really did have a bug). So switched to Apache (version 3.1.1). The 3.x API seems to have been simplified. So finally we wrote:
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
...
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:8080/pebble/xmlrpc/"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
// Params needed: blogid, username, password, struct, publish
// First create the fourth parameter, struct:
Map<string, String> m = new HashMap<string, String>();
m.put("title", "Hello World " + Calendar.getInstance().toString());
m.put("link", "http://www.indiwiz.com/");
m.put("description", "This is the content of the post!");
Object[] params = new Object[]{"default", "username", "password", m, true};
String ret = (String) client.execute("metaWeblog.newPost", params);
System.out.println(ret);
And then we delivered our demo!
JSR-286: Adding Header Elements
Some HTML elements like <link>, <script> may need to be placed in the HTML’s <head> section. For such needs, JSR-286 defines a standard way:
import javax.portlet.GenericPortlet;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.MimeResponse;
import org.w3c.dom.Element;
...
public class MyPortlet extends GenericPortlet {
@Override
protected void doHeaders(RenderRequest request, RenderResponse response){
Element e = response.createElement("link");
e.setAttribute("rel", "stylesheet");
e.setAttribute("type", "text/css");
e.setAttribute("href", "abc.css");
response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, e);
}
}
response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, ...) might be called for adding any number of headers.
We also have to add this in the portlet.xml (either in portlet scope or application scope):
<container-runtime-option> <name>javax.portlet.renderHeaders</name> <value>true</value> </container-runtime-option>
This is because javax.portlet.renderHeaders is set to false by default.
Quick WebService Client in Groovy
Writing WebService client in Groovy is simple.
import groovy.net.soap.SoapClient
def proxy = new SoapClient("http://localhost:7777/path/to/endpoint?WSDL")
def result = proxy.sayHello("Subhash")
println result
sayHello() is the operation name.
More details here. See the Installation part, you need to put the Groovy SOAP Jar in ${user.home}/.groovy/lib.
Quick WebService in Java 6
To write a quick JAX-WS webservice in Java 6:
package test;
import javax.xml.ws.Endpoint;
@javax.jws.WebService
public class MyWebService{
@javax.jws.WebMethod
public String getQuote(String name){
return "1234.56";
}
public static void main(String[] arg){
Endpoint end = Endpoint.create(new MyWebService());
end.publish("http://localhost:1000/MyWebService");
}
}
To compile and run:
$ apt -d bin/ MyWebService.java $ java -cp bin test.MyWebService
Learning to Program
My personal favorite language, of course is Java. But Java is difficult to learn. Consider the Hello World program in Java:
public class MyClass{
public static void main(String[] arg){
System.out.println("Hello World");
}
}
Now consider the same program in other languages (Python, Perl, Ruby, Groovy):
print "Hello World"
When learning Java as the first programming language, the learner is forced to understand, difficult to understand concepts like package, command line parameter, visibility, arrays, etc. in the very first program itself. This is not beginner friendly.
Eric S. Raymond recommended Python for beginners. But now a days it could be any of the new scripting languages: Ruby, Groovy, Scala, or of course Python itself. Each of these dynamic scripting languages have very minimal infrastructure code. So when writing a program to do something, the code exactly means that. Very beginner friendly.
Java
After being exposed to so many languages, I still love Java. Of course, I spend lot of time still writing infrastructure code instead of core business logic even now, many of these are changing in Java. For example, to read a user input from command line, long back ago we had to write:
Before Java 5
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
br.close();
}
catch(IOException ex){
// ...
}
Java 5:
Scanner in = new Scanner(System.in); String s = in.nextLine(); in.close();
Now, in Java 6 this has been replaced with:
String s = System.console().readLine(); // No IOException thrown
Things are getting more developer friendly day by day.
Java Swing
One of my favorite parts in Java is Swing programming. All over the years since I first touched Java, Swing has constantly made me learn new things. And I have also been awe inspired so often at the wonderful extensible design of the Swing API itself.
Using Swing APIs itself is a covert educating process. When I started writing event processing code, I was covertly introduced to Observer design pattern. There is thousands of such instances where I learned good OOP design approaches without any formal education. Another area where in normal Java coding we do not spend much time is concurrency. When writing any non-trivial Swing applications, you will have to think about concurrency!
Swing has constantly challenged me to think and design smart applications. This is an area which must be covered for learning Java.
Enterprise Java
Enterprise Java is one thing I work day-in and day-out. But the majority of the time I spend when writing Enterprise Java code is: figuring out how. The Enterprise Java platform takes care of the critical areas like resource pooling, transaction management, concurrency etc., so at the end of the day, the programmer is relieved of writing this same code again-and-again. But this ease comes with the cost of configuring the system for it. Also, is Enterprise Java a good learning platform for programming? Well, for programming not exactly. But for many practices, it is. Practices include: packaging, build, testing among others.
Interrupting a Thread in Java
Long long ago, when I was studying in College, my professors taught me to abruptly interrupt a running Thread using Thread.stop() method. Later this method was deprecated. Then in some article I read to interrupt a running thread, you have to write your custom logic:
class MyThread extends Thread{
private boolean isCancelled = false;
public void run(){
while(isCancelled != true){
// do long running job
}
}
public void cancel(){
isCancelled = true;
}
}
This seems to be a valid code, but there is an issue. If we are doing some blocking operation, or an IO operation inside the loop, then the cancel notification does not reach until that is finished. Well, so how do we solve this issue?
Thread API
The java.lang.Thread class has the following API methods:
void interrupt(); boolean isInterrupted();
To signal a running Thread about our request for termination, we can call its interrupt() method. Unlike the old stop() method, this does not abruptly terminate the execution of the Thread. What is does:
| When Thread is in Blocking mode | When Thread is in normal execution |
|---|---|
| Thread’s interrupt status will be cleared, and InterruptedException thrown. | Thread’s interrupt status will be set. |
A Thread is in blocking mode during following states:
- Thread blocked in invocation of wait(...) methods; or
- join(...) methods; or
- sleep(...) methods.
Now my actual reason for exploring this concept was due to an issue in RESTClient. I had wanted to implement a Stop button just as in a normal browser. So my Thread was not blocked using any of the interruptable methods, but due to a socket IO. So how can I solve this?
class MyThread extends Thread{
public void run(){
while(isInterrupted() != true){
// do socket IO
}
}
}
But this has the same limitation as the first code I wrote. If the socket IO is in progress, this condition is not checked until the IO is done. So what finally is the solution? It is simple:
class MyThread extends Thread{
private Socket soc = ..;
public void run(){
// do socket IO
}
@Override
public void interrupt(){
if(soc != null){
soc.close(); // wrap in try/catch
}
super.interrupt();
}
}
When we close the Socket object, the IO will fail raising an IOException which we can gracefully handle.
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.
Welcome Back
Hi All,
Welcome to indiWiz.com! It has been some time since this site disappeared, mainly because I was not able to find time to update it. But now it is back! I have moved it to WordPress for easy maintenance and hopefully will find time to update it continuously.
One of my priority items is to migrate the older content to this site. But hold on! This will also take some time! So till then, enjoy the fresh new content
Subhash.