prototyping mobile applications with spring
DESCRIPTION
Speakers: Peter Buchop, Anne Fyk, STA Group Applied Spring Track A common challenge in mobile prototyping is creating an environment where both server side data services and client side applications integrate easily. The back end services need to be Internet accessible for communication to the mobile device. For easier integration with the client side mobile application, the services should be restful. To speed the prototyping process, it is important that services can be developed quickly, and changed easily, since they are typically standing in for real services during this phase. We wanted to see if these objectives could be met using the Spring Framework. For this evaluation we used Spring Boot, to allow easy creation of a server side Spring application, along with Spring Rest to meet the server side objectives and create the necessary services. Spring Android and iOS are used on the mobile client side to prototype a dashboard application that uses these services. In this session, we will demonstrate our results and lessons learned from creating a mobile prototyping ecosystem using Spring Boot, Spring Rest, Spring Android and iOS. Sample code will be provided.TRANSCRIPT
© 2014 SpringOne 2GX. All rights reserved. Do not distribute without permission.
Prototyping Mobile Applications With
SpringBy: Pete Buchhop and Anne Fyk
Agenda
• Mobile Software Engineering Problem Context
• Mobile Prototyping - Leveraging Spring
• Use Case: Paddle Score Entry with Spring
• Demo
• Spring Mobile
• Closing Comments
• Q&A
2
Pete’s Background
• Pete is a 25 year Senior Technology Executive in Banking and Capital Markets (BAML).
• Named the Bank of America/Merrill Lynch Inventor of the Year for the entire company.
• Bank of America Technology Fellow (one of first four in entire company).
• Bank of America/Merril Lynch he was an Award of Excellence Winner (awarded to top 1%).
• Pete is holder of 8 Patents (6 of them in the Mobile space).
• Seven Technical Certifications including Sun Certified Enterprise Architect & CISSP.
• Pete also has an MBA with a concentration in Finance.
3
Mobile Landscape Last 15 years
• 1999-2006 Age of Carrier Control• 1999 Launch of Blackberry 850
• 2002 PocketPC 2002 (Merlin)
• 2003 Android Founded
• 2005 Android acquired by Google
• Shift to Apple and Google• iPhone launch in June, 2007
• Dev Kit Released in Feb, 2008
• Launch of Android in Sep, 2008
• Enter the Tablet• 2010, iPad launches, successful
• 2012 Surface Launches
4
What Challenges Does this Ecosystem Raise?
5
• Multiple Tools
• Multiple Languages
• New Factors
−Location Based Services
−Push Notification
−Expectations
−Speed of Change
−Security (both in motion and at rest)
−Legal (Privacy Concerns)
−Reputational Risk
Challenges
① Need Internet Accessible Servers
② Need to be able to prototype services quickly
③ Need to be able to prototype the client application quickly
6
Use of Amazon Cloud / EC2 and Rapid Scripting
languages
7
Use of Amazon Cloud / EC2 and Rapid Scripting
languages
8
iOS SDK
Android Developer ToolkitLAMP
Linux, Apache, mySQL, PHP
Agenda
Mobile Software Engineering Problem Context
• Mobile Prototyping - Leveraging Spring
• Use Case: Paddle Score Entry with Spring
• Demo
• Spring Mobile
• Closing Comments
• Q&A
9
Anne’s Background
• 25 years of technology experience as a professional software developer in banking and trading industries.
• Most recently focused on mobile development and web based application development.
• Holder of 2 Patents in the Mobile space.
• Platform Tennis Enthusiast
10
How can be leveraged to address
these challenges?
11
Advantages to Using
• Prototype in same language, using familiar tools
• Easier to convert to production application.
• Simulate closer to actual application.
12
Hypothesis
13
Use of Amazon Cloud / EC2, Java, Spring Framework,
Spring Boot, Spring Android and Spring Mobile
14
Challenge 1 : Internet Accessible Servers
• Lots of Available Cloud Implementations Today
• Spring Boot - Allows easy configuration and deployment options.
15
Challenge 2: Prototype Services Quickly
• Current LAMP Implementation
• Uses PHP scripting which allows for quick development.
• Code cannot be taken forward in the application; it is throwaway code.
• Spring Framework
• Allows us to code in java using tools and APIs that are familiar.
• Code could be used in the actual implementation, not just the prototype.
• Features such as the @RestController help with rapid development.
16
Challenge 3 : Prototype Client Side Application
Quickly
• Current : Native tools kits for iOS and Android
• Android - Spring for Android – Can we leverage this?
• iOS - Nothing Spring specific
17
Agenda
• Mobile Software Engineering Problem Context
• Mobile Prototyping - Leveraging Spring
• Use Case: Paddle Score Entry with Spring
• Demo
• Spring Mobile
• Closing Comments
• Q&A
18
19
Use Case: Platform Tennis Score Entry System
What is Platform Tennis (a.k.a. Paddle) ?
20
Source :
• Racquet sport invented in 1928 and played outside in all types of weather,
primarily in the Winter.
• Court is about 1/3 size of tennis court.
• A heated platform helps keep the court dry and free of snow.
• Scoring is same as for tennis.
• Screens of “chicken wire” surround the court and are playable like the walls
in squash and racquetball.
Platform Tennis Court
21
Tournament Challenge - Locations
22
• Each paddle location has 2-6
courts and a “Paddle Hut”.
• 2011 Nationals in Chicago
used 23 different facilities and
~140 volunteers.
Image :Wilmette Park District
Next location determined by match outcome
• Where do I go next?
23
Draw Sheet Source:
24
Multiple Draws Source :
25
Navigating the Draws
26
Source :
Problem Description
• Need scores to be reported to keep tournament on track:
• Multiple Locations
• Multiple Draws
• Match location changes based on win or loss
• Injury and Default situations
• Currently players call in scores or use mobile web browser and/or volunteers take scores at huts.
27
Paddle Score Entry Prototype
Restful Web Service to return player’s next matches, receive score
updates :
• Challenge 1: Internet Accessible Servers
• Challenge 2: Prototype Services Quickly
iOS and Android client applications for score entry
• Challenge 3 : Prototype Client Side Application Quickly
28
Paddle Score Entry Restful Service Example
• Objective : Create a restful service that returns the player’s
scheduled match information based on the input phone number.
• Use @RestfulController Annotation
• New in Spring 4
• Tells Spring that every method in the controller should return a domain
object instead of a view
• Automatically converts the object to JSON
29
PaddleScoresController.java
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PaddleScoresController {
@RequestMapping(value="/getMatches", method=RequestMethod.GET)
public Matches matches(@RequestParam(value="phoneNumber", required=true) String phoneNumber) {
// retrieve matches from store based on phoneNumber
return getMatches(phoneNumber);
}
}
30
Match.java
public class Match {
private int roundNumber;
private String draw;
private String matchTime;
private String opposingTeam;
private String location;
private String winningTeam;
private String score;
public Match() {
}
// followed by getters & setters for each field
31
Matches.java
public class Matches {
private String phoneNumber;
private ArrayList<Match> matchList;
public Matches(String phoneNumber,) {
this.phoneNumber = phoneNumber;
createSampleMatches();
|}
public List<Match>getMatchList() {
return matches;
}
32
Matches.java continued
// remaining getters and setters
public void setMatchList(List<Match>matchList) {
this.matchList = matchList
}
public String getPhoneNumber() {
return phoneNumber;
}
Public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
33
Deployment : Spring Boot
• Spring Boot
• Makes the configuration decisions so that you don’t have to…
• All jars on classpath are combined into a single jar file.
• public static void main() method determines the entry point.
• Defaults Spring Boot dependencies to Spring Boot’s versions.
• Configures a number of dependencies and defaults based on class
path (Tomcat, H2, HSQL and Derby databases…)
34
Using Spring Boot Plugin
• Add to build.gradle
• dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:1.1.5.RELEASE")
}
• apply plugin: 'spring-boot’
35
Make Application an executable JAR
• Create Application.java
• Annotate the class with :
• @EnableAutoConfiguration – Uses the jars on the classpath to configure servers and components that the application needs such as Tomcat or Jetty, DispatchServlet, etc.
• @ComponentScan – Registers the Controllers.
• Define the public static void main() method
• Set it to use the SpringApplication helper class to manage it as a component in the application context.
36
Application.java
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
37
Build and Deploy
• Build
• ./gradlew clean build will create a single jar file
• Copy the jar file to the cloud instance
• Start the application :
• java –jar paddle-scores-0.1.0.jar
• Access • http://mycloudurl/paddlescores/getMatches?phoneNumber=“312-555-1212”
38
Deploy to existing Tomcat ?
• Good tutorial link included in the References slide
• Create a class to substitute for web.xml• Extend the SpringBootServletInitializer class• Override the configure method
• Changes to build.gradle• Add ‘war’ plugin (apply plugin: ‘war’)
• Change jar settings to war
• Tell spring that it doesn’t need to embed Tomcat:
configurations {
providedRuntime
}
dependencies {
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat”)
}
39
PaddleScoresController in action
40
mycloudurl
PaddleScores postScores
@RequestMapping(value="/postScores”)
public Matches matches(@RequestParam(value="roundNumber",required=true)
String roundNumber,@RequestBody Match match) {
int roundNumberInt = Integer.parseInt(roundNumber);
// create next match for simulation and save
updateMatches(roundNumberInt,match,teamName);
return matches;
}
41
Paddle Score Entry Restful Service
• Results
• Used @RestController and Spring boot to rapidly develop our restful service.
• Source Code listing (all java!) :
• Application.java – template
• PaddlescoresWebXml.java – template
• PaddleScoresController.java
• Match.java*
• Matches.java*
42
Paddle Score Entry – Client Side Apps
iOS and Android client applications for score entry
• Challenge 3 : Prototype Client Side Application Quickly
• iOS - Use 7.0 and Objective-C
• Android – Use Java and Spring for Android
43
iOS 7.0 - Matches Code Snippet - GET
NSJSONSerialization parses JSON into NSMutableDictionary :
44
NSError *jsonParsingError = nil;
NSMutableDictionary *matchesDict =
[NSJSONSerialization JSONObjectWithData:response
options:kNilOptions error:&jsonParsingError];
_myMatches = [_myMatchesDict valueForKey:@"matchList"];
for ( NSDictionary *matchDict in _myMatches) {
NSString *opposingTeam =
[self objectForKeyDefaultNil:matchDict key:@"opposingTeam"];
iOS 7.0 - Matches Code Snippet - POST
NSJSONSerialization converts JSON to NS* objects:
NSDictionary* jsonDictionary = [self.myMatch
toNSDictionary:self.phoneNumber];
NSError *error;
if ([NSJSONSerialization isValidJSONObject:jsonDictionary ]) {
NSData* jsonData = [NSJSONSerialization
dataWithJSONObject:jsonDictionary
options:NSJSONWritingPrettyPrinted error:&error];
45
iOS 7.0 - Matches Code Snippet - POST
Create a custom method in Match object to convert to NSDictionary:
- (NSMutableDictionary *)toNSDictionary:(NSString *)phoneNumber
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.location forKey:@”location"];
[dictionary setValue:self.draw forKey:@"draw"];
…
46
IOS 7 Client
• Results
Able to rapidly create iOS client with a few extra steps:
o Need to create code to handle connection to restful service
o Need to convert domain objects to NSDictionary for post
o Maybe future version of iOS will help ?
47
Paddle Score Entry – Android
Android client application for score entry
• Challenge 3 : Prototype Client Side Application Quickly
• Use Java and Spring for Android
48
Spring for Android
• Stated objective is to “simplify development of native Android applications”
• Core class is RestTemplate• Http Client and Methods for DELETE, GET, HEAD, OPTIONS, POST
and PUT
• Message Converters for XML, JSON, GSON and RSS and ATOM Feeds and more.
• Also supports GZIP Compression.
• Sample Projects exist for Twitter search, client, Facebook client, news reader ,basic auth.
49
Spring for Android – Code Sample
final String url = "http://mycloudurl/paddle-scores-
0.1.0/getMatches?phoneNumber=312.555.1212";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
GsonHttpMessageConverter());
Matches matches = restTemplate.getForObject(url,
Matches.class);
50
Spring for Android – Code Sample Continued
StringBuffer myMatchInfo = new StringBuffer();
myMatchInfo.append("Team Name: " + matches.getTeamName() + EOL);
myMatchInfo.append("Phone Number: " + matches.getPhoneNumber() + EOL);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
SimpleDateFormat displayFormat = new SimpleDateFormat("E hh:mm a");
for (Match match: matches.getMatches()) {
try {
Date matchDate = format.parse(match.getMatchTime());
String formattedMatchTime = displayFormat.format(matchDate);
myMatchInfo.append(match.getDraw() + " " + formattedMatchTime + " " + match.getLocation() + " "
+ match.getOpposingTeam() + EOL);
} catch (Exception ex) {
Log.e("Matches App" ,"Exception parsing date ");
}
} 51
Spring for Android - Dependencies
Spring Android :
<dependency>
<groupId>org.springframework.android</groupId>
<artifactId>spring-android-rest-template</artifactId>
<version>1.0.1.RELEASE</version>
</dependency>
GSON :
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
52
Spring for Android - Result on Emulator
53
Spring for Android
• Results
• Used Spring Android to rapidly create an app
• Reused Match and Matches domain objects from our restful service.
• Source code listing
• PaddleScoresActivity.java - view
• Match.java* - reused from restful service
• Matches.java* - reused from restful service
54
PaddleScores Prototype Next Steps
• Registration with Device info
• Push notification – “Would you like to enter your scores?”
• Save match info to device so that if out of coverage, scores can
be updated when back in coverage.
• Enhanced UI
55
Agenda
Mobile Software Engineering Problem Context
• Mobile Prototyping - Leveraging Spring
• Use Case: Paddle Score Entry with Spring
• Demo
• Spring Mobile
• Closing Comments
• Q&A
56
Demo
57
Agenda
• Mobile Software Engineering Problem Context
• Mobile Prototyping - Leveraging Spring
Use Case: Paddle Score Entry with Spring
Demo
• Spring Mobile
• Closing Comments
• Q&A
58
Spring Mobile Features
Provides features for browser experience:
• Device detection
• View resolvers
• Site preference
59
Spring Mobile Features continued
• Site preference / View Resolutiono versus Responsive Web
• Device Detection for Metrics
o Useful for collecting metrics
o Uses a “DeviceResolver” class to determine mobile, tablet or
“normal” desktop browser.
o Default resolver class uses a detection algorithm that is part
of the Wordpress Mobile Pack, but can be overridden.
60
Spring Mobile – Troubleshooting Device Detection
• The user-agent may incorrectly identify a device, so a
configuration mechanism to override is provided.
• New devices and types come out continuously and
sometimes break the detection algorithm.
• No standard for “User-agent” header.
• Need : an application that is internet accessible from all devices
and can return information about the device browser that
accessed it. (“Snoop”).
61
Spring Mobile – Snoop Controller Code snippet
public @ResponseBody String detectDevice(Device device, @RequestHeader(value="User-Agent") String userAgent) {
String deviceType = "unknown”;
if (device.isNormal()) {
deviceType = "normal”;
} else if (device.isMobile()) {
deviceType = "mobile”;
} else if (device.isTablet()) {
deviceType = "tablet";
}
String result = "Device Type : " + deviceType + "<br/>" + "User-agent : " + userAgent;
return result;}
62
Snoop Mobile – Use Spring Boot to Deploy
• Copy snoop-0.1.0.jar to cloud
• Run :
• Java –jar snoop-0.1.0.jar
• Access from browser on phone, tablet or browser
• http://yourCloudURL:8080/snoop
63
Spring Mobile – Snoop Results
• Safari MacBook Browser Result:
DeviceType: normal
User-agent : Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5)…
• iPhone 5 Result :
DeviceType : mobile
User-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) ….
• Possible Future Result :
DeviceType : watch
User-agent: Mozilla/5.0 (iWatch; CPU iWatch OS like Mac OS X) ….
64
Spring for Mobile
Results :
Used Spring Framework annotations and Spring Boot to rapidly
create troubleshooting app.
Source Code Listing :
• Application.java - template
• SnoopController.java
65
Recap : Prototyping with Spring
• Server Side
• Spring Boot
• Spring Framework (@RestController)
• Client Side
• Spring for Android
• Spring Mobile
66
Agenda
Mobile Prototyping – Past
Mobile Prototyping - Leveraging Spring
Use Case: Paddle Score Entry with Spring
Demo
Spring Mobile
• Closing Comments
• Q&A
67
68
Closing Comments
Other Mobile Talks at SpringOne
• Wednesday
• 12:45 Gradle for Android - Ken Kousen
• 2:30 Groovy Mobile Automation – Bobby Warner
• Thursday
• 12:45 Android and Groovy, a winning pair? - Cedric Champeau
Be sure to check latest listings for any updates!
69
References• Deploying Spring Boot Applications
• http://spring.io/blog/2014/03/07/deploying-spring-boot-applications
• Spring Boot - Good tutorial on how to deploy to existing Tomcat server
• http://spring.io/guides/gs/convert-jar-to-war/
• Spring Restful Services
• http://spring.io/guides/gs/rest-service/
• Spring Mobile Device Detection
• https://spring.io/guides/gs/device-detection/
• http://docs.spring.io/spring-mobile/docs/current/reference/html/device.html
70
References Continued
• Spring for Android
• Consuming XML from a RESTful Web Service with Android
• http://spring.io/guides/gs/consuming-rest-xml-android/
• Other Sample Projects
• https://github.com/spring-projects/spring-android-samples
• American Platform Tennis Associationo http://www.platformtennis.org
71
Agenda
Mobile Prototyping - Past
Mobile Prototyping - Leveraging Spring
Use Case: Paddle Score Entry with Spring
Demo
• Spring Mobile
Closing Comments
• Q&A
72
Thank you!
@mobileisforever
73