Wednesday, November 28, 2012

Create new Java Class files at runtime

When we write programs usual method is to write all the code compile it and run. But when we try to complex things some times we may want to generate a new class and use it at runtime. As an example I wanted to create a class which parse a xml message and create a new Java object from that data. This is used in web server. So that result object varies according to the web service which is deployed. The solution was to inspect the service at deployment time and create a new parser class according to that in the service deployment time. It has to be noted that this parser had to be generated as a .class file and dynamically added to the classpath. So the result was to use a bytecode manupulation library. There are few bytecode manuplulation libraries available as ASM and JavaAssist.
I used JavaAssist for this. The reason for using JavaAssist is it is simple to create a new class from the scratch using JavaAssit. When we create new class files using JavaAssit we have to create all the methods in the new class as Strings and the pass them to Java Assist. As a example if we have to add amethod called sayHellow() to new class we can create it as a String like this.
String s="public void sayHello(){ System.out.println("Hello"); }

/**
     * @param c   Any class which can be used to get the class loader                          (c.getClassLoarder()) can be passed using object.getClass() methood
     * @param name
     *            Name of the to be generated class
     * @param methods
     *            Methods to be created as Strings
     * @param interfaces
     *            interfaces to be implemented as Strings
     * @param directory
     *            the directory generated class files has to be written
     */
    public static void createClass(Class<?> c, String name, List<String> methods,
            List<String> interfaces, String directory) {
        String temp = null;
        try {
            ClassPool pool = ClassPool.getDefault();
            pool.insertClassPath(new ClassClassPath(c));
            CtClass cc = pool.makeClass(name);
            if (interfaces != null) {
                for (String s : interfaces) {
                    CtClass anInterface = pool.get(s);
                    cc.addInterface(anInterface);
                }
            }
            for (String s : methods) {
                temp = s;
                CtMethod m = CtNewMethod.make(s, cc);
                cc.addMethod(m);
            }
            cc.writeFile(directory);
        } catch (Exception e) {
            // TODO throw
            System.out.println(temp);
            e.printStackTrace();
        }
    }

To add this class to the classpath following method can be used.

//Here directory is the path which class files were written

 public static Class loadClass(String className,String directory, ClassLoader loader) throws Exception {
        File f = new File(directory);
        java.net.URL[] urls = new java.net.URL[] { f.toURI().toURL() };
        ClassLoader cl = new URLClassLoader(urls, loader);
        Class cls = cl.loadClass(className);
        return cls;
    }

Note - JavaAssist does not support generics. If we use genarics java assist throws an exception. We have to use fully qualified names for types. As an example we have to use java.util.List for List type.

Monday, October 8, 2012

How to get the base class of a Array using java reflection.

