Archive for the ‘Java’ Category

Accept or Ignore Self Signed Certificates While reading ssl web page using Java

January 18, 2010

Turns out this is quite easy to do but hard to find the code for it. So here it is.

TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
	public java.security.cert.X509Certificate[] getAcceptedIssuers() {
		return null;
	}

	public void checkClientTrusted(X509Certificate[] certs,
			String authType) {
	}

	public void checkServerTrusted(X509Certificate[] certs,
			String authType) {
	}
} };

// Install the all-trusting trust manager
SSLContext sc;
try {
	sc = SSLContext.getInstance("SSL");
	sc.init(null, trustAllCerts, new java.security.SecureRandom());
	HttpsURLConnection
			.setDefaultSSLSocketFactory(sc.getSocketFactory());

	// Create all-trusting host name verifier
	HostnameVerifier allHostsValid = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};
	HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

So basically what the above manager does is that it creates a socketFactory with a trust manager which allows all certificates and sets that as the default socket factory. The 2nd part is to validate a hostname which is not really important unless you are working on a server side IMO.

Advertisements

Saving/Retrieving the java object as/from xml string

November 19, 2009

Apparently this is extremely easy :). I wanted to save an object in xml format in order to later recover the object. The coading involves only a couple of lines of code. Following is an example class I wrote on how to do that. As you can see I’ve included the xml encoding & decoding methods (toString() and the getMyObject()) inside the same class which of course can be done outside the class also.

package a.b.c;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class MyClass {
	private String name;
	private int age;
	private Map friends=new HashMap();

	public void setAge(int age) {this.age = age;}
	public int getAge() {return age;}
	public void setName(String name) {this.name = name;}
	public String getName() {return name;}
	public void setFriends(Map friends) {this.friends = friends;}
	public Map getFriends() {return friends;}

        // from here starts the xml encoding/decoding
	public String toString(){
	   StringOutputStream fos = new StringOutputStream();
           XMLEncoder xenc = new XMLEncoder(fos);
	   xenc.writeObject(this);
	   xenc.close();
           return fos.getString();
	}
	public static MyClass getMyClass(String xmlObjStr){
	   XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(xmlObjStr.getBytes()));
	   MyClass p = (MyClass)decoder.readObject();
	   decoder.close();
	   return p;
	}
	private class StringOutputStream extends OutputStream {
	  StringBuilder mBuf = new StringBuilder();
	  public void write(int bytes) throws IOException {mBuf.append((char) bytes);}
	  public String getString() {return mBuf.toString();}
	}
        // xml encoding/decoding ends
}

then by simply just calling toString() method of an object of above class you can get the xml representation of the object (save it to a file/database if u want) and recreate an object of the type by passing this xml to getMyClass() method.

How to programatically add classpaths to an eclipse project

December 3, 2008

This is very easy, All you need is the name of the project or IProject it self and the jar path list.

   public static void setClassPathToNewLibs(String projectName,String[] jarPathList){
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
        try {
            IJavaProject javaProject = (IJavaProject)project.getNature(JavaCore.NATURE_ID);
            IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
            List list = new LinkedList(java.util.Arrays.asList(rawClasspath));
            for(String path:jarPathList){
                String jarPath = path.toString();
                boolean isAlreadyAdded=false;
                for(IClasspathEntry cpe:rawClasspath){
                    isAlreadyAdded=cpe.getPath().toOSString().equals(jarPath);
                    if (isAlreadyAdded) break;
                }
                if (!isAlreadyAdded){
                    IClasspathEntry jarEntry = JavaCore.newLibraryEntry(new Path(jarPath),null,null);
                    list.add(jarEntry);
                }
            }
            IClasspathEntry[] newClasspath = (IClasspathEntry[])list.toArray(new IClasspathEntry[0]);
            javaProject.setRawClasspath(newClasspath,null);
        } catch (CoreException e) {
            e.printStackTrace();
        }

}

Should work for any kind of eclipse project I guess.

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.

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.

Specifying the Main class to run in a jar file from command line

November 4, 2008

Recently i wanted to run a jar file where its Main entry is not specified in the MANIFEST file. I knew this can be done since i’ve done it before, but couldn’t remember how to do it. So as usual i googled it but could not find it.

The thing is that this is a scenario that can arise when there are multiple entry points (mutiple classes having static main methods) in the jar file.

Funny enough the solution was pretty simple. Eventhough one might think that you need to specify the extry point class and the jar file which it is contained, the truth is we look at that fact in a wrong angle. What we have to do is to specify the class name and then the class path which the jvm should look for relevant classes (thus our jar should be included in this path).

eg:

say we have a class foo.class (which has a static main method) and it is in the jar file bar.jar. Then to execute the jar using the static main method present in foo class

$ java -cp bar.jar foo

here the class name should be a fully qualified class name. You can add more paths to the -cp parameter seprating them from a “:”