35
Develop a Spring client for Android to a JAX-RS web service Learn to create a Spring Android client Skill Level: Intermediate Deepak Vohra ([email protected]) Consultant Independent 12 Aug 2011 The Representational State Transfer (REST) software architecture is based on transferring representation of resources. A RESTful web service is a web service based on REST and the HTTP protocol and is made available as a URI path. The web service consists of methods producing messages of various media types such as XML, HTML, JSON, and text. The web service methods respond to HTTP methods GET, PUT, POST, and DELETE. The Java™ API for RESTful web services (JAX-RS) is defined in JSR 311, and Jersey is a reference implementation for JAX-RS. Spring, a platform to run Java enterprise applications, provides several benefits, including increased productivity and runtime performance. Spring Android is an extension of the Spring framework that simplifies the development of Android applications. The main features of Spring Android are a REST client for Android and Auth support for accessing secure APIs. In this article, access a RESTful web service with the Spring Android REST client. Overview The article has the following sections: Develop a Spring client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 1 of 35

Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Develop a Spring client for Android to a JAX-RSweb serviceLearn to create a Spring Android client

Skill Level: Intermediate

Deepak Vohra ([email protected])ConsultantIndependent

12 Aug 2011

The Representational State Transfer (REST) software architecture is based ontransferring representation of resources. A RESTful web service is a web servicebased on REST and the HTTP protocol and is made available as a URI path. Theweb service consists of methods producing messages of various media types suchas XML, HTML, JSON, and text. The web service methods respond to HTTPmethods GET, PUT, POST, and DELETE. The Java™ API for RESTful web services(JAX-RS) is defined in JSR 311, and Jersey is a reference implementation forJAX-RS.

Spring, a platform to run Java enterprise applications, provides several benefits,including increased productivity and runtime performance. Spring Android is anextension of the Spring framework that simplifies the development of Androidapplications. The main features of Spring Android are a REST client for Android andAuth support for accessing secure APIs.

In this article, access a RESTful web service with the Spring Android REST client.

Overview

The article has the following sections:

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 1 of 35

Page 2: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

• Setting the environment

• Creating a JAX-RS web service resource

• Installing Maven plugins

• Creating a Spring Android client

• Configuring Maven plugins and dependencies

• Configuring Android Maven goals

• Running the Spring client Android application

Setting the environment

Frequently used acronyms

• API: Application programming interface

• HTML: HyperText Markup Language

• HTTP: HyperText Transfer Protocol

• IDE: Integrated Development Environment

• JSON: JavaScript Object Notation

• MIME: Multipurpose Internet Mail Extensions

• POJO: Plain Old Java Object

• SDK: Software Development Kit

• UI: User Interface

• URI: Uniform Resource Identifier

• URL: Uniform Resource Locator

• XML: Extensible Markup Language

To set the environment, complete the following tasks. (For links, see Resources.)

• Install Eclipse IDE.

• Install the Android Development Tools (ADT) plugin for Eclipse. The ADTplugin for Eclipse provides a set of extensions to develop Androidapplications in Eclipse.

• Install the SDK Platform Android 2.2. The Android SDK provides tools fordeveloping Android applications.

• Create an Android Virtual Device (AVD), which is an emulator for Android,

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 2 of 35

Page 3: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

in Eclipse.

• You also need to install a web server such as Tomcat or an applicationserver, such as WebSphere or WebLogic server.

• Download the Jersey archive jersey-archive-1.4.zip containing the Jerseyjars and core dependencies. Also, download the Jersey bundle JARjersey-bundle-1.4.jar. As Jersey is built using JDK 6.0, you also need toinstall JDK 6.0. Add the JAR files shown in Listing 1 to the runtimeCLASSPATH of the application/web server.Listing 1. JAR files to add to server Classpath

C:\Jersey\jersey-bundle-1.4.jar;C:\Jersey\jersey-archive-1.4\lib\asm-3.1.jar;C:\Jersey\jersey-archive-1.4\lib\jsr311-api-1.1.1.jar

• Download the Spring Android project ZIP file. Extract the ZIP file to adirectory.

