Devoxx Java Social and Agorava

  • 1,025 views
Uploaded on

Slides of Devox 2012 university "Java Social JSR, it's alive". Talking about JSR 357 and Agorava framework

Slides of Devox 2012 university "Java Social JSR, it's alive". Talking about JSR 357 and Agorava framework

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,025
On Slideshare
0
From Embeds
0
Number of Embeds
10

Actions

Shares
Downloads
43
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Java Social JSR, It’s Alive Antoine Sabot-Durand Java EE Expert, Architect Ippon Technologies @antoine_sd Werner Keil Build Manager, DevOps Expert, Agile Coach Maersk Line @wernerkeilmardi 13 novembre 12
  • 2. Antoine Sabot-Durand • Java EE expert at Ippon Technologies • Architect and Tech consultant • 16 years in IT • Java & OSS : • Agorava technical leader • Apache Deltaspike Commiter • Member of l’EG CDI 1.1(JSR 346) • @antoine_sd 2mardi 13 novembre 12
  • 3. Werner Keil - Bio • Consultant – Coach • Creative Cosmopolitan • Open Source Evangelist • Software Architect • Java Godfather • JCP Executive Committee Member • Eclipse UOMo Project Lead • DevOps Guy 3mardi 13 novembre 12
  • 4. Agenda • Episode I : History – JSR 357 Rise and Fall • The precursors • From Seam Social to JSR 357 • What went Wrong? • Episode II : Standards in Social Media • The standards part • The non standard part • So what would be a Java Standard for Social Media ? 4mardi 13 novembre 12
  • 5. Agenda (2) • Espisode III : The Agorava Project • Agorava Demo • From JSR 357 to Agorava • Agorava architecture • Extending Agorava • Related JSR : Security & identity • Differences from other APIs and Frameworks • Episode IV: Agorava, the technical parts • Jackson Mapping Mixin • CDI in Agorava 0.5 • JsonSchema2Pojo • JAX-RS 2.0 client Framework in Agorava 1.0 • Episode V : Demo and Q&A 5mardi 13 novembre 12
  • 6. Episode I JSR 357 Rise and Fallmardi 13 novembre 12
  • 7. Before JSR 357 (Java Social) 7mardi 13 novembre 12
  • 8. Twitter4j • Twitter4J is an unofficial Java library for the Twitter API. With Twitter4J, you can easily integrate your Java application with Twitter. • Its author, Yusuke Yamamoto used to work at Twitter. While he did, he was briefly meant to represent Twitter in the Social JSR EG. • It’s light and based on Java 1.4 to be integrated in mobile app for instance 8mardi 13 novembre 12
  • 9. Scribe Java • Scribe is java framework that provides basic OAuth function • It also contains configuration for a lot of Social Media • Only one dependency on Apache Common Codec • At the heart of Agorava 0.5 9mardi 13 novembre 12
  • 10. DaliCore – CMS • More than a CMS → DaliCore • Adds functionality common to users, content and permissions on top of Java EE 6. • Focus on Users and Permissions. • In about every project that uses DaliCore, users should be able to login with existing credentials (Facebook, Twitter, Google Connect,...) • Dali modules extend DaliCore 10mardi 13 novembre 12
  • 11. Spring Social • Spring social that inspired Seam Social and Agorava and is more mature • Spring Social module were used to create first agorava modules (thanks to OSS and ASL2) • But it’s Spring only module.... 11mardi 13 novembre 12
  • 12. And then the JSR 357 was proposed • In march 2012 on Werner Keil initiative, Java Social was submitted to the JCP to become a JSR • It proposed to standardized access to Social Media in Java • It was voted down by 8 votes against 5 12mardi 13 novembre 12
  • 13. What went Wrong? (Feedback from vote) 13mardi 13 novembre 12
  • 14. Too Broad ? Maybe... 14mardi 13 novembre 12
  • 15. Too Soon? Lack of real POC... 15mardi 13 novembre 12
  • 16. It can’t be standardized? FALSE 16mardi 13 novembre 12
  • 17. Episode II Standards in Social Mediamardi 13 novembre 12
  • 18. Standard part in social media • All social medias use REST as transmission protocol • Most of them transmit data in JSON format and some in XML • Identification & Authentication are almost always based on OAuth protocol 18mardi 13 novembre 12
  • 19. REST • REpresentational State Transfer : Requests about resource representation (customer, book, order) • REST is based on low level HTTP concepts • Each resource has a unique identifier (an URI). 4 HTTP verbs can be applied to a uri : GET, POST, PUT, DELETE • Java has a standard to deal with REST: JAX-RS. Version 1.0 doesn’t provide client API yet. JAX-RS 2.0 will provide one 19mardi 13 novembre 12
  • 20. JSON Javascript Object Notation : This data 1: { 2: "firstName": "John", format comes from Javascript. It became a 3: 4: "lastName" : "Smith", "age" : 25, standard for online services including Social 5: 6: "address" : { Media. 7: "streetAddress": "21 2nd Street", 8: "city" : "New York", 9: "state" : "NY", 10: "postalCode" : "10021" 11: }, 12: "phoneNumber": 13: [ 14: { 15: "type" : "home", 16: "number": "212 555-1234" 17: }, 18: { 19: "type" : "fax", 20: "number": "646 555-4567" 21: } 22: ] 23: } 20mardi 13 novembre 12
  • 21. OAuth • OAuth is a protocol to delegate rights for an application to act on the behalf of an user who granted its rights without giving awayher login / password • Developped by Twitter, Magnolia and Google, it was made standard by IETF in april 2010 under RFC 5849 • Version 2.0, simpler to use but often citicised by its too many implementation s was standardized in October 2012 under RFC 6749 and 6750. It’s already used by many actors (Facebook, Google, Microsoft) • All social Media are based on OAuth 1.0a or 2.0. • To use OAuth, one has to create an application on the targeted service to have an entry point for consumer 21mardi 13 novembre 12
  • 22. OAuth has 3 step • Creating an application in the OAuth Social Media service • Initialization : the right granting phase also called the OAuth Dance. At the end of the dance we obtain an access token (formed by a public and secret part) use in next step • Signature : each request is signed with access token and token identifying the OAuth application that was granted the rights 22mardi 13 novembre 12
  • 23. OAuth Step 1 : Create an application 23mardi 13 novembre 12
  • 24. OAuth : application settings 24mardi 13 novembre 12
  • 25. The OAuth 1.0a «Dance» Social Media Service (where OAuth application is declared) user Consuming service server 25mardi 13 novembre 12
  • 26. The OAuth 1.0a «Dance» Social Media Service (where OAuth application is declared) user 1 client asks for a resource on the consuming service Consuming service server 25mardi 13 novembre 12
  • 27. The OAuth 1.0a «Dance» Social Media Service (where OAuth application is declared) user Consuming service ask a 1 request token tot he Social 2 Media (using OAuth application keys). It also send a callback url client asks for a resource on the consuming service Consuming service server 25mardi 13 novembre 12
  • 28. The OAuth 1.0a «Dance» Social Media Service (where OAuth application is declared) token is returned by SM user 3 Consuming service ask a 1 request token tot he Social 2 Media (using OAuth application keys). It also send a callback url client asks for a resource on the consuming service Consuming service server 25mardi 13 novembre 12
  • 29. The OAuth 1.0a «Dance» Social Media Service (where OAuth application is declared) Consuming service 4 redirect user on the social media login token is returned by SM page user 3 Consuming service ask a 1 request token tot he Social 2 Media (using OAuth application keys). It also send a callback url client asks for a resource on the consuming service Consuming service server 25mardi 13 novembre 12
  • 30. The OAuth 1.0a «Dance» Social Media Service Once authenticated, social media (where OAuth application is declared) redirects user on call back url with a verification code Consuming service 4 redirect user 5 on the social media login token is returned by SM page user 3 Consuming service ask a 1 request token tot he Social 2 Media (using OAuth application keys). It also send a callback url client asks for a resource on the consuming service Consuming service server 25mardi 13 novembre 12
  • 31. The OAuth 1.0a «Dance» Social Media Service Once authenticated, social media (where OAuth application is declared) redirects user on call back url with a verification code Consuming service 4 redirect user 5 on the social media login token is returned by SM page user 3 Consuming service ask a 1 request token tot he Social 2 Media (using OAuth 6 application keys). It also send a callback url client asks for a resource on the with the code and request token consuming service consuming service request an access token Consuming service server 25mardi 13 novembre 12
  • 32. The OAuth 1.0a «Dance» Social Media Service Once authenticated, social media (where OAuth application is declared) redirects user on call back url with a verification code Consuming Social media returns Access token service 4 redirect user 5 on the social 7 media login token is returned by SM page user 3 Consuming service ask a 1 request token tot he Social 2 Media (using OAuth 6 application keys). It also send a callback url client asks for a resource on the with the code and request token consuming service consuming service request an access token Consuming service server 25mardi 13 novembre 12
  • 33. The OAuth 2.0 «Dance» now in SSL Social Media Service (where OAuth application is declared) user Consuming service server 26mardi 13 novembre 12
  • 34. The OAuth 2.0 «Dance» now in SSL Social Media Service (where OAuth application is declared) user 1 client asks for a resource on the consuming service SSL is mandatory Consuming service server 26mardi 13 novembre 12
  • 35. The OAuth 2.0 «Dance» now in SSL Social Media Service (where OAuth application is declared) Consuming service redirect user 2 on the social media login page user 1 client asks for a resource on the consuming service SSL is mandatory Consuming service server 26mardi 13 novembre 12
  • 36. The OAuth 2.0 «Dance» now in SSL Social Media Service Once authenticated, social media (where OAuth application is declared) redirects user on call back url with a verification code Consuming service redirect user 2 3 on the social media login page user 1 client asks for a resource on the consuming service SSL is mandatory Consuming service server 26mardi 13 novembre 12
  • 37. The OAuth 2.0 «Dance» now in SSL Social Media Service Once authenticated, social media (where OAuth application is declared) redirects user on call back url with a verification code Consuming service redirect user 2 3 on the social media login page user 1 4 client asks for a with the code and request token resource on the consuming service request an access consuming service token SSL is mandatory Consuming service server 26mardi 13 novembre 12
  • 38. The OAuth 2.0 «Dance» now in SSL Social Media Service Once authenticated, social media (where OAuth application is declared) redirects user on call back url with a verification code Consuming Social media returns Access token service redirect user 2 3 on the social 5 media login page user 1 4 client asks for a with the code and request token resource on the consuming service request an access consuming service token SSL is mandatory Consuming service server 26mardi 13 novembre 12
  • 39. OAuth Signature : original request 27mardi 13 novembre 12
  • 40. OAuth Signature : original request POST /1/statuses/update.json?include_entities=true HTTP/1.1 Accept: */* Connection: close User-Agent: OAuth gem v0.4.4 Content-Type: application/x-www-form-urlencoded Content-Length: 76 Host: api.twitter.com status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth %20request%21 27mardi 13 novembre 12
  • 41. OAuth Signature : request & OAuth params 28mardi 13 novembre 12
  • 42. OAuth Signature : request & OAuth params status Hello Ladies + Gentlemen, a signed OAuth request! include_entities true oauth_consumer_key xvz1evFS4wEEPTGEFPHBog oauth_nonce kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg oauth_signature_method HMAC-SHA1 oauth_timestamp 1318622958 oauth_token 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb oauth_version 1.0 28mardi 13 novembre 12
  • 43. OAuth Signature : parameter string 29mardi 13 novembre 12
  • 44. OAuth Signature : parameter string include_entities=true&oauth_consumer_key=xvz1evFS4wEEPTGEFP HBog&oauth_nonce=kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg &oauth_signature_method=HMAC- SHA1&oauth_timestamp=1318622958&oauth_token=370773112- GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb&oauth_version=1.0& status=Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed %20OAuth%20request%21 29mardi 13 novembre 12
  • 45. OAuth Signature : Base String 30mardi 13 novembre 12
  • 46. OAuth Signature : Base String POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses %2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key %3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce %3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg %26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp %3D1318622958%26oauth_token%3D370773112- GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version %3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen %252C%2520a%2520signed%2520OAuth%2520request%2521 30mardi 13 novembre 12
  • 47. OAuth Signing key 31mardi 13 novembre 12
  • 48. OAuth Signing key Application consumer key secret part VQ5CZHG4qUoAkUUmckPn4iN4yyjBKcORTW0wnok4r1k& LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE Access Token secret part 31mardi 13 novembre 12
  • 49. OAuth Signature : Signed request 32mardi 13 novembre 12
  • 50. OAuth Signature : Signed request POST /1/statuses/update.json?include_entities=true HTTP/1.1 Accept: */* Connection: close User-Agent: OAuth gem v0.4.4 Content-Type: application/x-www-form-urlencoded Authorization: OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg", oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318622958", oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0" Content-Length: 76 Host: api.twitter.com status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21 32mardi 13 novembre 12
  • 51. The non Standard parts • Non standard identity management or any other API across Social Media • More than that. There is no Social Media that Guarantee : • Its API won’t change for a given period • backward compatibility when its API change 33mardi 13 novembre 12
  • 52. So what would be a standard for Social ? • A basic heart providing basic services : • OAuth and Rest request • Multi Social Media connexions • Polymorphic services to enforce standard on social Media • Connector definition for Social module • So this standard would be a kind Java Social Connector definition standard 34mardi 13 novembre 12
  • 53. Socializer Demomardi 13 novembre 12
  • 54. Episode III Agorava Projectmardi 13 novembre 12
  • 55. From JSR 357 to Agorava • Before Agorava there was Seam Social part of Seam 3 JBoss project • In begining of 2012, Seam was stopped to be merged in Apache DeltaSpike • Agorava was born mainly from Seam Social after JSR 357 attempt • One of it’s goals is to be the missing POC for a new Java Social JSR 37mardi 13 novembre 12
  • 56. Linked concept Security and Identity • Identity, Privacy and Trust • Identity attributes are properties of a digital subject • A digital subject is a digital representation of an entity that is an actor or target of a digital operation. • Privacy is the degree to which the availability of an entity’s identity attributes can be controlled • Trust is an evaluation of the reliability of a representation of a digital subject • An identity is a set of identity attributes that distinguish an entity 38mardi 13 novembre 12
  • 57. Identity for Social Media • Java Identity API (JSR 351) goals for Social Media • Attribute Service composed of attribute providers • specification will define contracts to facilitate repository integrations by third parties. • Reference Implementation will provide some specific integrations including those provided by contributors to Open Source project; Facebook, Twitter, and LinkedIn will be among the identity repositories considered for integration within the reference integration, as will their associated programming interfaces and protocols, including Facebook Connect, Google-ID and OAuth 2.0. 39mardi 13 novembre 12
  • 58. Facebook JSR 351 Example – Agent @Named("Facebook") public class FacebookRepositoryAgent implements RepositoryAgent { public AttributeRepository getAttributeRepository(String repositoryName) { TableIdentifier tID = null; AttributeRepository rvalue = null; try { tID = FacebookTableID.valueOf(repositoryName); rvalue = repositoryTable.get(tID); } catch (IllegalArgumentException iae) { } if (rvalue == null) { rvalue = new FacebookAttributeRepository(new RepositoryDescriptor(FacebookRepositoryAgent.class,tID.name())); repositoryTable.put(tID,rvalue); } return rvalue; } 56mardi 13 novembre 12
  • 59. Facebook JSR 351 Example – Repository public class FacebookAttributeRepository implements AttributeRepository { private RepositoryDescriptor _repositoryDescriptor; private ProviderLookupContext _context; FacebookLookupService _lookupService; public FacebookAttributeRepository(RepositoryDescriptor descriptor) { _repositoryDescriptor = descriptor; _context = new ProviderLookupContext(descriptor); _lookupService = new FacebookLookupService(this); } public RepositoryDescriptor getRepositoryDescriptor() { return _repositoryDescriptor; } […] public IDPredicate and(IDPredicate ... predicates) { return new FacebookPredicate(_context, IDBooleanOperator.and, predicates); } 57mardi 13 novembre 12
  • 60. Facebook JSR 351 Example – Connect JSONObject graphValues = getResponseValues(graphResponse); user = (String) graphValues.get(userPropertyName); Iterator<String> it = graphValues.keys(); while (it.hasNext()) { String key = it.next(); final URI id = new URI(userInfoEndpoint + "/" + key); final Collection<String> names = new ArrayList<String>(); final Object value = graphValues.get(key); final IDAttributeValue attributeValue = new IDAttributeValue() { public Serializable getValue() { return (Serializable) value; } public Collection getValues() { return Collections.EMPTY_LIST; } }; 58 }mardi 13 novembre 12
  • 61. Agorava Goals • Provides generics services across different Social Media (identification, Post, etc...) • Dynamic discovery of Social Media modules (core detect what modules are available at startup) • Managing multiple Social Media connection at the same time • Provides high level services (and binding) to interact with Social Media 43mardi 13 novembre 12
  • 62. Agorava 0.5 Macro architecture • Agorava core is the «smart Twitter Module LinkedIn Module Facebook Module Social Media X module part» of the framework • Modules are mainly REST Agorava Core API and JSON mapping CDI impl Guice impl Spring impl • Today Agorava has a CDI implementation only @Inject impl • On the roadmap we plan to Java SE Impl provide : • full Java SE support API • JSR 330 (Guice and/or Spring) support 44mardi 13 novembre 12
  • 63. Agorava core API architecture «interface» api.rest. «interface» «interface» api.oauth. api.oauth. RestRequest OAuthProvider OAuthRequest +send() +getRequestToken() +addOAuthParameter(String, String) +addHeader(String, String) +getAccessToken(OAuthToken, String) +getOauthParameters() +addBodyParameter(String, String) +signRequest(OAuthToken, OAuthRequest) +addBodyParameters(Map) +getVersion() +addQuerystringParameter(String, String) +getAuthorizationUrl(OAuthToken) +addPayload(String) +requestFactory(RestVerb, String) +getQueryStringParams() +tokenFactory(String, String) +getBodyParams() +getUrl() +getSanitizedUrl() «interface» «interface» +getBodyContents() api.oauth. api.oauth. +getVerb() OAuthAppSettings OAuthService +getHeaders() «interface» api.rest. +setConnectTimeout(int, TimeUnit) +getApiKey() +getAccessToken() RestService +setReadTimeout(int, TimeUnit) +getApiSecret() +getAuthorizationUrl() +getCompleteUrl() +getCallback() +getVerifier() +addPayload(byte[n]) +isConnected() +getCharset() +getScope() +initAccessToken() +getType() +setCharset(String) +getSocialMediaName() +sendSignedRequest(RestVerb, String) +get(String, Class) +setConnectionKeepAlive(boolean) +sendSignedRequest(RestVerb, String, Map) +get(String, Class, Object[n]) +sendSignedRequest(RestVerb, String, String, Object) +post(String, Map, Class) +setVerifier(String) +post(String, Object, Object[n]) +setAccessToken(String, String) «interface» +put(String, Object, Object[n]) +setAccessToken(OAuthToken) api.oauth. +delete(String) api. OAuthToken +sendSignedXmlRequest(RestVerb, String, String) UserProfile +setRequestHeader(Map) +getSession() cdi. +sendSignedRequest(OAuthRequest) AbstractSocialMediaApi +getToken() +get(String, Class, boolean) +getFullName() +getSecret() +getProfileImageUrl() +buildUri(String, String, String) +equals(Object) «interface» +buildUri(String, Map) api. «interface» +buildUri(String) SocialMediaApiHub api.oauth. +buildUri(String, Object) OAuthSession +getMyProfile() +resetConnection() +getRequestToken() +isConnected() +setRequestToken(OAuthToken) +getVerifierParamName() +getAccessToken() «interface» +getSocialMediaName() +setAccessToken(OAuthToken) api.oauth. +getVerifier() OAuthServiceAware +setVerifier(String) +setUserProfile(UserProfile) +getService() +getUserProfile() 45 +getSession() +getServiceQualifier() +isConnected() +getName()mardi 13 novembre 12
  • 64. Main classes «interface» «interface» «interface» api.oauth. api. api.oauth. cdi. OAuthProvider SocialMediaApiHub OAuthAppSettings AbstractSocialMediaApi +getRequestToken() +getMyProfile() +getApiKey() +buildUri(String, String, String) +getAccessToken(OAuthToken, String) +resetConnection() +getApiSecret() +buildUri(String, Map) +signRequest(OAuthToken, OAuthRequest) +isConnected() +getCallback() +buildUri(String) +getVersion() +getVerifierParamName() +getScope() +buildUri(String, Object) +getAuthorizationUrl(OAuthToken) +getSocialMediaName() +getSocialMediaName() +requestFactory(RestVerb, String) +tokenFactory(String, String) «interface» «interface» api.oauth. api.oauth. OAuthService OAuthSession +getAccessToken() +getRequestToken() +getAuthorizationUrl() +setRequestToken(OAuthToken) +getVerifier() +getAccessToken() +initAccessToken() +setAccessToken(OAuthToken) +sendSignedRequest(RestVerb, String) +getVerifier() +sendSignedRequest(RestVerb, String, Map) +setVerifier(String) +sendSignedRequest(RestVerb, String, String, Object) +setUserProfile(UserProfile) +setVerifier(String) +getUserProfile() +setAccessToken(String, String) +getServiceQualifier() +setAccessToken(OAuthToken) +isConnected() +sendSignedXmlRequest(RestVerb, String, String) +getName() +getSession() +sendSignedRequest(OAuthRequest) 46 +get(String, Class, boolean)mardi 13 novembre 12
  • 65. OAuth configuration public interface OAuthAppSettings { • OAuthAppSettings contains needed infos to start the OAuth public String getApiKey(); Dance : public String getApiSecret(); •Public and private keys of OAuth public String getCallback(); application public String getScope(); •Callback URL •OAuth 2.0 scope public String getSocialMediaName(); •Name of the Social Media to } which these settings are related 47mardi 13 novembre 12
  • 66. OAuth support public interface OAuthProvider { • OAuthProvider provides public OAuthToken getRequestToken(); OAuth support. Its public OAuthToken getAccessToken(OAuthToken tok, String ver); implementation uses public void signRequest(OAuthToken tok, OAuthRequest req); OAuthAppSettings to get initatilized • public String getVersion(); There one can : • public String getAuthorizationUrl(OAuthToken requestToken); Create a RequestToken public OAuthRequest requestFactory(RestVerb v, String uri); public OAuthToken tokenFactory(String token, String secret); • Get the URL to start connexion • } Get the Acces Token • Create OAuth signature 48mardi 13 novembre 12
  • 67. Rest calls with OAuthService public interface OAuthService extends RestService { • OAuthService uses public OAuthToken getAccessToken(); OAuthProvider to create and public String getAuthorizationUrl(); public String getVerifier(); sign requests. It provides public void initAccessToken(); higher level services : public RestResponse sendSignedRequest(RestVerb verb, String uri); public RestResponse sendSignedRequest(RestVerb verb, String uri, Map<String, ?> params); • Integration of user OAuth public RestResponse sendSignedRequest(RestVerb verb, String uri, String key, Object value); session public void setVerifier(String verifierStr); public void setAccessToken(String token, String secret); • Management of OAuth life public void setAccessToken(OAuthToken token); cycle public RestResponse sendSignedXmlRequest(RestVerb verb, String uri, String payload); public OAuthSession getSession(); • Sending simple Rest Request } public RestResponse sendSignedRequest(OAuthRequest request); <T> T get(String uri, Class<T> clazz, boolean signed); • Sending signed Rest Request 49mardi 13 novembre 12
  • 68. High level API root : AbstractSocialMediaApi • AbstractSocialMediaApi is the root for each family of API in a given social media module • Some services provides more than ten API families (for instance Twitter) • So we need a concept to gather these families 50mardi 13 novembre 12
  • 69. API families Hubs with SocialMediaApiHub public interface SocialMediaApiHub extends OAuthServiceAware, Serializable { • Hubs are here to : •Provide a gathering class public UserProfile getMyProfile(); for all API families of a public void resetConnection(); given service public boolean isConnected(); •Be the entry point of generic functionalities public String getVerifierParamName(); across different Social Media public String getSocialMediaName(); • They also are the entry } point of Social Media configuration 51mardi 13 novembre 12
  • 70. OAuthSession contains user specific infos • public interface OAuthSession extends Serializable { OAuthSession contains data public OAuthToken getRequestToken(); to handle the user part of an public void setRequestToken(OAuthToken requestToken); OAuth connexion : public OAuthToken getAccessToken(); • RequestToken • public void setAccessToken(OAuthToken accessToken); Verifier • public String getVerifier(); And last but not least public void setVerifier(String verifier); AccessToken public void setUserProfile(UserProfile userProfile); • OAuthSession keeps alos public UserProfile getUserProfile(); track of connected user public Annotation getServiceQualifier(); identity public boolean isConnected(); 52 }mardi 13 novembre 12
  • 71. Bootstraping Twitter in CDI Impl @Twitter Thanks to Generic Beans extension this @ApplicationScoped @OAuthApplication producer create 4 beans with different @Produces public SocialMediaApiHub OAuthSettinsProducer(TwitterServicesHub service) { scopes. } return service; By default OAuth app settings are read in agorava.properties file @Twitter @ApplicationScoped @Twitter @SessionScoped «interface» @Twitter @Twitter api.oauth. @ApplicationScoped OAuthService @ApplicationScoped «interface» api.oauth. +getAccessToken() OAuthSession +getAuthorizationUrl() +getVerifier() «interface» +initAccessToken() +getRequestToken() api.oauth. +sendSignedRequest(RestVerb, String) +setRequestToken(OAuthToken) «interface» OAuthProvider +sendSignedRequest(RestVerb, String, Map) +getAccessToken() api. +sendSignedRequest(RestVerb, String, String, Object) +setAccessToken(OAuthToken) SocialMediaApiHub +setVerifier(String) +getVerifier() +getRequestToken() +setAccessToken(String, String) +setVerifier(String) +getAccessToken(OAuthToken, String) +getMyProfile() +setAccessToken(OAuthToken) +setUserProfile(UserProfile) +signRequest(OAuthToken, OAuthRequest) +resetConnection() +sendSignedXmlRequest(RestVerb, String, String) +getUserProfile() +getVersion() +isConnected() +getSession() +getServiceQualifier() +getAuthorizationUrl(OAuthToken) +getVerifierParamName() +sendSignedRequest(OAuthRequest) +isConnected() +requestFactory(RestVerb, String) +getSocialMediaName() +get(String, Class, boolean) +getName() +tokenFactory(String, String) 53mardi 13 novembre 12
  • 72. Create a new Agorava module • To create a new module for Agorava 0.5, you have to : • Create a Qualifier (annotation) tagued with @ServiceRelated meta annotation • Create a low level API class containing basic endpoints to the new Social service. The class should use the same name as qualifier • Extend AbstractSocialMediaApi to create the root class for all API families of the new Social Media • Extend AbstractSocialMediaApiHub to gather Api families and implements generic services • At minima create Service class to deal with user profile in the new service 54mardi 13 novembre 12
  • 73. Episode IV Technologies in Agoravamardi 13 novembre 12
  • 74. Jacksonmardi 13 novembre 12
  • 75. Jackson • JSON to Pojo binding • A JAX-B like solution for JSON • Works with JAX-B anotations • Provides also Json parsing tools • Provides an elegant solution : the Mixin to configure mapping outside of the pojo 57mardi 13 novembre 12
  • 76. Mixin Example public class Trend { private final String name; private final String query; public Trend(String name, String query) { @JsonIgnoreProperties(ignoreUnknown = true) this.name = name; abstract class TrendMixin { this.query = query; } @JsonCreator TrendMixin(@JsonProperty("name") String name, public String getName() { @JsonProperty("query") String query) { return name; } } } public String getQuery() { return query; } } 58mardi 13 novembre 12
  • 77. Module configuration is needed to use mixin class TwitterModule extends SimpleModule { public TwitterModule() { super("TwitterModule", new Version(1, 0, 0, null)); } @Override public void setupModule(SetupContext context) { context.setMixInAnnotations(TwitterProfile.class, TwitterProfileMixin.class); context.setMixInAnnotations(SavedSearch.class, SavedSearchMixin.class); context.setMixInAnnotations(Trend.class, TrendMixin.class); } } ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new TwitterModule); 59mardi 13 novembre 12
  • 78. CDImardi 13 novembre 12
  • 79. Simple dependency injection @ApplicationScoped public class JsonMapperJackson implements JsonMapper { ... } public class OAuthServiceImpl implements OAuthService { ... @Inject protected JsonMapper jsonService; ... } 61mardi 13 novembre 12
  • 80. Qualified Injection @Qualifier @ServiceRelated @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Twitter { } public abstract class TwitterBaseService extends AbstractSocialMediaApi { ... @Inject @Twitter private OAuthService service; ... } 62mardi 13 novembre 12
  • 81. Producer @ApplicationScoped public class JsonMapperJackson implements JsonMapper { @Produces private final ObjectMapper objectMapper = new ObjectMapper(); ... } public class GraphApiImpl extends FacebookBaseService implements GraphApi { @Inject private ObjectMapper objectMapper; ... } 63mardi 13 novembre 12
  • 82. Programatic injection public class OAuthServiceImpl implements OAuthService { @Inject @Any private Instance<OAuthProvider> providers; ... protected Annotation qualifier; ... private OAuthProvider getProvider() { return providers.select(getQualifier()).get(); } ... } 64mardi 13 novembre 12
  • 83. Programmatic injection for Mixin @Twitter @ServiceX class TwitterModule extends SimpleModule { class ServiceXModule extends SimpleModule { ... ... } } @Facebook class FacebookModule extends SimpleModule { ... } @Inject @Any protected Instance<Module> moduleInstances; ... @PostConstruct protected void init() { for (Module module : moduleInstances) { registerModule(module); } } 65mardi 13 novembre 12
  • 84. Context & context Mixup @SessionScoped public class MultiSessionManagerImpl implements MultiSessionManager, Serializable { @Produces @Named @Current private OAuthSession currentSession; public String initNewSession(String servType) { Annotation qualifier = getServicesToQualifier().get(servType); setCurrentSession(new OAuthSessionImpl(qualifier)); return getCurrentService().getAuthorizationUrl(); } } @ApplicationScoped public class OAuthServiceImpl implements OAuthService { @Inject @Any protected Instance<OAuthSession> sessionInstances; ... 66 }mardi 13 novembre 12
  • 85. Decorator @Decorator public abstract class TwitterTLServiceDecorator implements TwitterTimelineService { @Inject @Delegate @Any private TwitterTimelineService delegate; @Override public Tweet updateStatus(String status) { System.out.println("*** In Decorator ***"); delegate.updateStatus(status + "decorated" ); } } 67mardi 13 novembre 12
  • 86. Events public class OAuthServiceImpl implements OAuthService { ... @Inject @Any private Event<OAuthComplete> completeEventProducer; ... public synchronized void initAccessToken() { session.setAccessToken(getProvider().getAccessToken(getRequestToken(), session.getVerifier())); Event<OAuthComplete> event = completeEventProducer.select(getQualifier()); event.fire(new OAuthComplete(SocialEvent.Status.SUCCESS, "", session)); } } public class FacebookServicesHub extends AbstractSocialMediaApiHub { ... @Inject Instance<FacebookBaseService> services; ... public void initMyProfile(@Observes @Facebook OAuthComplete oauthComplete) { if (oauthComplete.getStatus() == Status.SUCCESS) oauthComplete.getEventData().setUserProfile(services.select(UserServiceImpl.class).get().getUserProfile()); } ... } 68mardi 13 novembre 12
  • 87. CDI extensionsmardi 13 novembre 12
  • 88. CDI Extensions why ? • An extension allows to • Create beans or injection points • modify beans or injection points • Cancel beans creation • More generally to analyse all beans and change them before the application is launch 70mardi 13 novembre 12
  • 89. Understanding extensions • Once the application is running, bean manager is immutable (no dynamic bean in CDI) • Extensions will be launch when the application is launch • Extensions are also Beans 71mardi 13 novembre 12
  • 90. CDI Lifecycle Deploy Process Process Before Undeploy Application Beans Producers Shutdown Application Process Before Bean Process Application Observer Discovery Injection Taget Running Methods After Scan Process After Bean Deployment Archive Anotated Types Discovery Validation 72mardi 13 novembre 12
  • 91. To create an extension • Create a class which implements Extension • Add one or more method that Observes CDI lifecycle steps to modify Bean Manager content • Add this file in classpath META-INF/services/javax.enterprise.inject.spi.Extension in which you add qualified name of the extension class 73mardi 13 novembre 12
  • 92. Simple Example : @Veto  <X> void processAnnotatedType(@Observes final ProcessAnnotatedType<X> pat, BeanManager beanManager) {         final AnnotatedType<X> annotatedType = pat.getAnnotatedType();         final Class<X> javaClass = annotatedType.getJavaClass();         final Package pkg = javaClass.getPackage();         // Support for @Veto         if (annotatedType.isAnnotationPresent(Veto.class) || (pkg != null && pkg.isAnnotationPresent(Veto.class))) {             pat.veto();             log.info("Preventing " + javaClass + " from being installed as bean due to @Veto annotation");             return;         } } 74mardi 13 novembre 12
  • 93. New technologies in version 1.0 • JAX-RS 2.0 client framework • Development has just started • It will deprecated Java Scribe in Agorava • OAuth filters has to be written for this client • Json 2 pojo schema • An easy way to generate pojo from Json • Demo 75mardi 13 novembre 12
  • 94. Major API Evolution in version 1.0 public interface HasTimeline { public interface HasUpdate { public List<String> getTimeLine(); public boolean sendUpdate(String message); public List<String> getTimeLine(Date from, Date to); } public List<String> getTimeLine(String fromId); } public class FacebookServicesHub extends AbstractSocialMediaApiHub implements HasUpdate, HasTimeline @Inject @Any Instance<HasUpdate> updatables; ... for (HasUpdate updatable : updatables) { updatable.sendUpdate(msg); 76 }mardi 13 novembre 12
  • 95. Q&Amardi 13 novembre 12
  • 96. Links • Agorava Project: http://agorava.org • Follow us http://twitter.com/agoravaproj • Fork Agorava http://github.com/agoravamardi 13 novembre 12
  • 97. Links • DaliCore: http://java.net/projects/dalicore/ • Oracle SocialLink: http://java.net/projects/sociallink • JSR 351 Identity API: http://java.net/projects/identity-api-spec • Nobis JSR 351 RI: http://java.net/projects/nobis/mardi 13 novembre 12