Archive for November, 2008

Using URL class to access files in local system as well as on web

November 27, 2008

I’ve being trying to do this for a while and I accidentally stumbled upon the solution. Until then I was using the “File” class whenever I wanted to access a local file and “URL” class whenever I want to access some thing on the web, and treat each case separately.

So If I wanted to treat the both cases in the same way the answer is to use the “URL” class. There are some drawbacks on using this class, but when the occasion presents it self best to use this class. The trick is that URL class expects the address specified has the protocol included in it when an object of it is instantiated.

For example for a web address you always have to specify the address for the URL class starting with the protocol such as “http://www.goo..” . Similarly If you want to access a file in the local file system just use the absolute path with the protocol “file://” as the suffix. (eg: “file:///home/saminda/Desktop/myfile.xml”)

eg : URL url=new URL("file:///home/saminda/Desktop/myfile.xml")

Or you can just use the other available constructors to specify the protocol seperately. Check the URL api here. There are many other protocols supported by URL class. They are,

  • file
  • ftp
  • gopher
  • http
  • mailto
  • appletresource
  • doc
  • netdoc
  • systemresource
  • verbatim

Exact implementations of supported protocols can vary. Above set is from sun java.

How to save the data in a url location to a file using java

November 27, 2008

This is pretty much simple and straight forward. But sometimes ppl tend to mess it up. Here’s how it is done with a minimum number of codes as I know.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

    public void saveUrlToFile(File saveFile,String location){
        URL url;
        try {
            url = new URL(location);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            BufferedWriter out = new BufferedWriter(new FileWriter(saveFile));
            char[] cbuf=new char[255];
            while ((in.read(cbuf)) != -1) {
                out.write(cbuf);
            }
            in.close();
            out.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

}

You can use this to download somefile from the net manually if you want to. But this cannot be used as a download accelerator since this uses only one thread to download stuff.

How to post or upload a file to a url or servelet using java

November 24, 2008

It took me a while to find out how to do this. Things you need to do is not hard, but how to find out things you needed to do was hard. No where in the internet I could easily find a way to do this. Finally I came across a few examples where it uses java deprecated classes/methods to do it. With some more research I found a valid way to do it without using any deprecated classes/methods.

Here it is in the form of a function. I’ll just paste the function I created.

import java.io.File;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public static String uploadFile(File resourceUrl,String url) throws HttpException, IOException{
	File f = resourceUrl;
	PostMethod filePost = new PostMethod(url);
	Part[] parts = {new FilePart(f.getName(), f)};
	filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
	HttpClient client = new HttpClient();
	int status = client.executeMethod(filePost);
	String resultUUid=null;
	resultUUid = filePost.getResponseBodyAsString();
	filePost.releaseConnection();
	return resultUUid;
}

You will need either the

org.wso2.carbon.commons.httpclient-3.1.jar 
org.wso2.carbon.logging-1.0.jar
org.wso2.carbon.commons.codec-1.3.jar

or 

commons-httpclient-3.1.jar 
commons-logging-1.1.jar
commons-codec-1.3.jar

files as libraries to run this.

In the function

the “status” represents the status of the post call.If the call is successfull the value of this would be 200. If not it will contain the relevant error status value which you can look upon on the net as http status messages.

The “resultUUid” will contain the server response. In this case I’ve taken it as a string. You can get it as a stream also in case the respose is a very long one (like a file that needs to be downloaded)

How to escape a string from regular expression using java

November 24, 2008

Sometimes when using java you may want to search in a string or split a string using some other string which may have characters which corresponds to special characters in regular expressions. Thus you may want to escape those characters. There are two ways.

1. Escape the special characters one by one.

in this case all you have to do is to put a “\” infront of each special character.

eg: "12+3"  => "12\+3"

2. Escape the whole string at one go.

This asks the regular expression parser to ignore any special characters in the string. This is also very simple as the first method. All you have to do is to put “\Q” in front of the string and “\E” at the end of the string.

eg: "[1] C++ is a (highlevel) programming language" => 
"\Q[1] C++ is a (highlevel) programming language\E"

This is however already available as a function in java

String escapedString=java.util.regex.Pattern.quote(myStringToEscape)

Naturally you can use this method to make parts of a string escape as a regular expression.

Taare Zameen Par

November 20, 2008

The most wonderful worth while watching hindi movie I’ve seen for a very very long time. This film touches your heart like from a mother to a child. Even the songs I enjoyed (mind you I normally fast foward when there is a song in the hindi film that I’m watching – so this is saying something). After watching it I said “wow”. Amir Khan really addressed humanity to its best. Amir you are great!!!

I recommend anyone to watch this movie. You dont need to understand hindi to understand. Your heart will tell you the meaning.

I specially loved the song about the mother…

And the song about stars (little stars)…

I nominate this movie to the OSCAR.

List java source folders in an eclipse project in the workspace

November 20, 2008

If you are doing plugin development this is quite easy to do. The ResourceUtils class does the job for you.

			
import org.eclipse.jst.ws.internal.common.ResourceUtils;
...
  IProject project = .....
  IPath srcPath = ResourceUtils.getJavaSourceLocation(project);

Some times there are more than one source folder in the project, If you want to list them all just use,

ResourceUtils.getAllJavaSourceLocations(project)

instead. I had to do it the hardway since I didn’t know how that there was such a function to list java source folders, so I wrote one myself. If anyone wants to do it manually….

public static String[] getJavaProjectSourceDirectories (String projectName) throws CoreException, JavaModelException{
    ArrayList paths = new
    ArrayList();
    IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    if (project.isOpen() && JavaProject.hasJavaNature(project)){

        IJavaProject javaProject = JavaCore.create(project);


        IClasspathEntry[] classpathEntries = null;

        classpathEntries = javaProject.getResolvedClasspath(true);
        for(inti = 0; i<classpathEntries.length;i++){
            IClasspathEntry entry = classpathEntries[i];

            if(entry.getContentKind() == IPackageFragmentRoot.K_SOURCE){
                IPath path = entry.getPath();

                String srcPath = path.segments()[path.segmentCount()-1];
                paths.add(srcPath);

            }

        }
    }
    return (String[])paths.toArray(new String[0]);

}

List the projects in the eclipse workspace

November 20, 2008

If you are creating an eclipse plugin you might want to list the projects contained in the currently running workspace. This is very easy to do. Just checkout the coding below.

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
...
...
public IProject[] getProjects(){
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
return projects;
}

Some people does this the wrong way. They findout the path of the workspace and read the folder names in that workspace to determine the projects in the workspace. There can be several things that can go wrong here.

  1. The particular project may not be loaded in to the workspace even though its in the workspace path.
  2. The name of the project need not to be the same as the name of the folder which it resides in.
  3. There can be imported projects which are not copied to the workspace.

If you use the above method not only you can get the project in the workspace correctly you can control them also, like open/close/delete/refresh etc.

Validating a xml against an xml schema using java

November 19, 2008

WSO2 maintaines the eclipse axis2 plugins for eclipse. I working on plugins for wso2, sometime back wanted to validate a user given services.xml file with the relevant schema. Eventhough it took me a while to findout how to do it, it is actually pretty simple to do. But its best to write it down somewhere so someone (which includes me) can next time find it out easily and understand it without problems. Following is the code snippet on how to do it by java.


import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
....
....
public boolean isXMLValid(String xmlPath, String schemaPath){
SchemaFactory factory = SchemaFactory.newInstance(
                     "http://www.w3.org/2001/XMLSchema");
try {
Schema schema = factory.newSchema(new File(schemaPath));
Validator validator = schema.newValidator();
Source source = new StreamSource(new File(xmlPath));
validator.validate(source);
return true;
} catch (Exception ex) {
return false;
}
}

So its pretty easy. If you know the paths of the two files (i.e. the xml file which you want to validate and the xsd file which you want to validate against), using the above function you can do it. If the function true returns that means the xml is in accordance with the schema. Take notice that this validation is case sensitive. That means the uppercase and lowercase are considered different eventhough they are the same words. The schema will take in to the case sensitivity in to consideration when validating.

Some times what you have may be the url of the xml or schema. In which case just use

new URL(<url_address>)

instead of

new File(file_path)

It is as simple as that. If the validation fails there will always be an exception in which case we return false. But if you want to know what the error was in the xml file simply analyse the exception that was thrown. It consists of details which caused the validator to decide it is not according to the schema.

How eclipse knows the internally launched server has started

November 16, 2008

I work in WSO2 eclipse plugins. WSAS 3.0 will be release within next month or so. It would be a major release interms of carbon. Search for WSAS on the google to find out more about WSAS. Anyway I’m right now in the process of doing plugins for this WSAS 3.0 release. One of the things I wanted to do was to bringup the WSAS server inside eclipse. This I’ll put another blog on how this is exactly done, but for now let me tell you how eclipse knows whent he server is up.

When you create a server runtime plugin you specify a server definition file which contains all the needed information about the server which eclipse should start/stop etc. This is an xml file. Among these there is a tag like following

<port>
<no>9763</no>
<name>Http</name>
<protocol>http</protocol>
</port>

this is where we say to the eclipse what port the server will be using. Eclipse will be trying to connect with this port once eclipse initialises the server. If it manages to connect with the port then it assumes thatt he server has started. Keep in mind the protocol tag contained in the above port tag. Eclipse attempts to connect to the server with that protocol. So it is neccessary that you have specified the correct protocol for correct port. For example WSAS normally uses port 9443 for https protocol.

Same goes for then stopping the server. If eclipse does not manage to connect with the port with the given protocol it will assume that the server has stopped.

thats it really.

Google video chat – Good or bad?

November 15, 2008

We were wondering whether they would come up with this feature. It is really great to have this feature in gmail specially since it would complete an almost perfect communication platform for gmail. However I recently decided to check this out.

Google launched their video chat (if my research is correct) on November 12, 2008. Which is 3 days ago (today is 15th). So it would be kind of unfair to judge this feature yet. But I couldn’t help noticing a few things here which might not make this video chatting feature popular as expected.

First and foremost thing is that you need to install some software for the web video chat to work. Which is a HUGE drawback. I mean users usually like if the the things are like “click and run” type. In here you need to download some installer and run it for the browsers to support the gmail video chat. And after the installation you need to restart the browsers too (which anyway you have to do if you made some changes relating to the browser). Nowadays users dont want to go to that length of trouble to just to let others see your face on the screen. Is this possible in a net cafe. Users may not have privileges you know.

Another one is that this feature requires both parties having the required software being installed. So it doesn’t matter if you go to any length of trouble to install the google video chat, you have to ask the other person in the other end which you want to video chat with to do the same. i have over 20-30 ppl generaly online in my chat list but non-of them had the feature installed yet (yeah i know, the feature just only got released, but u will see my point here), so i had to wait until who does have it installed to come online.

Another one of the drawbacks is that it still does not support linux. Main PC OS users around the world consists of windows and linux. We here in WSO2 being a great open source company uses mainly linux as our platform OS for our work. Its kind of annoying to see the message in the gtalk window saying that the OS does not support the video chat yet. Hopefully this problem will be fixed in near future.

So I finally managed to find someone who had the video chat feature installed. The video chat worked well for a couple of seconds and then “boom”, it stopped working.  I’m not sure why the reason is, may its because I’m not directly connected to the Internet or I’m behind a router firewall, but the point is that this feature is not yet stable. They should have stress tested this in more scenarios. Very disappointing guys!!!.

There were few other things which I thought could have being an improvement but I guess those can be improved with the time. One of the curious question I had is that why google did not use the web cam support in the flash controls. Because one thing is that flash is generally used in browsers so often that its like a part of requirement for a browser to have the flash support. So you can expect the browser to have flash installed. Controlling the web cam through flash is very easy as I know. Users doesn’t have to install anything new and they can just have the functionality without having to install or click anything at all. And flash is there in all major browsers and platforms. Besides google uses flash controls in their “talk gadget”. My only reason for not using the flash control might be for security reasons, but I’m sure that can be handled also if you put some effort to it.

All in all I think its good that Google launched at least some form of a working video chat feature. The web has being lacking this functionality for sometime now.