Creating a JAX-RS web service resource

You will create a Spring client for a JAX-RS web service resource in this section.Your JAX-RS web service will produce three different types of messages, each witha different MIME type: text/plain, text/xml, and text/html.

First, create an Eclipse project.

1. Create a web project and add the JAX-RS facet to the project. Select File> New, and in the New window, select Web > Dynamic Web Project.

2. Click Next. Specify a project name, and configure a new target runtimefor the WebSphere, Tomcat, or WebLogic server.

3. Select the default project settings, and click Finish.

Eclipse creates a dynamic web project and adds it to the Project Explorer.

1. In the Project Properties window, configure the JAX-RS (REST WebServices) 1.1 project facet.

2. In the JAX-RS Capabilities window, specify the Servlet name as JAX-RSServlet, configure a JAX-RS Implementation Library, and add JerseyJARs to the user library.

3. Add the Jersey JARs jersey-bundle-1.4.jar,

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 3 of 35

Page 4: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

C:\Jersey\jersey-archive-1.4\lib\asm-3.1.jar, andC:\Jersey\jersey-archive-1.4\lib\jsr311-api-1.1.1.jar.

4. In the JAX-RS Capabilities window, specify the JAX-RS servlet classname ascom.sun.jersey.spi.container.servlet.ServletContainer.The JAX-RS User libraries are added to the project, and the JAX-RSServlet and the Servlet mapping are configured in web.xml.

5. Add init-param elements for thecom.sun.jersey.config.property.resourceConfigClass andthe com.sun.jersey.config.property.packages init parameters.

Listing 2 shows the web.xml file.

Listing 2. web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><display-name>EclipseJAX-RS</display-name><servlet>

<description>JAX-RS Tools Generated - Do not modify</description><servlet-name>JAX-RS Servlet</servlet-name><servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class><init-param>

<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name><param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>

</init-param><init-param>

<param-name>com.sun.jersey.config.property.packages</param-name><param-value>jaxrs</param-value>

</init-param><load-on-startup>1</load-on-startup>

</servlet><servlet-mapping>