If we use Java reflection to get the class of a object like String[][] strings; Java reflection will return [[Ljava.lang.String. But sometimes you may want to get the bases class e.g in this case java.lang.String. Following method can be used to do that. If you want to get the bass class of array object a you use this as Class c=getTypeOfArray(a.getClass());

public static Class getTypeOfArray(Class c){
        Class cls=null;
        while(true){
            if(c.isArray()){
                c=c.getComponentType();
            }else{
                cls=c;
                break;
            }
        }
        return cls;
    }

Monday, September 3, 2012

GSoC 2012 with Apache Photark, A great experience.



Google summer of code is one of the worlds leading opensource development programs. It is held anually by Google inc. Many enthusiastic students participate each year for this.
In every year many number of students try to take part of this program. But nearly 1000 students only get selected for this event.  I was lucky to take part in 2012 program for the first time.
I took part on GSoC 2012 under Apache Software Foundation for their incubator project Photark.

The interesting thing was my initial plan was to participate on another organization which develops a CMS. I also worked with them nearly one month. But then I realized what they are expecting and what I am interested is not matching. So I looked for another organization and found this interesting project.
But then there was little time for application closing period.  So I quickly checcout the code base play with it for little time, drafted a proposal and submitted it.
Then Mr. Suhothayan Sriskandarajah who was happened to my mentor contacted me and explained further about what they are expecting and pointed out week points in my proposal. Then I updated my proposal according to the feedbacks. Then I started familiarizing with other technologies were new to me but need for this project.
Time went results came. Boom, I was taking part in GSoC 2012. Then the community bonding period started. But there was a slight problem I had exams in first two weeks of the community bonding period. But the community was very friendly. They understood my situation and they give me freedom until exams are over.
Then I started cording. Since it was a somewhat green field project (project details will be explained in another blog post) I had to take important design descisions how the UI must be organized, what are the libraries to be used, etc. But I managed to done it in to a significant level when the mid evaluation came.
In the mid evaluation my mentor evaluated my problem and we discussed what have to be done in the next half. Also my mentor suggested some UI improvements which were essential to make the app usable.
Mean time the community decided to give me the commitership for the project. They asked whether I like to be a committer and I agreed instantly. After the normal procedures (signing the ILCA etc.) I officially became a committer at Apache Photark. This helped me to contribute to the project more efficiently. Not I could do the changes immediately without submitting patches waiting until they applied. Also I could quickly do bug fixes.
After the mid term evaluation as the first task I did the UI improvements and gave id a modern and user friendly look and feel. Then I implemented rest of the  functionality gradually. When It comes to the final evaluations I have completed most of the planned functionality as they were planned. The app has came to a release level with my contributions and other GSoC participant's contributions. 
Then I did a code review with my mentor and he suggested some changes to code structure and naming    conventions to make it more understandable and clean. It is very important for a open source project since many people are going to contribute it in the future. After the soft pencil down date we did an another code review and officially ended out mentoring sessions for GSoC 2012.
After the evaluation period I was officially notified that I have completed GSoC 2012 successfully. Finally I like to say GSoC 2012 was one of the best experiences in my life. It gave me the opportunity to involve with open source projects, communities and contribute to them. Those contributions will not be limited to the GSoC period and I am going to do those contributions further.  
Finally I like to thank the people who helped me to make this project a success. First of all I like to thank my mentor who gave me this amazing opportunity and helped me throughout this project. Also I like to thank the project lead Luciano Resende, project member Avdesh Yadav and other GSoC participant Bhargav for their help throughout this project. I will discuss about my project in the next blog post in detail. 

Sunday, August 12, 2012

How to get current time and date using JavaScript.

Getting system date and time using JavaScript is easy. But some steps has to follow to convert it to a readable format. These functions will help you to get rid of the hassle .

//returns date in format 01/01/2012

function getCurrentDate() {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
return (month + "/" + day + "/" + year);
}

//returns time in format 05:45 AM
function getCurrentTime() {
var time = ""; var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); if (minutes < 10) { minutes = "0" + minutes; } var h; if (hours > 12) { h = hours - 12; } if (h < 10) { h = '0' + h; } time += (h + ":" + minutes + " "); if (hours > 11) { time += ("PM"); } else { time += ("AM"); } return time;
}

Thursday, June 28, 2012

How to build a maven project without tests

When we build a large project using maven it takes a lot of time because of tests  runs. So we can build quickly by disabling the tests. We can do that using the following command.
mvn -Dmaven.test.skip=true install

Wednesday, May 30, 2012

Using Geolocation API in phone gap

I am currently developing a Phonegap application for Google summer of Code 2012. I encountered some problems when using it and this is how I corrected them.

Location not available- In android emulator does not automatically get the location. So we have to send a moc location to the emulator using DDMS perspective in eclipse.

Phonegap documentation says to use the below method to get location.

navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);

But this gave me an error with error code 2 unable to start geolocation service. I corrected it using the below method.

navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError,{ enableHighAccuracy: true });

Note - This is only for testing in the emulator.

Friday, April 13, 2012

How to make a phone call in a Android application

This may a looks like a simple task. Actually it is a simple task. You can do it using few lines of code. But there are only few places which shows how to do it. So I decided to mention it here.


public void onCallButtonClicked(View view) {
String url = "tel:" + tpNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
intent.setData(Uri.parse(url));
startActivity(intent);
}

Sunday, March 4, 2012

Android: Using Google maps app to show places in your application

When we are developing android application with maps functionality normally developers tries to use Google maps API for this. But if your requirement is simple it may be more easy and effective to use existing maps application by a intent. In this application I'm going to show how to show the nearest hospital in your application.

Note- To make this work your app and emulator must be created using Google APIs not android APIs. (Both are the same but if you are not using Google maps API map application functionality is not available to you).

Here is the code,

LocationManager  locMgr  = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = recentLoc.getLatitude();
double lon = recentLoc.getLongitude();
String geoURI = String.format("geo:%f,%f?q=hospital", lat, lon);
Uri geo = Uri.parse(geoURI);
Intent geoMap = new Intent(Intent.ACTION_VIEW, geo);
startActivity(geoMap);


In the geoURI string you can change the hospital in to any other place. If you just wan't to center the map to your location do not include the question mark and latter part in geoURI .

This is how my application shows the nearest hospital to my location.

If you test this in Android emulator you have to send your location to the emulator using DDMS in eclipse because. Otherwise it will throw a null pointer exception. You can find articles on how to do this in internet.