Calling a remote Servlet using Android Activity.

Hi all, in the past i received some queries regarding “how to call EJB from Android?”, at that time i am not sure but i just replied by saying call a servlet from your Android and its the servlet that internally calls EJB, Yes its true there is no direct implementation to call EJB from Android but we can call a servlet from Android and from there its your logic to call any business components like EJB,etc. following is my tutorial which will take you how to call Servlet from Android
Note:This tutorial will create Servlets with specification 3.0 with no web.xml and uses annotations to map the requests from client.

1.Create a dynamic web project with servlet specification 3.0 and create a servlet in src folder of your project as shown below.
2.Deploy the servlet in local server(Apache-tomcat 7.x) and test the working by hitting the below url http://localhost:8080/AndroidServlet/androidServlet

package com.spark.android.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AndroidServlet
 * @author Mantha Pavan Kumar
 */
@WebServlet("/androidServlet")
public class AndroidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AndroidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Sample Page !");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Now its time to create android project(using Eclipse), Assuming all the prerequisites of android are already installed in your environment lets start the project.

3.create Android Application project
4.In the main.xml file add the below content

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button" />

    <TextView
        android:id="@+id/outputTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#CC0033"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

5. in res/values/strings.xml add the below content

<resources>

    <string name="app_name">SimpleHttpGetServlet</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
	<string name="button">Invoke Servlet</string>
</resources>

6.Now in the MainActivity.java place the below content

package com.example.simplehttpgetservlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
    Button button;
    TextView outputText;
 
    public static final String URL = "http://10.40.230.98:8080/AndroidServlet/androidServlet";
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        findViewsById();
 
        button.setOnClickListener(this);
    }
 
    private void findViewsById() {
        button = (Button) findViewById(R.id.button);
        outputText = (TextView) findViewById(R.id.outputTxt);
    }
 
    public void onClick(View view) {
        GetXMLTask task = new GetXMLTask();
        task.execute(new String[] { URL });
    }
 
    private class GetXMLTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String output = null;
            for (String url : urls) {
                output = getOutputFromUrl(url);
            }
            return output;
        }
 
        private String getOutputFromUrl(String url) {
            String output = null;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                output = EntityUtils.toString(httpEntity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return output;
        }
 
        @Override
        protected void onPostExecute(String output) {
            outputText.setText(output);
        }
    }
}

7.Finally we give persmissions to our android app to access internet in the AndroidManifest.xml as below.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simplehttpgetservlet"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thats it launch your AVD by running the Android project and click the button, you will see the response from servlet.
Happy coding πŸ™‚

How to create your own custom annotations in java and how to use it..PART-II

Hi in my previous post i have explained how to approach and understand over custom annotations using java, taking the support of meta annotations already given by java. Now i explain you how to code your own annotations. In my example i would like to explain how to inject object based on annotation.

Now i write a custom annotation “@AutoInject”, this annotation should be annotated on methods which will inject the object of particular class type as shown below

private EmployeeDTO employeeDTO;

public EmployeeDTO getEmployeeDTO() {
return employeeDTO;
}

@AutoInject
public void setEmployeeDTO(EmployeeDTO employeeDTO) {
this.employeeDTO = employeeDTO;
}

Now this code to get executed first we need to design our annotation i.e. @AutoInject as shown below:

/**
*
*/
package com.spark.custom.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @author Mantha Pavan Kumar
* injects the object to a getter method
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoInject {

}

Now to process the annotation we have to write a class which will actually give the annotation behavior as below.

/**
*
*/
package com.spark.custom.annotations;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
* @author Mantha Pavan Kumar
*
*/
public class GenericAnnotations {
/**
* @param obj
* @return
*/
public static <T> T injectDependencies(final T obj) {
try {
Class clazz = obj.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
Method writeMethod = pd.getWriteMethod();

if (writeMethod == null) {
continue;
}

Object existingVal = pd.getReadMethod().invoke(obj);
if (existingVal == null) {
for (Annotation annotation : writeMethod.getAnnotations()) {
if (annotation instanceof AutoInject) {
Class propertyType = pd.getPropertyType();
writeMethod.invoke(obj, propertyType.newInstance());
}
}
}
}
} catch (Exception e) {
// do something intelligent :)
}
return obj;
}

}

in this way you can code your own functional behavior of annotations, Happy Coding πŸ™‚ please find the below file for the entire code.
CustomAnnotations

How to create your own custom annotations in java and how to use it..PART-I

Hi All
Recently i have a thought why cant i create a custom annotations and use it, and below is the solution for it.

Lets look at what are annotations:

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.Annotations have a number of uses, among them:

Information for the compiler β€” Annotations can be used by the compiler to detect errors or suppress warnings.
Compiler-time and deployment-time processing β€” Software tools can process annotation information to generate code, XML files, and so forth.
Runtime processing β€” Some annotations are available to be examined at runtime.

Annotations can be applied to a program’s declarations of classes, fields, methods, and other program elements.

Annotation Structure

There are two main components in annotations. First is annotation type and the next is the annotation itself which we use in the code to add meaning. Every annotation belongs to a annotation type.

Annotation Type:

public @interface {
method declaration;
}
eg: public @interface AutoInject{
public injectObject() default "";
}

Annotation type is very similar to an interface with little difference.

We attach β€˜@’ just before interface keyword.
Methods will not have parameters.
Methods will not have throws clause.
Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.
We can assign a default value to method.

There are specific annotations which can only be used in the context of annotations. The annotations are target, retention, documented and inherited.

Meta Annotations

Annotations itself is meta information then what is meta annotations? As you have rightly guessed, it is information about annotation. When we annotate a annotation type then it is called meta annotation. For example, we say that this annotation can be used only for methods.

@Target(ElementType.METHOD)
public @interface MethodInfo { }

Annotation Types:
Documented: When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool.

Inherited: This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.

Retention: This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values:

@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
String value();
}

a.Class: When the annotation value is given as β€˜class’ then this annotation will be compiled and included in the class file.
b.Runtime: The value name itself says, when the retention value is β€˜Runtime’ this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation. I have give an example below.
c.Source: This annotation will be removed at compile time and will not be available at compiled class.

Target:This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE.

in my next post i will explain how to code custom annotations and use them
Happy Coding πŸ™‚