<servlet-name>JAX-RS Servlet</servlet-name><url-pattern>/jaxrs/*</url-pattern>

</servlet-mapping></web-app>

Next, create a RESTful web service resource using a root resource class. The rootresource class is a POJO annotated with the @PATH annotation, and it consists of atleast three methods annotated with the @GET annotation, which indicates that themethods process HTTP GET requests. Specify the URI path on which the Javaclass is to be hosted as /helloworld. See Listing 3.

Listing 3. Resource URI path

@Path("/helloworld")

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 4 of 35

Page 5: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

public class HelloWorldResource {...}

Add resource methods to produce three different MIME types. Add the followingmethods to the resource class, and annotate each of the methods with the @GETannotation.

• getClichedMessage(). Outputs a "Hello JAX-RS" message usingMIME types text/plain.

• getXMLMessage(). Outputs a "Hello JAX-RS" message using MIMEtype text/xml.

• getHTMLMessage(). Outputs a "Hello JAX-RS" message using MIMEtype text/html.

Specify the return type for each of the methods as String, annotate each of themethods with the @PRODUCES, and specify a different MIME type for each of themethods. The getXMLMessage method is annotated with the@Produces("text/xml") annotation that produces an XML message. Uncommentonly one of the methods annotated with the @GET method for each deployment.Listing 4 shows the root resource class.

Listing 4. JAX-RS web service resource class

package jaxrs;import javax.ws.rs.GET;import javax.ws.rs.Produces;import javax.ws.rs.Path;import javax.ws.rs.core.MediaType;

// The Java class will be hosted at the URI path "/helloworld"@Path("/helloworld")public class HelloWorldResource {

// The Java method will process HTTP GET requests// @GET// The Java method will produce content identified by the MIME Media// type "text/plain"//@Produces("text/plain")//public String getClichedMessage() {// Return some cliched textual content//return "Hello Android";//}

// @GET// @Produces("text/xml")// public String getXMLMessage() {// return "<?xml version=\"1.0\"?>" + "<hello> //Hello Android" + "</hello>";// }

// @GET//@Produces("text/html")//public String getHTMLMessage() {

//return "<html> " + "<title>" + "Hello Android" + "</title>"//+ "<body><h1>" + "Hello Android" + "</body></h1>" + "</html> ";

// }

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 5 of 35

Page 6: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

}

Figure 1 shows the directory structure of the AndroidJAX-RS client.

Figure 1. JAX-RS web service project

Next, run the resource class producing different types of output.

1. Uncomment the method to be tested for each of the test runs.

2. Test the text/plain MIME type as output.

3. Start the application/web server if it is not already started.

4. Right-click the resource class, and select Run As > Run on Server.

The AndroidJAX-RS application is deployed on the server.

Installing Maven plugins

You'll use Apache Maven, a software management tool, to build the Android project

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 6 of 35

Page 7: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

for a Spring client for the Android JAX-RS web service. Use the Maven Integrationproject to add Maven support to Eclipse. For Android application development withMaven, you need the Maven Android plugin, which you install in a later section,Configuring Maven plugins and dependencies. Maven Integration for AndroidDevelopment Tools is an Eclipse plugin that adds support for Maven Integration toAndroid Development Tools and the Maven Android plugin.

You can install the Maven Integration to Android Development Tools from theEclipse Marketplace.

1. Open the Eclipse IDE and select Help > Eclipse Marketplace.

2. On the Search tab of Eclipse Marketplace, specify m2eclipse-androidin the Find field and click Go (see Figure 2).Figure 2. Selecting the m2eclipse-android plugin

3. The Search tab now lists the Maven Integration for Android DevelopmentTools. Click Install (see Figure 3).Figure 3. Installing Maven Integration for Android DevelopmentTools

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 7 of 35

Page 8: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

4. On the Confirm Selected Features window, select the check boxes forthe Android Development Tools, Maven Integration for AndroidDevelopment Tools, and Maven Integration for Eclipse features (seeFigure 4). Click Next.Figure 4. Selecting the plugins to install

5. Accept the terms of the license agreement, and click Finish to completethe installation of the plugin software.To check the installed plugins, select Help > About Eclipse andInstallation Details in About Eclipse.

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 8 of 35

Page 9: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Creating a Spring Android client

In this section, you create an Android Spring client project for the JAX-RS webservice. You create an Android project in which you create the Spring client forAndroid to access the JAX-RS web service.

1. In Eclipse IDE, select File > New.

2. In the New window, select Android > Android Project. Click Next.

3. In the New Android Project window, specify a project name(AndroidSpring).

4. For Build Target, select Android Platform 2.2 API 8.

5. For Properties, specify an application name and a package name.

6. Select the Create Activity check box, and specify the Activity class(AndroidSpring) as in Figure 5. An activity represents a userinteraction, and the class extending the Activity class creates a windowfor a UI.

7. Specify the minimum SDK version as 8, and click Finish as in Figure 5.Figure 5. Creating a Spring Android client

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 9 of 35

Page 10: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

The Android project consists of the following files:

• An activity class(AndroidSpring), which extends the Activity class

• A res/layout/main.xml file to specify the layout of the Android

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 10 of 35

Page 11: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

application

• An AndroidManifest.xml file, which contains application configurationsuch as the package name, application components, processes,permissions, and the minimum API level for the Android system

In the res/layout/main.xml file, specify the layout of the Android UIcomponents in a LinearLayout element. Specify the value of theandroid:orientation attribute as vertical. Create a UI in which the responsefrom the web service is displayed as a text message.

Add a TextView element with the id "springmessage" to display the JAX-WS webservice response for a method call to one of the get methods. The methodinvocation gets a Hello message as a response in the form of XML, HTML, or text.Listing 5 shows the main.xml file.

Listing 5. main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">

<TextView android:id="@+id/springmessage"android:layout_width="fill_parent"

android:layout_height="wrap_content"/></LinearLayout>

To access the JAX-RS web service from an Android device, enable theandroid.permission.INTERNET permission in AndroidManifest.xml thatallows applications to open network sockets. Add the uses-permission elementin Listing 6.

Listing 6. Adding Internet permissions

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Specify the minimum Android version with the uses-sdk element. TheAndroidSpring activity, the intent-filter, and action are specified with thefollowing element. Listing 7 shows the AndroidManifest.xml file.

Listing 7. Adding Internet permissions

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="android.spring" android:versionCode="1" android:versionName="1.0"><uses-sdk android:minSdkVersion="8" /><application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".AndroidSpring" android:label="@string/app_name">

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 11 of 35

Page 12: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity>

</application><uses-sdk android:minSdkVersion="8" /><uses-permission

android:name="android.permission.INTERNET"></uses-permission></manifest>

Figure 6 shows the AndroidManifest.xml file viewed in the Eclipse IDE.

Figure 6. AndroidManifest.xml viewed in the Eclipse IDE

Select Java Build Path. On the Libraries tab, add thespring-android-rest-template JAR file to the Java build path as in Figure 7.

Figure 7. Spring Android REST template JAR in the Java build path

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 12 of 35

Page 13: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

org.springframework.web.client.RestTemplate implements RESTfulprinciples and is the central class for client-side HTTP access. Theorg.springframework.http package contains the basic abstraction overclient/server-side HTTP.

1. In the AndroidSpring class, import the RestTemplate class and theorg.springframework.http package. The AndroidSpring classextends the Activity class. The onCreate(Bundle savedInstanceState)method is invoked when the activity is first called.

2. Define the user interface using the setContentView method and thelayout resource.

setContentView(R.layout.main);

3. Create an Android widget TextView object using the findViewByIdmethod on the TextView element with id "springmessage" defined in themain.xml.

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 13 of 35

Page 14: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

TextView springmessage = (TextView) findViewById(R.id.springmessage);

4. Create a HttpHeaders object, which represents HTTP request andresponse headers.

HttpHeaders requestHeaders = new HttpHeaders();

5. Set the media type of the body as specified by the Content-Typeheader. The media type should match the media type produced by theJAX-RS web service.

requestHeaders.setContentType(new MediaType("text","plain"));

6. Create an HTTP request entity consisting of request headers.

HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);

7. Create a new instance of the RestTemplate using the constructor withthe default settings.

RestTemplate restTemplate = new RestTemplate();

8. Specify the URL to the resource hosted on the URI path /helloworld.

String url = "http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld";

9. Invoke the HTTP method to the specified URI template by sending therequest entity to the request using the exchange method. Theexchange method returns the response as ResponseEntity.

ResponseEntity<String> responseEntity =restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

10. Retrieve the response String from the ResponseEntity using thegetBody method.

ResponseEntity<String> String result = responseEntity.getBody();

11. Set the String message on the TextView UI component.

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 14 of 35

Page 15: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

springmessage.setText(result);

Listing 8 shows the AndroidSpring class.

Listing 8. AndroidSpring class

package anrdoid.spring;

import android.app.Activity;import android.os.Bundle;import android.widget.TextView;import org.springframework.web.client.RestTemplate;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.HttpEntity;import org.springframework.http.HttpMethod;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;

public class AndroidSpring extends Activity {/** Called when the activity is first created. */@Override

