Android and iOS
Development with JAX-RS,
WebSocket and Java EE 7
Reza Rahman, Oracle
Balaji Muthuvarathan, CapTech
Ryan Cu...
Program Agenda

 Mobile Landscape
 Java EE
 iOS
 Android
 Java EE + Mobile Demo
 Best Practices/Summary
 Q&A

2Copy...
Mobile Platform Overview
 Dominated by Google’s Android and Apple’s iOS platforms.
– Android’s US market share is about 5...
Mobile Development Models
 Native App
– Built for a specific platform
– Downloadable app
– Objective-C/xCode, Java/Eclips...
Mobile Development Models (cont.)


Native App
–
–

Access all device/hardware capabilities

–



Best user experience
B...
Client/Server Connectivity
Two main types – RESTful services and WebSockets
 RESTful Services
–

Client/server communicat...
Client/Server Connectivity (cont.)


WebSockets
–

Offers true bi-directional (full-duplex) communication over a single
T...
Java EE/Mobile
Mobile Device
Mobile Device

Java API for
Java API for
WebSocket
WebSocket

JAX-RS
JAX-RS

Java API for
Jav...
JAX-RS
 REST development API for Java
 Server and client
 Annotation based, declarative
– @Path, @GET, @POST, @PUT, @DE...
JAX-RS Example
@Path("/atm/{cardId}")
public class AtmService {
@GET
@Path("/balance")
@Produces("text/plain")
public Stri...
JAX-RS Example
...
@POST
@Path("/withdrawal")
@Consumes("text/plain")
@Produces("application/json")
public Money withdraw(...
Java API for WebSocket
 High level declarative API for WebSocket
 Both client and server-side
 Small, powerful API
– @S...
WebSocket Sample
@ServerEndpoint("/chat")
public class ChatBean {
Set<Session> peers = Collections.synchronizedSet(…);
@On...
WebSocket Sample (Continued)
...
@OnMessage
public void message(String message, Session client) {
for (Session peer : peer...
iOS
Overview
 iOS provides built-in support for REST and JSON.
– Functionality can be augmented with external libraries l...
iOS and REST
Reskit
 RestKit: http://restkit.org
 Apache License
 Core Data Support
 Object Mapping
 Pluggable Parser...
iOS and REST
RestKit – Configuration

17Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
iOS and REST
RestKit – Object Mapping Setup

18Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Publi...
iOS and REST
RestKit – Invoking Service

19Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
iOS and REST
NSURL Approach

20Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
iOS and WebSocket
SocketRocket
 Open source library WebSocket library for iOS.
 http://github.com/square/SocketRocket
 ...
iOS and WebSocket
Delegate Methods

 Message Message Callback
-(void)webSocket:(SRWebSocket*)webSocket
didReceiveMessage:...
iOS and WebSocket
Open WebSocket Connection

Open Connection

Close Connection

23Copyright © 2012, Oracle and/or its affi...
Android
Overview
 Comes bundled with Apache HTTPClient
 Comes bundled with a rudimentary JSON library from json.org
– Ja...
Spring Android RestTemplate
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
Ma...
Android – HTTP Basic Authentication
import org.springframework.http.HttpAuthentication;
import org.springframework.http.Ht...
Autobahn Android WebSockets Client
private final WebSocketConnection mConnection = new
WebSocketConnection();
...
mConnect...
Android – SSL certs and Self-signed certs
 Using SSL certificates from established CAs requires no additional

work
 Usi...
Java EE + Android/iOS Demo

https://github.com/m-reza-rahman/javaee-mobile

29Copyright © 2012, Oracle and/or its affiliat...
Some Best Practices
 REST vs. WebSocket
– REST for the most part, WebSocket only for full-duplex, bidirectional

 JSON v...
Some Best Practices
 Testing
– Be-aware of data conversion issues: encoding, data precision, etc
– Write unit tests for a...
Best Practices
Tcpmon Troubleshooting

32Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Summary
 Mobile space dominated by Android, iOS native development
 The mobile client development model is still evolvin...
Resources
 Mobile Development Models
–

http://www.captechconsulting.com/sites/default/files/MobileWebinar_CageMatch_V7.p...
Resources
 RestKit
– http://restkit.org/

 SocketRocket
– http://corner.squareup.com/2012/02/socketrocket-websockets.htm...
Upcoming SlideShare
Loading in...5
×

Android and iOS Development with Java EE 7

11,287

Published on

Mobile application development powered by platforms like Andriod and iOS is here to stay. In this heavily code driven session, we will show you how you can effectively utilize Java EE as the back-end powerhouse for your Andriod and iOS applications.

We will show you how to write effective service APIs using JAX-RS, JSR 356/WebSocket, JSON-P, CDI and Bean Validation, how to hook these services up to Andriod and iOS applications and what best practices/pitfalls you should be aware of on the way.

Published in: Technology, Education
6 Comments
8 Likes
Statistics
Notes
No Downloads
Views
Total Views
11,287
On Slideshare
0
From Embeds
0
Number of Embeds
22
Actions
Shares
0
Downloads
215
Comments
6
Likes
8
Embeds 0
No embeds

No notes for slide
  • Use @Path to define web resources
    Use other annotations to map requests to methods
    Use method return value as response
    MBR and MBW help us behind the scenes
  • MBR and MBW can be user defined too
  • Android and iOS Development with Java EE 7

    1. 1. Android and iOS Development with JAX-RS, WebSocket and Java EE 7 Reza Rahman, Oracle Balaji Muthuvarathan, CapTech Ryan Cuprak, Dassault Systemès
    2. 2. Program Agenda  Mobile Landscape  Java EE  iOS  Android  Java EE + Mobile Demo  Best Practices/Summary  Q&A 2Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    3. 3. Mobile Platform Overview  Dominated by Google’s Android and Apple’s iOS platforms. – Android’s US market share is about 52% against iOS’s 42%  Windows Phone is at a distance 3rd place with about 4% share  Globally, Android’s market share is even higher 3Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    4. 4. Mobile Development Models  Native App – Built for a specific platform – Downloadable app – Objective-C/xCode, Java/Eclipse etc.  Mobile Web App – Service side apps that run in the device’s web browser – HTML 5, CSS3, JavaScript – jQuery Mobile, Sencha Touch – Responsive and Adaptive Web Designs  Hybrid App – Developed mostly using Mobile Web App technologies, but are executed like a native app in a native (wrapper) container – PhoneGap, ADF Mobile, IBM Worklight, AeroGear, Appcelerator 4Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    5. 5. Mobile Development Models (cont.)  Native App – – Access all device/hardware capabilities –  Best user experience But, development/maintenance will have to be done for every target mobile platform Mobile Web App – – Low barrier to entry – low learning curve, nothing to download for users – But, evolving HTML 5 standards and inconsistent adoption/support could impact user experience and timelines –  Target multiple platforms from a single code base Access to device capabilities (such as accelerometer) is limited as well Hybrid – Allows to target multiple platforms with a single code base, while maintaining access to device capabilities – But, native development may still be needed and performance may also suffer slightly 5Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    6. 6. Client/Server Connectivity Two main types – RESTful services and WebSockets  RESTful Services – Client/server communication from mobile applications commonly happens over HTTP, more often using REST style services – Stateless, lightweight, scalable – Typically JSON over HTTP/HTTPS. XML could be used as well – Client initiates the request – Commonly supported HTTP verbs include GET, POST, PUT, and DELETE – Uses existing web technologies and security standards – Fully supported by Java EE and GlassFish Server 6Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    7. 7. Client/Server Connectivity (cont.)  WebSockets – Offers true bi-directional (full-duplex) communication over a single TCP connection – Initial hand-shake over HTTP, but subsequent conversations over WebSockets – Supports asynchronous, extremely low-lag communication – Perfect for applications like chat and game – Uses existing web technologies and security standards – Supported by Java EE and GlassFish 7Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    8. 8. Java EE/Mobile Mobile Device Mobile Device Java API for Java API for WebSocket WebSocket JAX-RS JAX-RS Java API for Java API for JSON JSON JAXB JAXB Bean Validation Bean Validation Servlet Servlet EJB 33 EJB JPA JPA 8Copyright © 2012, Oracle and/or its affiliates. All rights reserved. CDI CDI JMS JMS Public JTA JTA JCA JCA
    9. 9. JAX-RS  REST development API for Java  Server and client  Annotation based, declarative – @Path, @GET, @POST, @PUT, @DELETE, @PathParam, @QueryParam, @Produces, @Consumes  Pluggable and extensible – Providers, filters, interceptors 9Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    10. 10. JAX-RS Example @Path("/atm/{cardId}") public class AtmService { @GET @Path("/balance") @Produces("text/plain") public String balance( @PathParam("cardId") String card, @QueryParam("pin") String pin) { return Double.toString(getBalance(card, pin)); } ... 10Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    11. 11. JAX-RS Example ... @POST @Path("/withdrawal") @Consumes("text/plain") @Produces("application/json") public Money withdraw( @PathParam("card") String card, @QueryParam("pin") String pin, String amount) { return getMoney(card, pin, amount); } } 11Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    12. 12. Java API for WebSocket  High level declarative API for WebSocket  Both client and server-side  Small, powerful API – @ServerEndpoint, @OnOpen, @OnClose, @OnMessage, @OnError, Session, Remote  Pluggable and extensible – Encoders, decoders, sub-protocols 12Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    13. 13. WebSocket Sample @ServerEndpoint("/chat") public class ChatBean { Set<Session> peers = Collections.synchronizedSet(…); @OnOpen public void onOpen(Session peer) { peers.add(peer); } @OnClose public void onClose(Session peer) { peers.remove(peer); } ... 13Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    14. 14. WebSocket Sample (Continued) ... @OnMessage public void message(String message, Session client) { for (Session peer : peers) { peer.getRemote().sendObject(message); } } } 14Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    15. 15. iOS Overview  iOS provides built-in support for REST and JSON. – Functionality can be augmented with external libraries like RestKit.  iOS has no built-in WebSocket support. – External library required such as SocketRocket.  SSL supported for both REST and WebSockets. 15Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    16. 16. iOS and REST Reskit  RestKit: http://restkit.org  Apache License  Core Data Support  Object Mapping  Pluggable Parser  Support MIME types, multi-part submissions 16Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    17. 17. iOS and REST RestKit – Configuration 17Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    18. 18. iOS and REST RestKit – Object Mapping Setup 18Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    19. 19. iOS and REST RestKit – Invoking Service 19Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    20. 20. iOS and REST NSURL Approach 20Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    21. 21. iOS and WebSocket SocketRocket  Open source library WebSocket library for iOS.  http://github.com/square/SocketRocket  Apache 2.0 License.  Comprehensive regression suite.  Supports secure WebSockets.  Implement proxy SRWebSocketDelegate.  Simple project integration. 21Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    22. 22. iOS and WebSocket Delegate Methods  Message Message Callback -(void)webSocket:(SRWebSocket*)webSocket didReceiveMessage:(id)message;  WebSocket Open Operation - (void)webSocketDidOpen:(SRWebSocket*)webSocket;  WebSocket Connection Failed - (void)webSocket:(SRWebSocket*)webSocket didFailWithError:(NSError*)error;  WebSocket Failed - (void)webSocket:(SRWebSocket*)webSocket didCloseWithCode:(NSInteger)code reason:(NSString*)reason wasClean:(BOOL)wasClean; 22Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    23. 23. iOS and WebSocket Open WebSocket Connection Open Connection Close Connection 23Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    24. 24. Android Overview  Comes bundled with Apache HTTPClient  Comes bundled with a rudimentary JSON library from json.org – Jackson – GSON  No out-of-box REST support – Spring Android RestTemplate – RESTDroid – JAX-RS/Jersey Client APIs on Android?  No out-of-box WebSockets support – Autobahn Android – Android WebSockets from CodeButler – WebSocket/Tyrus Client APIs on Android? 24Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    25. 25. Spring Android RestTemplate RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); ResponseEntity<ToDoResponse> response = ResponseEntityrestTemplate.exchange( urlStr, HttpMethod.POST, new HttpEntity<ToDoItem>(todoItem, httpHeaders), ToDoResponse.class ); 25Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    26. 26. Android – HTTP Basic Authentication import org.springframework.http.HttpAuthentication; import org.springframework.http.HttpBasicAuthentication; import org.springframework.http.HttpHeaders; ... HttpAuthentication authHeader = new HttpBasicAuthentication(username, password); defaultHeaders = new HttpHeaders(); defaultHeaders.setAuthorization(authHeader); 26Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    27. 27. Autobahn Android WebSockets Client private final WebSocketConnection mConnection = new WebSocketConnection(); ... mConnection.connect(wsuri, new WebSocketHandler() { @Override public void onOpen() { mConnection.sendTextMessage("Hello, world!"); } @Override public void onTextMessage(String payload) { Log.d(TAG, "Got echo: " + payload); } @Override public void onClose(int code, String reason) { Log.d(TAG, "Connection lost."); } }); 27Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    28. 28. Android – SSL certs and Self-signed certs  Using SSL certificates from established CAs requires no additional work  Using self-signed SSL certs (during development or otherwise) requires some tedious setup – Export the cert from the server – Save the cert as an asset in the Android application – Load the cert into a CertificateFactory within the application – Create Trust Manager with the self-signed CA – Create an SSL Context that uses the Trust Manager – Set the SSLContext as the default context – Spring RestTemplate will automatically use this new default SSLContext when communicating with HTTPS resources 28Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    29. 29. Java EE + Android/iOS Demo https://github.com/m-reza-rahman/javaee-mobile 29Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    30. 30. Some Best Practices  REST vs. WebSocket – REST for the most part, WebSocket only for full-duplex, bidirectional  JSON vs. XML – JSON hands down  Where to store state – Mostly on the client, synchronize/persist on the server  API design – Coarse grained, stateless, general purpose  Security – TLS, federated (OAuth), avoid sensitive data on client  Development model – Native -> Hybrid -> HTML 5? 30Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    31. 31. Some Best Practices  Testing – Be-aware of data conversion issues: encoding, data precision, etc – Write unit tests for all target platforms. – Use Java for baseline unit testing. 31Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    32. 32. Best Practices Tcpmon Troubleshooting 32Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    33. 33. Summary  Mobile space dominated by Android, iOS native development  The mobile client development model is still evolving, perhaps towards HTML 5  Communication to server side happens via REST and WebSocket  Java EE well positioned as a mobile backend, especially with JAXRS and the Java API for WebSocket  You can use our demo code as a starting point  There are some best practices to be aware of  Most importantly, have fun! 33Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    34. 34. Resources  Mobile Development Models – http://www.captechconsulting.com/sites/default/files/MobileWebinar_CageMatch_V7.pdf  Mobile Market Share – http://www.networkworld.com/news/2013/070813-iphone6-ios-marketshare-apple-android-271583.html  Java EE – http://oracle.com/javaee  Java EE Tutorial – http://docs.oracle.com/javaee/7/tutorial/doc/home.htm  Reference Implementation – http://glassfish.org – http://java.net/projects/tyrus – http://jersey.java.net 34Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    35. 35. Resources  RestKit – http://restkit.org/  SocketRocket – http://corner.squareup.com/2012/02/socketrocket-websockets.html  Autobahn Android – http://autobahn.ws/android  Spring Android RestTemplate – http://projects.spring.io/spring-android/  CapTech Mobile Practice – http://www.captechconsulting.com/services/systems-integration/mobile- technologies 35Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×