public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);TextView

springmessage = (TextView) findViewById(R.id.springmessage);// RestTemplate restTemplate = new RestTemplate();// String url =

"http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld";// String result = restTemplate.getForObject(url, String.class);

HttpHeadersrequestHeaders = new HttpHeaders();

requestHeaders.setContentType(new MediaType("text","xml"));HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);String url = "http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld";RestTemplate restTemplate = new RestTemplate();

ResponseEntity<String> responseEntity =restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

String result =responseEntity.getBody();

springmessage.setText(result);

}}

Configuring Maven plugins and dependencies

The configuration detail used by Maven to build a project is specified in pom.xml,which defines the Project Object Model for Maven. Project dependencies,repositories, and plugins are some of the configuration detail specified in thepom.xml file. You'll configure the following repositories, dependencies, and pluginsin pom.xml.

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 15 of 35

Page 16: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

• Spring Maven repository - Obtains Spring 3 artifacts with Maven

• Spring Maven Milestone Repository - Enables developing with latestSpring milestone

• Maven Android plugin - A Maven plugin for Android

• Maven compiler plugin - Compiles sources for a project

• Google Android dependency - Specifies dependency on the GoogleAndroid platform

• Spring Android REST Template Module dependency - Specifiesdependency on the spring-android-rest-template

First create a pom.xml in the AndroidSpring web project.

1. Select File > New.

2. In the New window, select XML > XML File, and click Next

3. In the New XML File wizard, select the AndroidSpring folder.

4. Specify File Name as pom.xml as in Figure 8. Click Next.Figure 8. Creating pom.xml

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 16 of 35

Page 17: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

5. Select Create XML File from an XML template, and click Next.

6. Select the xml declaration template, and click Finish.The SpringAndroid project now display the pom.xml configuration file,as in Figure 9.

Figure 9. pom.xml

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 17 of 35

Page 18: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Configure the plugins, repositories, and dependencies listed earlier. To specify theSpring Maven Snapshot Repository, set the following values (see Listing 9):

• In the <id> element, specifyorg.springframework.maven.snapshot

• In the <url> element, specifyhttp://maven.springframework.org/snapshot

• In the enabled element for releases, set the value to false

• In the enabled element for snapshots, set the value to true

Listing 9. Spring Maven Snapshot Repository

<repository><id>org.springframework.maven.snapshot</id><name>Spring Maven Snapshot Repository</name><url>http://maven.springframework.org/snapshot</url>

<releases><enabled>false</enabled>

</releases><snapshots>

<enabled>true</enabled></snapshots>

</repository>

Similarly, configure the Spring Maven Milestone Repository with the followingvalues:

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 18 of 35

Page 19: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

• In the id element, specify org.springframework.maven.milestone

• In the releases/enabled element, specify true

• In the enabled element for snapshots, set the value as false

Configure the Maven Android plugin with the values in Listing 10:

• In the groupId element, specifycom.jayway.maven.plugins.android.generation

• In the artifactId element, specify maven-android-plugin

• In the <configuration>element for the Maven Android plugin, specifythe SDK platform as 8 and the path to the SDK asC:/Android/android-sdk

• In the <emulator> element for the Maven Android plugin, specify the<avd> to be used.

Listing 10. Spring Maven Snapshot Repository

<plugin><groupId>com.jayway.maven.plugins.android.generation2</groupId>

<artifactId>maven-android-plugin</artifactId><version>2.8.3</version><configuration>

<sdk><platform>8</platform>

<path>C:/Android/android-sdk</path></sdk><emulator>

<avd>rhoAndroid30</avd></emulator>

<deleteConflictingFiles>true</deleteConflictingFiles><undeployBeforeDeploy>true</undeployBeforeDeploy>

</configuration><extensions>true</extensions>

</plugin>

In the <dependencies> element, configure the Google Android dependency with<artifactId> as android. Configure <dependency> element on the SpringAndroid REST Template Module with <artifactId> asspring-android-rest-template. Listing 11 lists the pom.xml configurationfile.

Listing 11. pom.xml

<projectxsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"xmlns="http://maven.apache.org/POM/4.0.0"

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 19 of 35

Page 20: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><modelVersion>4.0.0</modelVersion><groupId>anrdoid.spring</groupId><artifactId>spring-demo</artifactId><name>Spring Demo</name><packaging>apk</packaging><version>1.0</version>

<repositories><repository>

<id>org.springframework.maven.snapshot</id><name>Spring Maven Snapshot Repository</name><url>http://maven.springframework.org/snapshot</url><releases>

<enabled>false</enabled></releases><snapshots>

<enabled>true</enabled></snapshots>

</repository><!-- For developing against latest Spring milestones --><repository>

<id>org.springframework.maven.milestone</id><name>Spring Maven Milestone Repository</name><url>http://maven.springframework.org/milestone</url><snapshots>

<enabled>false</enabled></snapshots>

</repository></repositories><build>

<sourceDirectory>src</sourceDirectory><finalName>${project.artifactId}</finalName><plugins>

<plugin><groupId>com.jayway.maven.plugins.android.generation2</groupId>

<artifactId>maven-android-plugin</artifactId><version>2.8.3</version><configuration>

<sdk><platform>8</platform><path>C:/Android/android-sdk</path></sdk><emulator>

<avd>rhoAndroid30</avd></emulator>

<deleteConflictingFiles>true</deleteConflictingFiles><undeployBeforeDeploy>true</undeployBeforeDeploy>

</configuration><extensions>true</extensions>

</plugin><plugin>

<artifactId>maven-compiler-plugin</artifactId><version>2.3.2</version>

</plugin></plugins>

</build><dependencies>

<dependency><groupId>com.google.android</groupId><artifactId>android</artifactId><version>2.2.1</version><scope>provided</scope>

</dependency><dependency>

<groupId>org.springframework.android</groupId><artifactId>spring-android-rest-template</artifactId><version>1.0.0.BUILD-SNAPSHOT</version>

</dependency></dependencies>

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 20 of 35

Page 21: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

</project>

Specify additional dependencies and other elements from the XML schema forpom.xml (http://maven.apache.org/xsd/maven-4.0.0.xsd) as required. Now that youhave configured the Maven Android plugin, the Android dependency, the SpringAndroid REST Template dependency, the Maven Integration for Eclipse plugin, andMaven Integration for Android Development Tools, you can use Maven to developAndroid applications with a Spring client in Eclipse. But, Maven's integration withEclipse is not complete yet. You need to enable the dependency management,which is provided by the Maven Integration for Eclipse plugin. Right-click theAndroidSpring project, and select Maven > Enable Dependency Management.See Figure 10.

Figure 10. pom.xml

The required Maven dependencies and sources from Maven repositories aredownloaded and updated, and the project is built. The target folder is added to theSpringAndroid directory.

Configuring Android Maven goals

The Maven 2.0 build lifecycle consists of various build phases. Table 1 lists anddescribes the phases of the default build cycle.

Table 1. Default build cycle phases

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 21 of 35

Page 22: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Phase Description

validate Validates the project

compile Compiles the project source code

test Tests the compiled source code with a unittesting framework

package Packages the compiled code

integration-test Runs integration tests

verify Verifies the validity of the packaging

install Installs the packaging into the local repository

deploy In an integration and release environment, copiesthe package to a remote repository

When you invoke a build phase, you also invoke all the preceding build phases. Abuild phase consists of goals, which represent finer-grained specific tasks. A buildphase might be associated with zero or more goals. If a build phase does not haveany goals bound to it, the build phase does not run. Goals are assigned to buildphases with packaging and plugins. Set the packaging to apk in pom.xml:

<packaging>apk</packaging>

Based on the packaging type specified, specific goals are bound to the differentbuild phases. Some packaging types are available from plugins configured inpom.xml. The apk packaging type is available with the Maven Android plugin. Youconfigured the Maven Android plugin in pom.xml. To use the packaging typeassociated with the Maven Android plugin, set the extensions element to true asin Listing 12.

Listing 12. pom.xml

<plugin><groupId>com.jayway.maven.plugins.android.generation2</groupId><artifactId>maven-android-plugin</artifactId>......<extensions>true</extensions></plugin>

You can also add goals by configuring plugins in pom.xml. Each plugin providessome goals whose configuration, such as binding to a specific build phase, can beconfigured in pom.xml. With the packaging type apk, the Maven Android plugincustomizes the default Maven lifecycle and runs some additional tasks. Table 2 listsand describes those customizations to the default Maven lifecycle.

Table 2. Customizations to the default Maven phases

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 22 of 35

Page 23: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Maven phase Description

generate-sources Packages the Android-specific resources, suchas AndroidManifest.xml, using the Android AssetPackaging Tool (AAPT)

process-classes Converts all classes (libraries, resources, andproject code) into davlik executable format usingthe dx tool

package Creates the Android package file (Apk) using theAndroid package tool (apk) for installation on anemulator or device

pre-integration-test Deploys the Android package file (apk) includingdependencies to the emulator or device

integration-test Runs the instrumentation test classes against thedeployed application

Table 3 lists and describes the goals that the Maven Android plugin provides.

Table 3. Maven Android plugin goalsGoal Description

android:apk Creates the Android package file (apk).

android:deploy Deploys the built (or another) apk to emulator ordevice.

android:deploy-dependencies Deploys all dependencies of type apk.

android:dex Converts Java classes to Android DalvikExecutable (dex) format.

android:emulator-start Starts the Android emulator. You have configuredan emulator for the Maven Android plugin inpom.xml:<emulator><avd>rhoAndroid30</avd></emulator>You can also configure the start up parametersand options in the emulator element.

android:generate-sources Stops the Android emulator.

install Generates the R.java file and deletes anyR.java in the source directory. Generates Javafiles based on .aidl files and deletes any .javafiles with the same name as an .aidl file.

android:instrument Runs the instrumentation Android package onthe emulator/device.

android:internal-integration-test Is an internal goal associated with theintegration-test phase.

android:internal-pre-integration-test Is an internal goal associated with thepre-integration-test phase.

android:pull Copies files and directories from the emulator ordevice.

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 23 of 35

Page 24: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

android:push Copies files and directories to the emulator ordevice.

android:undeploy Undeploys the apk associated with the currentbuild project, or another specified apk, from theemulator or device.

Next, you configure some goals from the Maven Android plugin into the Mavenlifecycle. Right-click AndroidSpring, and select Run As > Maven build as inFigure 11.

Figure 11. Configuring a Maven-run configuration

In the Maven Build node, add a Run Configuration for theandroid:emulator-start goal. Specify a Run Configuration name(AndroidSpring), and specify the android:emulator-start in Goals as inFigure 12. Maven Runtime is the Embedded 3.0-Snapshot. Click Apply.

Figure 12. Configuring the android:emualtor-start goal

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 24 of 35

Page 25: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Similarly, configure another Run Configuration (AndroidSpring(2)). In Goals,specify the following Maven build phases and Maven Android plugin goal.

clean package android:deploy

The build phases (and any preceding build phases for each build phase lifecycle)and goals are invoked in the order specified. Figure 13 shows the Run ConfigurationAndroidSpring (2).

Figure 13. Run configuration to package and deploy the Spring client

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 25 of 35

Page 26: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Running the Spring client Android application

Next, run the Android Spring application. Right-click AndroidSpring, and selectRun As > Android Application as in Figure 14.

Figure 14. Running the Spring Android application

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 26 of 35

Page 27: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

The Maven configurations that you configured are listed. First, select theconfiguration to start the Android emulator as in Figure 15. Click OK.

Figure 15. Starting the Android emulator

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 27 of 35

Page 28: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Subsequently, select the configuration to deploy the Android apk file. TheAndroidSpring application is packaged as an apk and then deployed to theAndroid emulator. Figure 16 shows the AndroidSpring application in the Androidemulator.

Figure 16. Spring Android client application

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 28 of 35

Page 29: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Click the AndroidSpring application to run the application. The Spring client for theJAX-RS web service invokes the web service, and the message returned by the webservice displays in the Android emulator as in Figure 17.

Figure 17. Text response from running the Spring Android client

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 29 of 35

Page 30: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Modify the JAX-RS web service resource class to produce a text/xml messageinstead of a text/plain message. See Listing 13.

Listing 13. Producing text/xml message

@GET@Produces("text/xml")

public String getXMLMessage() {return "<?xml version=\"1.0\"?>" + "<hello> Hello Android" + "</hello>";}

Modify the SpringAndroid client application to set the request headers contenttype to text/xml. See Listing 14.

Listing 14. Setting request headers to text/xml

requestHeaders.setContentType(new MediaType("text","xml"));

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 30 of 35

Page 31: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Redeploy the AndroidJAX-RS web service resource class, and redeploy theSpringAndroid client application. Run the SpringAndroid application on theemulator to output the XML message received from the JAX-RS web service asshown in Figure 18.

Figure 18. text/xml response in Android with the Spring Android client

In this article, you created a Spring client for an JAX-RS web service using theSpring Android plugin.

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 31 of 35

Page 32: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Downloads

Description Name Size Downloadmethod

Spring Android Client Eclipse Project android-spring.zip 627KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 32 of 35

Page 33: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

Resources

Learn

• Android: Learn about Android tools, and read the documentation on how tocreate Android applications.

• The SOA and web services site of developerWorks: Get the project resourcesyou need to advance your web services skills.

• IBM JAX-RS: Developer's Guide: Get pointers about the IBM JAX-RS andWebSphere Application Server.

• JAX-RS Selection Algorithm: Learn more about the Java class annotated withJAX-RS annotations to represent a web resource.

• More articles by this author (Deepak Vohra, developerWorks, April2005-current): Read articles about Android, Ajax, PHP, XML, web services,Ruby on Rails, EJB, and other technologies.

• New to XML? Get the resources you need to learn XML.

• XML area on developerWorks: Find the resources you need to advance yourskills in the XML arena. See the XML technical library for a wide range oftechnical articles and tips, tutorials, standards, and IBM Redbooks

• IBM XML certification: Find out how you can become an IBM-CertifiedDeveloper in XML and related technologies.

• developerWorks technical events and webcasts: Stay current with technology inthese sessions.

• developerWorks on Twitter: Join today to follow developerWorks tweets.

• developerWorks podcasts: Listen to interesting interviews and discussions forsoftware developers.

• developerWorks on-demand demos: Watch demos ranging from productinstallation and setup for beginners to advanced functionality for experienceddevelopers.

Get products and technologies

• Android SDK: Download this SDK for the tools, sample code, and docs.

• Spring Android: Download and start using the Spring Framework in a Androidenvironment.

• Eclipse for Java EE: Download the latest version of tools for creating Java EEand web applications, including a Java IDE, tools for Java EE, JPA, JSF, Mylynand others.

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 33 of 35

Page 34: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

• Jersey: Download the Jersey bundle and the Jersey archive.

• JDK 6.0: Download the JDK 6.0 binaries.

• WebSphere Application Server: Download a Java EE 5 certified, EJB 3.0supported technology-based application platform, that drives business agilitywith an innovative, performance based foundation for your SOA environment onthe broadest range of platforms in the industry.

• IBM product evaluation versions: Download or explore the online trials in theIBM SOA Sandbox and get your hands on application development tools andmiddleware products from DB2®, Lotus®, Rational®, Tivoli®, andWebSphere®.

Discuss

• XML zone discussion forums: Participate in any of several XML-relateddiscussions.

• The developerWorks community: Connect with other developerWorks userswhile exploring the developer-driven blogs, forums, groups, and wikis.

About the author

Deepak VohraDeepak Vohra is a Sun Certified Java programmer, and Sun CertifiedWeb Component Developer. Deepak has published in Java Developer'sJournal and XML Journal.

Trademarks

IBM, the IBM logo, ibm.com, DB2, developerWorks, Lotus, Rational, Tivoli, andWebSphere are trademarks or registered trademarks of International BusinessMachines Corporation in the United States, other countries, or both. These and otherIBM trademarked terms are marked on their first occurrence in this information withthe appropriate symbol (® or ™), indicating US registered or common lawtrademarks owned by IBM at the time this information was published. Suchtrademarks may also be registered or common law trademarks in other countries.See the current list of IBM trademarks.Adobe, the Adobe logo, PostScript, and the PostScript logo are either registeredtrademarks or trademarks of Adobe Systems Incorporated in the United States,and/or other countries.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the

developerWorks® ibm.com/developerWorks

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 34 of 35

Page 35: Develop a Spring client for Android to a JAX-RS web servicepublic.dhe.ibm.com/software/dw/xml/x-springandroid/... · Spring, a platform to run Java enterprise applications, provides

United States, other countries, or both.Other company, product, or service names may be trademarks or service marks ofothers.

ibm.com/developerWorks developerWorks®

Develop a Spring client for Android to a JAX-RS web service Trademarks© Copyright IBM Corporation 2011 Page 35 of 35