diff --git a/.gitignore b/.gitignore index 5c3b031d8..0e3e8d35c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,15 @@ -# Eclipse specific settings -.classpath -.project -.settings - -# IntelliJ Idea settings -.idea -*.iml - -# Netbeans settings -nb-configuration.xml -nbproject - -# Binaries -target +# Eclipse specific settings +.classpath +.project +.settings + +# IntelliJ Idea settings +.idea +*.iml + +# Netbeans settings +nb-configuration.xml +nbproject + +# Binaries +target diff --git a/LICENSE.txt b/LICENSE.txt index 8cde51fa9..3de404125 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,22 +1,22 @@ -The MIT License - -Copyright (c) 2013 hh.ru -Copyright (c) 2010 Pablo Fernandez - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +The MIT License + +Copyright (c) 2013 hh.ru +Copyright (c) 2010 Pablo Fernandez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index a521eb3e9..75addead1 100644 --- a/README.md +++ b/README.md @@ -1,114 +1,250 @@ -# Welcome to the home of ScribeJava, the simple OAuth Java lib! - -# Why use ScribeJava? - -### Dead Simple - -Who said OAuth/OAuth2 was difficult? Configuring ScribeJava is __so easy your grandma can do it__! check it out: - -```java -OAuthService service = new ServiceBuilder() - .apiKey(YOUR_API_KEY) - .apiSecret(YOUR_API_SECRET) - .build(LinkedInApi20.instance()); -``` - -That **single line** (added newlines for readability) is the only thing you need to configure ScribeJava with LinkedIn's OAuth API for example. - -### Threadsafe - -Hit ScribeJava as hard and with many threads as you like. - -### Async - -You can use ning async http client out-of-box, just use ServiceBuilderAsync - -### Supports all major 1.0a and 2.0 OAuth APIs out-of-the-box - -* AWeber (http://www.aweber.com/) -* Digg (http://digg.com/) -* Доктор на работе (http://www.doktornarabote.ru/) -* Facebook (https://www.facebook.com/) -* Flickr (https://www.flickr.com/) -* Foursquare (https://foursquare.com/) -* Freelancer (https://www.freelancer.com/) -* Genius (http://genius.com/) -* GitHub (https://github.com/) -* Google (https://www.google.ru/) -* HeadHunter ХэдХантер (https://hh.ru/) -* Imgur (http://imgur.com/) -* Kaixin 开心网 (http://www.kaixin001.com/) -* LinkedIn (https://www.linkedin.com/) -* Microsoft Live (https://login.live.com/) -* Mail.Ru (https://mail.ru/) -* Meetup (http://www.meetup.com/) -* NetEase (http://www.163.com/) -* Odnoklassniki Одноклассники (http://ok.ru/) -* Pinterest (https://www.pinterest.com/) -* 500px (https://500px.com/) -* Renren (http://renren.com/) -* Salesforce (https://www.salesforce.com/) -* Sina (http://www.sina.com.cn/ http://weibo.com/login.php) -* Skyrock (http://skyrock.com/) -* sohu 搜狐 (http://www.sohu.com/) -* StackExchange (http://stackexchange.com/) -* Trello (https://trello.com/) -* Tumblr (https://www.tumblr.com/) -* TUT.BY (http://www.tut.by/) -* Twitter (https://twitter.com/) -* Viadeo (http://viadeo.com/) -* VK ВКонтакте (http://vk.com/) -* XING (https://www.xing.com/) -* Yahoo (https://www.yahoo.com/) -* Misfit (http://misfit.com/) -* check the [examples folder](https://github.com/scribejava/scribejava/tree/master/scribejava-apis/src/test/java/com/github/scribejava/apis/examples) - -### Small and modular - -ScribeJava's code is small (about 1k LOC) and simple to understand. No smart-ass or "clever" hacks here. -You can use only 'core' or 'with apis' maven modules - -### Android-Ready - -Works out of the box with android(TM) applications. - -### Stable & bulletproof - -Good test coverage to keep you safe from harm. - -When something bad actually happens, ScribeJava's meaningful error messages will tell you exactly what went wrong, when and where. - -### Pull it from Maven Central! - -You can pull ScribeJava from the central maven repository, just add these to your __pom.xml__ file: - -```xml - - com.github.scribejava - scribejava-apis - 2.7.3 - -``` - -And in case you need just core classes (that's it, without any external API (FB, VK, GitHub, Google etc) specific code), you could pull just 'core' artifact. -```xml - - com.github.scribejava - scribejava-core - 2.7.3 - -``` - -## Getting started in less than 2 minutes - -Check the [Getting Started](https://github.com/scribejava/scribejava/wiki/getting-started) page and start rocking! Please Read the [FAQ](https://github.com/scribejava/scribejava/wiki/faq) before creating an issue :) - -Also, remember to read the [fantastic tutorial](http://akoskm.github.io/2015/07/31/twitter-sign-in-for-web-apps.html) that [@akoskm](https://twitter.com/akoskm) wrote to easily integrate a server side app with an API (twitter in this case). - -## Questions? - -Feel free to drop us an email or create issue right here on github.com - -## Forks - -If you have a useful fork that should be listed there please contact us +# Welcome to the home of ScribeJava, the simple OAuth Java lib! + +# Why use ScribeJava? + +### Dead Simple + +Who said OAuth/OAuth2 was difficult? Configuring ScribeJava is __so easy your grandma can do it__! check it out: + +```java +OAuthService service = new ServiceBuilder() + .apiKey(YOUR_API_KEY) + .apiSecret(YOUR_API_SECRET) + .build(LinkedInApi20.instance()); +``` + +That **single line** (added newlines for readability) is the only thing you need to configure ScribeJava with LinkedIn's OAuth API for example. + +### Threadsafe + +Hit ScribeJava as hard and with many threads as you like. + +### Async + +You can use ning async http client out-of-box, just use ServiceBuilderAsync + +### Supports all major 1.0a and 2.0 OAuth APIs out-of-the-box + +* Google + +* Facebook + +* Yahoo + +* LinkedIn + +* Twitter + +* Foursquare + +* Evernote + +* Vimeo + +* Windows Live + +* Odnoklassniki + +* Mail.ru + +* LinkedIn2.0 + +* Google2.0 + +* GitHub + +* and many more! check the [examples folder](https://github.com/scribejava/scribejava/tree/master/scribejava-apis/src/test/java/com/github/scribejava/apis/examples) + +### Small and modular + +ScribeJava's code is small (about 1k LOC) and simple to understand. No smart-ass or "clever" hacks here. +You can use only 'core' or 'with apis' maven modules + +### Android-Ready + +Works out of the box with android(TM) applications. + +### Stable & bulletproof + +Good test coverage to keep you safe from harm. + +When something bad actually happens, ScribeJava's meaningful error messages will tell you exactly what went wrong, when and where. + +### Pull it from Maven Central! + +You can pull ScribeJava from the central maven repository, just add these to your __pom.xml__ file: + +```xml + + com.github.scribejava + scribejava-apis + 2.5.3 + +``` + +And in case you need just core classes (that's it, without any external API (FB, VK, GitHub, Google etc) specific code), you could pull just 'core' artifact. +```xml + + com.github.scribejava + scribejava-core + 2.5.3 + +``` + +## Getting started in less than 2 minutes + +Check the [Getting Started](https://github.com/scribejava/scribejava/wiki/getting-started) page and start rocking! Please Read the [FAQ](https://github.com/scribejava/scribejava/wiki/faq) before creating an issue :) + +Also, remember to read the [fantastic tutorial](http://akoskm.github.io/2015/07/31/twitter-sign-in-for-web-apps.html) that [@akoskm](https://twitter.com/akoskm) wrote to easily integrate a server side app with an API (twitter in this case). + +## Questions? + +Feel free to drop us an email or create issue right here on github.com + +## Forks + +If you have a useful fork that should be listed there please contact us + + +## QQ登陆 + + final String apiKey = "101303927"; + final String apiSecret = "0c3ac6430d6e2f60dfb637101252417e "; + final OAuth20Service service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret) + .callback("http://www.yichisancun.com/qqlogin.htm").state("xxxx") + .scope("get_user_info,list_album,upload_pic,do_like").build(QQApi.instance()); + System.out.println(service.getAuthorizationUrl()) + +## 微信登陆 + + final String apiKey = "x"; + final String apiSecret = "x "; + final OAuth20Service service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret) + .callback("url").state("xxxx").scope("snsapi_login") + .build(WeiXinApi.instance()); + System.out.println(service.getAuthorizationUrl()); + +## 开源中国登陆 + + final OAuth20Service oschina = new ServiceBuilder().apiKey("CTJlkYcnBaZCsi4GGgUk").grantType("authorization_code") + .apiSecret("TlKrmPCKImAKEzk1ORZtdwooJKDIgXrF").callback("http://www.yichisancun.com/oschinalogin.htm") + .responseType("code").build(OschinaApi.instance()); + System.out.println(service.getAuthorizationUrl()); + + +======= +# Welcome to the home of ScribeJava, the simple OAuth Java lib! + +# Why use ScribeJava? + +### Dead Simple + +Who said OAuth/OAuth2 was difficult? Configuring ScribeJava is __so easy your grandma can do it__! check it out: + +```java +OAuthService service = new ServiceBuilder() + .apiKey(YOUR_API_KEY) + .apiSecret(YOUR_API_SECRET) + .build(LinkedInApi20.instance()); +``` + +That **single line** (added newlines for readability) is the only thing you need to configure ScribeJava with LinkedIn's OAuth API for example. + +### Threadsafe + +Hit ScribeJava as hard and with many threads as you like. + +### Async + +You can use ning async http client out-of-box, just use ServiceBuilderAsync + +### Supports all major 1.0a and 2.0 OAuth APIs out-of-the-box + +* AWeber (http://www.aweber.com/) +* Digg (http://digg.com/) +* Доктор на работе (http://www.doktornarabote.ru/) +* Facebook (https://www.facebook.com/) +* Flickr (https://www.flickr.com/) +* Foursquare (https://foursquare.com/) +* Freelancer (https://www.freelancer.com/) +* Genius (http://genius.com/) +* GitHub (https://github.com/) +* Google (https://www.google.ru/) +* HeadHunter ХэдХантер (https://hh.ru/) +* Imgur (http://imgur.com/) +* Kaixin 开心网 (http://www.kaixin001.com/) +* LinkedIn (https://www.linkedin.com/) +* Microsoft Live (https://login.live.com/) +* Mail.Ru (https://mail.ru/) +* Meetup (http://www.meetup.com/) +* NetEase (http://www.163.com/) +* Odnoklassniki Одноклассники (http://ok.ru/) +* Pinterest (https://www.pinterest.com/) +* 500px (https://500px.com/) +* Renren (http://renren.com/) +* Salesforce (https://www.salesforce.com/) +* Sina (http://www.sina.com.cn/ http://weibo.com/login.php) +* Skyrock (http://skyrock.com/) +* sohu 搜狐 (http://www.sohu.com/) +* StackExchange (http://stackexchange.com/) +* Trello (https://trello.com/) +* Tumblr (https://www.tumblr.com/) +* TUT.BY (http://www.tut.by/) +* Twitter (https://twitter.com/) +* Viadeo (http://viadeo.com/) +* VK ВКонтакте (http://vk.com/) +* XING (https://www.xing.com/) +* Yahoo (https://www.yahoo.com/) +* Misfit (http://misfit.com/) +* check the [examples folder](https://github.com/scribejava/scribejava/tree/master/scribejava-apis/src/test/java/com/github/scribejava/apis/examples) + +### Small and modular + +ScribeJava's code is small (about 1k LOC) and simple to understand. No smart-ass or "clever" hacks here. +You can use only 'core' or 'with apis' maven modules + +### Android-Ready + +Works out of the box with android(TM) applications. + +### Stable & bulletproof + +Good test coverage to keep you safe from harm. + +When something bad actually happens, ScribeJava's meaningful error messages will tell you exactly what went wrong, when and where. + +### Pull it from Maven Central! + +You can pull ScribeJava from the central maven repository, just add these to your __pom.xml__ file: + +```xml + + com.github.scribejava + scribejava-apis + 2.7.3 + +``` + +And in case you need just core classes (that's it, without any external API (FB, VK, GitHub, Google etc) specific code), you could pull just 'core' artifact. +```xml + + com.github.scribejava + scribejava-core + 2.7.3 + +``` + +## Getting started in less than 2 minutes + +Check the [Getting Started](https://github.com/scribejava/scribejava/wiki/getting-started) page and start rocking! Please Read the [FAQ](https://github.com/scribejava/scribejava/wiki/faq) before creating an issue :) + +Also, remember to read the [fantastic tutorial](http://akoskm.github.io/2015/07/31/twitter-sign-in-for-web-apps.html) that [@akoskm](https://twitter.com/akoskm) wrote to easily integrate a server side app with an API (twitter in this case). + +## Questions? + +Feel free to drop us an email or create issue right here on github.com + +## Forks + +If you have a useful fork that should be listed there please contact us +>>>>>>> branch 'master' of https://github.com/scribejava/scribejava.git diff --git a/checkstyle.xml b/checkstyle.xml index 9cba55776..c712331dd 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -1,124 +1,124 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 723b1b5e1..3413fe0d6 100644 --- a/pom.xml +++ b/pom.xml @@ -203,33 +203,7 @@ - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - - validate - validate - - ${basedir}/src - checkstyle.xml - UTF-8 - true - - - check - - - - + diff --git a/scribejava-apis/pom.xml b/scribejava-apis/pom.xml index 465b17303..a2a18902e 100644 --- a/scribejava-apis/pom.xml +++ b/scribejava-apis/pom.xml @@ -5,7 +5,7 @@ com.github.scribejava scribejava - 2.7.4-SNAPSHOT + 2.5.6-SNAPSHOT ../pom.xml diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/AWeberApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/AWeberApi.java index fe5d86691..780cb0c52 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/AWeberApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/AWeberApi.java @@ -1,37 +1,37 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class AWeberApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://auth.aweber.com/1.0/oauth/authorize?oauth_token=%s"; - private static final String REQUEST_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/request_token"; - private static final String ACCESS_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/access_token"; - - protected AWeberApi() { - } - - private static class InstanceHolder { - private static final AWeberApi INSTANCE = new AWeberApi(); - } - - public static AWeberApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return ACCESS_TOKEN_ENDPOINT; - } - - @Override - public String getRequestTokenEndpoint() { - return REQUEST_TOKEN_ENDPOINT; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class AWeberApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://auth.aweber.com/1.0/oauth/authorize?oauth_token=%s"; + private static final String REQUEST_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/request_token"; + private static final String ACCESS_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/access_token"; + + protected AWeberApi() { + } + + private static class InstanceHolder { + private static final AWeberApi INSTANCE = new AWeberApi(); + } + + public static AWeberApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return ACCESS_TOKEN_ENDPOINT; + } + + @Override + public String getRequestTokenEndpoint() { + return REQUEST_TOKEN_ENDPOINT; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/DiggApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/DiggApi.java index 047537d8a..0c3d50949 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/DiggApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/DiggApi.java @@ -1,37 +1,37 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class DiggApi extends DefaultApi10a { - - private static final String AUTHORIZATION_URL = "http://digg.com/oauth/authorize?oauth_token=%s"; - private static final String BASE_URL = "http://services.digg.com/oauth/"; - - protected DiggApi() { - } - - private static class InstanceHolder { - private static final DiggApi INSTANCE = new DiggApi(); - } - - public static DiggApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getRequestTokenEndpoint() { - return BASE_URL + "request_token"; - } - - @Override - public String getAccessTokenEndpoint() { - return BASE_URL + "access_token"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZATION_URL, requestToken.getToken()); - } - -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class DiggApi extends DefaultApi10a { + + private static final String AUTHORIZATION_URL = "http://digg.com/oauth/authorize?oauth_token=%s"; + private static final String BASE_URL = "http://services.digg.com/oauth/"; + + protected DiggApi() { + } + + private static class InstanceHolder { + private static final DiggApi INSTANCE = new DiggApi(); + } + + public static DiggApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getRequestTokenEndpoint() { + return BASE_URL + "request_token"; + } + + @Override + public String getAccessTokenEndpoint() { + return BASE_URL + "access_token"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZATION_URL, requestToken.getToken()); + } + +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/FlickrApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/FlickrApi.java index 0e1db4ea7..f07fda2e4 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/FlickrApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/FlickrApi.java @@ -1,47 +1,47 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -/** - * OAuth API for Flickr. - * - * @see Flickr API - */ -public class FlickrApi extends DefaultApi10a { - - protected FlickrApi() { - } - - private static class InstanceHolder { - private static final FlickrApi INSTANCE = new FlickrApi(); - } - - public static FlickrApi instance() { - return InstanceHolder.INSTANCE; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAccessTokenEndpoint() { - return "https://www.flickr.com/services/oauth/access_token"; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return "https://www.flickr.com/services/oauth/authorize?oauth_token=" + requestToken.getToken(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getRequestTokenEndpoint() { - return "https://www.flickr.com/services/oauth/request_token"; - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +/** + * OAuth API for Flickr. + * + * @see Flickr API + */ +public class FlickrApi extends DefaultApi10a { + + protected FlickrApi() { + } + + private static class InstanceHolder { + private static final FlickrApi INSTANCE = new FlickrApi(); + } + + public static FlickrApi instance() { + return InstanceHolder.INSTANCE; + } + + /** + * {@inheritDoc} + */ + @Override + public String getAccessTokenEndpoint() { + return "https://www.flickr.com/services/oauth/access_token"; + } + + /** + * {@inheritDoc} + */ + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return "https://www.flickr.com/services/oauth/authorize?oauth_token=" + requestToken.getToken(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getRequestTokenEndpoint() { + return "https://www.flickr.com/services/oauth/request_token"; + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/FoursquareApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/FoursquareApi.java index 69111d235..03ec1f238 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/FoursquareApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/FoursquareApi.java @@ -1,35 +1,35 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class FoursquareApi extends DefaultApi10a { - - private static final String AUTHORIZATION_URL = "http://foursquare.com/oauth/authorize?oauth_token=%s"; - - protected FoursquareApi() { - } - - private static class InstanceHolder { - private static final FoursquareApi INSTANCE = new FoursquareApi(); - } - - public static FoursquareApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "http://foursquare.com/oauth/access_token"; - } - - @Override - public String getRequestTokenEndpoint() { - return "http://foursquare.com/oauth/request_token"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZATION_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class FoursquareApi extends DefaultApi10a { + + private static final String AUTHORIZATION_URL = "http://foursquare.com/oauth/authorize?oauth_token=%s"; + + protected FoursquareApi() { + } + + private static class InstanceHolder { + private static final FoursquareApi INSTANCE = new FoursquareApi(); + } + + public static FoursquareApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://foursquare.com/oauth/access_token"; + } + + @Override + public String getRequestTokenEndpoint() { + return "http://foursquare.com/oauth/request_token"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZATION_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/FreelancerApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/FreelancerApi.java index 52fe4cc1f..516c60c3f 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/FreelancerApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/FreelancerApi.java @@ -1,78 +1,78 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; -import com.github.scribejava.core.model.Verb; - -public class FreelancerApi extends DefaultApi10a { - - private static final String AUTHORIZATION_URL = "http://www.freelancer.com/users/api-token/auth.php?oauth_token=%s"; - - protected FreelancerApi() { - } - - private static class InstanceHolder { - private static final FreelancerApi INSTANCE = new FreelancerApi(); - } - - public static FreelancerApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "http://api.freelancer.com/RequestAccessToken/requestAccessToken.xml?"; - } - - @Override - public String getRequestTokenEndpoint() { - return "http://api.freelancer.com/RequestRequestToken/requestRequestToken.xml"; - } - - @Override - public Verb getAccessTokenVerb() { - return Verb.GET; - } - - @Override - public Verb getRequestTokenVerb() { - return Verb.GET; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZATION_URL, requestToken.getToken()); - } - - public static class Sandbox extends FreelancerApi { - - private static final String SANDBOX_AUTHORIZATION_URL - = "http://www.sandbox.freelancer.com/users/api-token/auth.php"; - - private Sandbox() { - } - - private static class InstanceHolder { - private static final Sandbox INSTANCE = new Sandbox(); - } - - public static Sandbox instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getRequestTokenEndpoint() { - return "http://api.sandbox.freelancer.com/RequestRequestToken/requestRequestToken.xml"; - } - - @Override - public String getAccessTokenEndpoint() { - return "http://api.sandbox.freelancer.com/RequestAccessToken/requestAccessToken.xml?"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(SANDBOX_AUTHORIZATION_URL + "?oauth_token=%s", requestToken.getToken()); - } - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.model.Verb; + +public class FreelancerApi extends DefaultApi10a { + + private static final String AUTHORIZATION_URL = "http://www.freelancer.com/users/api-token/auth.php?oauth_token=%s"; + + protected FreelancerApi() { + } + + private static class InstanceHolder { + private static final FreelancerApi INSTANCE = new FreelancerApi(); + } + + public static FreelancerApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://api.freelancer.com/RequestAccessToken/requestAccessToken.xml?"; + } + + @Override + public String getRequestTokenEndpoint() { + return "http://api.freelancer.com/RequestRequestToken/requestRequestToken.xml"; + } + + @Override + public Verb getAccessTokenVerb() { + return Verb.GET; + } + + @Override + public Verb getRequestTokenVerb() { + return Verb.GET; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZATION_URL, requestToken.getToken()); + } + + public static class Sandbox extends FreelancerApi { + + private static final String SANDBOX_AUTHORIZATION_URL + = "http://www.sandbox.freelancer.com/users/api-token/auth.php"; + + private Sandbox() { + } + + private static class InstanceHolder { + private static final Sandbox INSTANCE = new Sandbox(); + } + + public static Sandbox instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getRequestTokenEndpoint() { + return "http://api.sandbox.freelancer.com/RequestRequestToken/requestRequestToken.xml"; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://api.sandbox.freelancer.com/RequestAccessToken/requestAccessToken.xml?"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(SANDBOX_AUTHORIZATION_URL + "?oauth_token=%s", requestToken.getToken()); + } + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/LinkedInApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/LinkedInApi.java index 2d876ec5f..28a558f5c 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/LinkedInApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/LinkedInApi.java @@ -1,52 +1,52 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class LinkedInApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://api.linkedin.com/uas/oauth/authenticate?oauth_token=%s"; - private static final String REQUEST_TOKEN_URL = "https://api.linkedin.com/uas/oauth/requestToken"; - - private final String scopesAsString; - - public LinkedInApi() { - scopesAsString = null; - } - - public LinkedInApi(String... scopes) { - if (scopes == null || scopes.length == 0) { - scopesAsString = null; - } else { - final StringBuilder builder = new StringBuilder(); - for (String scope : scopes) { - builder.append('+').append(scope); - } - scopesAsString = "?scope=" + builder.substring(1); - } - } - - private static class InstanceHolder { - - private static final LinkedInApi INSTANCE = new LinkedInApi(); - } - - public static LinkedInApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "https://api.linkedin.com/uas/oauth/accessToken"; - } - - @Override - public String getRequestTokenEndpoint() { - return scopesAsString == null ? REQUEST_TOKEN_URL : REQUEST_TOKEN_URL + scopesAsString; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class LinkedInApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://api.linkedin.com/uas/oauth/authenticate?oauth_token=%s"; + private static final String REQUEST_TOKEN_URL = "https://api.linkedin.com/uas/oauth/requestToken"; + + private final String scopesAsString; + + public LinkedInApi() { + scopesAsString = null; + } + + public LinkedInApi(String... scopes) { + if (scopes == null || scopes.length == 0) { + scopesAsString = null; + } else { + final StringBuilder builder = new StringBuilder(); + for (String scope : scopes) { + builder.append('+').append(scope); + } + scopesAsString = "?scope=" + builder.substring(1); + } + } + + private static class InstanceHolder { + + private static final LinkedInApi INSTANCE = new LinkedInApi(); + } + + public static LinkedInApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://api.linkedin.com/uas/oauth/accessToken"; + } + + @Override + public String getRequestTokenEndpoint() { + return scopesAsString == null ? REQUEST_TOKEN_URL : REQUEST_TOKEN_URL + scopesAsString; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/MeetupApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/MeetupApi.java index b00db6159..fa0fb9ef7 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/MeetupApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/MeetupApi.java @@ -1,38 +1,38 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -/** - * OAuth access to the Meetup.com API. For more information visit http://www.meetup.com/api - */ -public class MeetupApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "http://www.meetup.com/authenticate?oauth_token=%s"; - - protected MeetupApi() { - } - - private static class InstanceHolder { - private static final MeetupApi INSTANCE = new MeetupApi(); - } - - public static MeetupApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getRequestTokenEndpoint() { - return "http://api.meetup.com/oauth/request/"; - } - - @Override - public String getAccessTokenEndpoint() { - return "http://api.meetup.com/oauth/access/"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +/** + * OAuth access to the Meetup.com API. For more information visit http://www.meetup.com/api + */ +public class MeetupApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "http://www.meetup.com/authenticate?oauth_token=%s"; + + protected MeetupApi() { + } + + private static class InstanceHolder { + private static final MeetupApi INSTANCE = new MeetupApi(); + } + + public static MeetupApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getRequestTokenEndpoint() { + return "http://api.meetup.com/oauth/request/"; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://api.meetup.com/oauth/access/"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/NeteaseWeibooApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/NeteaseWeibooApi.java index 91edb38ca..6f81507b3 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/NeteaseWeibooApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/NeteaseWeibooApi.java @@ -1,61 +1,61 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; -import com.github.scribejava.core.model.OAuth1Token; - -public class NeteaseWeibooApi extends DefaultApi10a { - - private static final String REQUEST_TOKEN_URL = "http://api.t.163.com/oauth/request_token"; - private static final String ACCESS_TOKEN_URL = "http://api.t.163.com/oauth/access_token"; - private static final String AUTHORIZE_URL = "http://api.t.163.com/oauth/authorize?oauth_token=%s"; - private static final String AUTHENTICATE_URL = "http://api.t.163.com/oauth/authenticate?oauth_token=%s"; - - protected NeteaseWeibooApi() { - } - - private static class InstanceHolder { - private static final NeteaseWeibooApi INSTANCE = new NeteaseWeibooApi(); - } - - public static NeteaseWeibooApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getRequestTokenEndpoint() { - return REQUEST_TOKEN_URL; - } - - @Override - public String getAccessTokenEndpoint() { - return ACCESS_TOKEN_URL; - } - - /** - * this method will ignore your callback if you're creating a desktop client please choose this url else your can - * call getAuthenticateUrl - * - * via - * http://open.t.163.com/wiki/index.php?title=%E8%AF%B7%E6%B1%82%E7%94%A8%E6%88%B7%E6%8E%88%E6%9D%83Token(oauth/authorize) - * @return url to redirect user to (to get code) - */ - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } - - /** - * this method is for web client with callback url if you're creating a desktop client please call - * getAuthorizationUrl - * - * via - * http://open.t.163.com/wiki/index.php?title=%E8%AF%B7%E6%B1%82%E7%94%A8%E6%88%B7%E6%8E%88%E6%9D%83Token(oauth/authenticate) - * - * @param requestToken Token - * @return String - */ - public String getAuthenticateUrl(OAuth1Token requestToken) { - return String.format(AUTHENTICATE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.model.OAuth1Token; + +public class NeteaseWeibooApi extends DefaultApi10a { + + private static final String REQUEST_TOKEN_URL = "http://api.t.163.com/oauth/request_token"; + private static final String ACCESS_TOKEN_URL = "http://api.t.163.com/oauth/access_token"; + private static final String AUTHORIZE_URL = "http://api.t.163.com/oauth/authorize?oauth_token=%s"; + private static final String AUTHENTICATE_URL = "http://api.t.163.com/oauth/authenticate?oauth_token=%s"; + + protected NeteaseWeibooApi() { + } + + private static class InstanceHolder { + private static final NeteaseWeibooApi INSTANCE = new NeteaseWeibooApi(); + } + + public static NeteaseWeibooApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getRequestTokenEndpoint() { + return REQUEST_TOKEN_URL; + } + + @Override + public String getAccessTokenEndpoint() { + return ACCESS_TOKEN_URL; + } + + /** + * this method will ignore your callback if you're creating a desktop client please choose this url else your can + * call getAuthenticateUrl + * + * via + * http://open.t.163.com/wiki/index.php?title=%E8%AF%B7%E6%B1%82%E7%94%A8%E6%88%B7%E6%8E%88%E6%9D%83Token(oauth/authorize) + * @return url to redirect user to (to get code) + */ + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } + + /** + * this method is for web client with callback url if you're creating a desktop client please call + * getAuthorizationUrl + * + * via + * http://open.t.163.com/wiki/index.php?title=%E8%AF%B7%E6%B1%82%E7%94%A8%E6%88%B7%E6%8E%88%E6%9D%83Token(oauth/authenticate) + * + * @param requestToken Token + * @return String + */ + public String getAuthenticateUrl(OAuth1Token requestToken) { + return String.format(AUTHENTICATE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/OschinaApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/OschinaApi.java new file mode 100644 index 000000000..0231e2763 --- /dev/null +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/OschinaApi.java @@ -0,0 +1,75 @@ +package com.github.scribejava.apis; + +import com.github.scribejava.apis.service.OsChinaOAuthServiceImpl; +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.extractors.OAuth2AccessTokenExtractor; +import com.github.scribejava.core.extractors.TokenExtractor; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +public class OschinaApi extends DefaultApi20 { + + private static final String AUTHORIZE_URL = "http://www.oschina.net/action/oauth2/authorize?client_id=%s&redirect_uri=%s"; + + protected OschinaApi() { + } + + private static class InstanceHolder { + private static final OschinaApi INSTANCE = new OschinaApi(); + } + + public static OschinaApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public Verb getAccessTokenVerb() { + return Verb.GET; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://www.oschina.net/action/openapi/token"; + } + +// @Override +// public String getAuthorizationUrl(OAuthConfig config) { +// Preconditions.checkValidUrl(config.getCallback(), +// "Must provide a valid url as callback. GitHub does not support OOB"); +// final StringBuilder sb = new StringBuilder(String.format(AUTHORIZE_URL, config.getApiKey(), +// OAuthEncoder.encode(config.getCallback()))); +// if (config.hasScope()) { +// sb.append('&').append(OAuthConstants.SCOPE).append('=').append(OAuthEncoder.encode(config.getScope())); +// } +// final String state = config.getState(); +// if (state != null) { +// sb.append('&').append(OAuthConstants.STATE).append('=').append(OAuthEncoder.encode(state)); +// } +// final String response_type = config.getResponseType(); +// if (response_type != null) { +// sb.append('&').append("response_type").append('=').append(OAuthEncoder.encode(response_type)); +// } +// return sb.toString(); +// } + + @Override + public TokenExtractor getAccessTokenExtractor() { + return OAuth2AccessTokenExtractor.instance(); + } + + @Override + public OAuth20Service createService(OAuthConfig config) { + return new OsChinaOAuthServiceImpl(this, config); + } + + @Override + protected String getAuthorizationBaseUrl() { + // TODO Auto-generated method stub + return "http://www.oschina.net/action/oauth2/authorize"; + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/Px500Api.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/Px500Api.java index 2c4e6de3c..535a91e20 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/Px500Api.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/Px500Api.java @@ -1,35 +1,35 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class Px500Api extends DefaultApi10a { - - private static final String AUTHORIZATION_URL = "https://api.500px.com/v1/oauth/authorize?oauth_token=%s"; - - protected Px500Api() { - } - - private static class InstanceHolder { - private static final Px500Api INSTANCE = new Px500Api(); - } - - public static Px500Api instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "https://api.500px.com/v1/oauth/access_token"; - } - - @Override - public String getRequestTokenEndpoint() { - return "https://api.500px.com/v1/oauth/request_token"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZATION_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class Px500Api extends DefaultApi10a { + + private static final String AUTHORIZATION_URL = "https://api.500px.com/v1/oauth/authorize?oauth_token=%s"; + + protected Px500Api() { + } + + private static class InstanceHolder { + private static final Px500Api INSTANCE = new Px500Api(); + } + + public static Px500Api instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://api.500px.com/v1/oauth/access_token"; + } + + @Override + public String getRequestTokenEndpoint() { + return "https://api.500px.com/v1/oauth/request_token"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZATION_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/QQApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/QQApi.java new file mode 100644 index 000000000..7293ddae5 --- /dev/null +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/QQApi.java @@ -0,0 +1,75 @@ +package com.github.scribejava.apis; + +import com.github.scribejava.apis.service.OsChinaOAuthServiceImpl; +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.extractors.OAuth2AccessTokenExtractor; +import com.github.scribejava.core.extractors.TokenExtractor; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +public class QQApi extends DefaultApi20 { + + private static final String AUTHORIZE_URL = "https://graph.qq.com/oauth2.0/authorize?client_id=%s&redirect_uri=%s"; + + protected QQApi() { + } + + private static class InstanceHolder { + private static final QQApi INSTANCE = new QQApi(); + } + + public static QQApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public Verb getAccessTokenVerb() { + return Verb.GET; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://graph.qq.com/oauth2.0/token"; + } + +// @Override +// public String getAuthorizationUrl(OAuthConfig config) { +// Preconditions.checkValidUrl(config.getCallback(), +// "Must provide a valid url as callback. GitHub does not support OOB"); +// final StringBuilder sb = new StringBuilder(String.format(AUTHORIZE_URL, config.getApiKey(), +// OAuthEncoder.encode(config.getCallback()))); +// if (config.hasScope()) { +// sb.append('&').append(OAuthConstants.SCOPE).append('=').append(OAuthEncoder.encode(config.getScope())); +// } +// final String state = config.getState(); +// if (state != null) { +// sb.append('&').append(OAuthConstants.STATE).append('=').append(OAuthEncoder.encode(state)); +// } +// final String response_type = config.getResponseType(); +// if (response_type != null) { +// sb.append('&').append("response_type").append('=').append(OAuthEncoder.encode(response_type)); +// } +// return sb.toString(); +// } + + @Override + public TokenExtractor getAccessTokenExtractor() { + return OAuth2AccessTokenExtractor.instance(); + } + + @Override + public OAuth20Service createService(OAuthConfig config) { + return new OsChinaOAuthServiceImpl(this, config); + } + + @Override + protected String getAuthorizationBaseUrl() { + // TODO Auto-generated method stub + return "https://graph.qq.com/oauth2.0/authorize"; + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/SinaWeiboApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/SinaWeiboApi.java index b91108c18..d33d15454 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/SinaWeiboApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/SinaWeiboApi.java @@ -1,37 +1,37 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class SinaWeiboApi extends DefaultApi10a { - - private static final String REQUEST_TOKEN_URL = "http://api.t.sina.com.cn/oauth/request_token"; - private static final String ACCESS_TOKEN_URL = "http://api.t.sina.com.cn/oauth/access_token"; - private static final String AUTHORIZE_URL = "http://api.t.sina.com.cn/oauth/authorize?oauth_token=%s"; - - protected SinaWeiboApi() { - } - - private static class InstanceHolder { - private static final SinaWeiboApi INSTANCE = new SinaWeiboApi(); - } - - public static SinaWeiboApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getRequestTokenEndpoint() { - return REQUEST_TOKEN_URL; - } - - @Override - public String getAccessTokenEndpoint() { - return ACCESS_TOKEN_URL; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class SinaWeiboApi extends DefaultApi10a { + + private static final String REQUEST_TOKEN_URL = "http://api.t.sina.com.cn/oauth/request_token"; + private static final String ACCESS_TOKEN_URL = "http://api.t.sina.com.cn/oauth/access_token"; + private static final String AUTHORIZE_URL = "http://api.t.sina.com.cn/oauth/authorize?oauth_token=%s"; + + protected SinaWeiboApi() { + } + + private static class InstanceHolder { + private static final SinaWeiboApi INSTANCE = new SinaWeiboApi(); + } + + public static SinaWeiboApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getRequestTokenEndpoint() { + return REQUEST_TOKEN_URL; + } + + @Override + public String getAccessTokenEndpoint() { + return ACCESS_TOKEN_URL; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/SkyrockApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/SkyrockApi.java index 02c0eb533..34edcc899 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/SkyrockApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/SkyrockApi.java @@ -1,43 +1,43 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -/** - * OAuth API for Skyrock. - * - * @see Skyrock.com API - */ -public class SkyrockApi extends DefaultApi10a { - - private static final String API_ENDPOINT = "https://api.skyrock.com/v2"; - private static final String REQUEST_TOKEN_RESOURCE = "/oauth/initiate"; - private static final String AUTHORIZE_URL = "/oauth/authorize?oauth_token=%s"; - private static final String ACCESS_TOKEN_RESOURCE = "/oauth/token"; - - protected SkyrockApi() { - } - - private static class InstanceHolder { - private static final SkyrockApi INSTANCE = new SkyrockApi(); - } - - public static SkyrockApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return API_ENDPOINT + ACCESS_TOKEN_RESOURCE; - } - - @Override - public String getRequestTokenEndpoint() { - return API_ENDPOINT + REQUEST_TOKEN_RESOURCE; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(API_ENDPOINT + AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +/** + * OAuth API for Skyrock. + * + * @see Skyrock.com API + */ +public class SkyrockApi extends DefaultApi10a { + + private static final String API_ENDPOINT = "https://api.skyrock.com/v2"; + private static final String REQUEST_TOKEN_RESOURCE = "/oauth/initiate"; + private static final String AUTHORIZE_URL = "/oauth/authorize?oauth_token=%s"; + private static final String ACCESS_TOKEN_RESOURCE = "/oauth/token"; + + protected SkyrockApi() { + } + + private static class InstanceHolder { + private static final SkyrockApi INSTANCE = new SkyrockApi(); + } + + public static SkyrockApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return API_ENDPOINT + ACCESS_TOKEN_RESOURCE; + } + + @Override + public String getRequestTokenEndpoint() { + return API_ENDPOINT + REQUEST_TOKEN_RESOURCE; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(API_ENDPOINT + AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/SohuWeiboApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/SohuWeiboApi.java index 6ef769c6a..d324f9aa7 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/SohuWeiboApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/SohuWeiboApi.java @@ -1,37 +1,37 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class SohuWeiboApi extends DefaultApi10a { - - private static final String REQUEST_TOKEN_URL = "http://api.t.sohu.com/oauth/request_token"; - private static final String ACCESS_TOKEN_URL = "http://api.t.sohu.com/oauth/access_token"; - private static final String AUTHORIZE_URL = "http://api.t.sohu.com/oauth/authorize?oauth_token=%s"; - - protected SohuWeiboApi() { - } - - private static class InstanceHolder { - private static final SohuWeiboApi INSTANCE = new SohuWeiboApi(); - } - - public static SohuWeiboApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getRequestTokenEndpoint() { - return REQUEST_TOKEN_URL; - } - - @Override - public String getAccessTokenEndpoint() { - return ACCESS_TOKEN_URL; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class SohuWeiboApi extends DefaultApi10a { + + private static final String REQUEST_TOKEN_URL = "http://api.t.sohu.com/oauth/request_token"; + private static final String ACCESS_TOKEN_URL = "http://api.t.sohu.com/oauth/access_token"; + private static final String AUTHORIZE_URL = "http://api.t.sohu.com/oauth/authorize?oauth_token=%s"; + + protected SohuWeiboApi() { + } + + private static class InstanceHolder { + private static final SohuWeiboApi INSTANCE = new SohuWeiboApi(); + } + + public static SohuWeiboApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getRequestTokenEndpoint() { + return REQUEST_TOKEN_URL; + } + + @Override + public String getAccessTokenEndpoint() { + return ACCESS_TOKEN_URL; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/TrelloApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/TrelloApi.java index 8fd95f7a2..989e36352 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/TrelloApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/TrelloApi.java @@ -1,36 +1,36 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class TrelloApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://trello.com/1/OAuthAuthorizeToken?oauth_token=%s"; - - protected TrelloApi() { - } - - private static class InstanceHolder { - private static final TrelloApi INSTANCE = new TrelloApi(); - } - - public static TrelloApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "https://trello.com/1/OAuthGetAccessToken"; - } - - @Override - public String getRequestTokenEndpoint() { - return "https://trello.com/1/OAuthGetRequestToken"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } - -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class TrelloApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://trello.com/1/OAuthAuthorizeToken?oauth_token=%s"; + + protected TrelloApi() { + } + + private static class InstanceHolder { + private static final TrelloApi INSTANCE = new TrelloApi(); + } + + public static TrelloApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://trello.com/1/OAuthGetAccessToken"; + } + + @Override + public String getRequestTokenEndpoint() { + return "https://trello.com/1/OAuthGetRequestToken"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } + +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/TumblrApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/TumblrApi.java index 1d7a9e93f..77e058024 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/TumblrApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/TumblrApi.java @@ -1,37 +1,37 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class TumblrApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://www.tumblr.com/oauth/authorize?oauth_token=%s"; - private static final String REQUEST_TOKEN_RESOURCE = "http://www.tumblr.com/oauth/request_token"; - private static final String ACCESS_TOKEN_RESOURCE = "http://www.tumblr.com/oauth/access_token"; - - protected TumblrApi() { - } - - private static class InstanceHolder { - private static final TumblrApi INSTANCE = new TumblrApi(); - } - - public static TumblrApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return ACCESS_TOKEN_RESOURCE; - } - - @Override - public String getRequestTokenEndpoint() { - return REQUEST_TOKEN_RESOURCE; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class TumblrApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://www.tumblr.com/oauth/authorize?oauth_token=%s"; + private static final String REQUEST_TOKEN_RESOURCE = "http://www.tumblr.com/oauth/request_token"; + private static final String ACCESS_TOKEN_RESOURCE = "http://www.tumblr.com/oauth/access_token"; + + protected TumblrApi() { + } + + private static class InstanceHolder { + private static final TumblrApi INSTANCE = new TumblrApi(); + } + + public static TumblrApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return ACCESS_TOKEN_RESOURCE; + } + + @Override + public String getRequestTokenEndpoint() { + return REQUEST_TOKEN_RESOURCE; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/TwitterApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/TwitterApi.java index 3d8a2aba7..c121a4bda 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/TwitterApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/TwitterApi.java @@ -1,63 +1,63 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class TwitterApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token=%s"; - private static final String REQUEST_TOKEN_RESOURCE = "api.twitter.com/oauth/request_token"; - private static final String ACCESS_TOKEN_RESOURCE = "api.twitter.com/oauth/access_token"; - - protected TwitterApi() { - } - - private static class InstanceHolder { - private static final TwitterApi INSTANCE = new TwitterApi(); - } - - public static TwitterApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "https://" + ACCESS_TOKEN_RESOURCE; - } - - @Override - public String getRequestTokenEndpoint() { - return "https://" + REQUEST_TOKEN_RESOURCE; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } - - /** - * Twitter 'friendlier' authorization endpoint for OAuth. - * - * Uses SSL. - */ - public static class Authenticate extends TwitterApi { - - private static final String AUTHENTICATE_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=%s"; - - private Authenticate() { - } - - private static class InstanceHolder { - private static final Authenticate INSTANCE = new Authenticate(); - } - - public static Authenticate instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHENTICATE_URL, requestToken.getToken()); - } - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class TwitterApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token=%s"; + private static final String REQUEST_TOKEN_RESOURCE = "api.twitter.com/oauth/request_token"; + private static final String ACCESS_TOKEN_RESOURCE = "api.twitter.com/oauth/access_token"; + + protected TwitterApi() { + } + + private static class InstanceHolder { + private static final TwitterApi INSTANCE = new TwitterApi(); + } + + public static TwitterApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://" + ACCESS_TOKEN_RESOURCE; + } + + @Override + public String getRequestTokenEndpoint() { + return "https://" + REQUEST_TOKEN_RESOURCE; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } + + /** + * Twitter 'friendlier' authorization endpoint for OAuth. + * + * Uses SSL. + */ + public static class Authenticate extends TwitterApi { + + private static final String AUTHENTICATE_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=%s"; + + private Authenticate() { + } + + private static class InstanceHolder { + private static final Authenticate INSTANCE = new Authenticate(); + } + + public static Authenticate instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHENTICATE_URL, requestToken.getToken()); + } + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/WeiXinApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/WeiXinApi.java new file mode 100644 index 000000000..018df8b11 --- /dev/null +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/WeiXinApi.java @@ -0,0 +1,55 @@ +package com.github.scribejava.apis; + +import com.github.scribejava.apis.service.OsChinaOAuthServiceImpl; +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.extractors.OAuth2AccessTokenExtractor; +import com.github.scribejava.core.extractors.TokenExtractor; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +public class WeiXinApi extends DefaultApi20 { + + + protected WeiXinApi() { + } + + private static class InstanceHolder { + private static final WeiXinApi INSTANCE = new WeiXinApi(); + } + + public static WeiXinApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public Verb getAccessTokenVerb() { + return Verb.GET; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://api.weixin.qq.com/sns/oauth2/access_token"; + } + + + @Override + public TokenExtractor getAccessTokenExtractor() { + return OAuth2AccessTokenExtractor.instance(); + } + + @Override + public OAuth20Service createService(OAuthConfig config) { + return new OsChinaOAuthServiceImpl(this, config); + } + + @Override + protected String getAuthorizationBaseUrl() { + // TODO Auto-generated method stub + return "https://open.weixin.qq.com/connect/qrconnect"; + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/XingApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/XingApi.java index 5bef0670b..5039a6db1 100755 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/XingApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/XingApi.java @@ -1,36 +1,36 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class XingApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://api.xing.com/v1/authorize?oauth_token=%s"; - - protected XingApi() { - } - - private static class InstanceHolder { - private static final XingApi INSTANCE = new XingApi(); - } - - public static XingApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "https://api.xing.com/v1/access_token"; - } - - @Override - public String getRequestTokenEndpoint() { - return "https://api.xing.com/v1/request_token"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } - -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class XingApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://api.xing.com/v1/authorize?oauth_token=%s"; + + protected XingApi() { + } + + private static class InstanceHolder { + private static final XingApi INSTANCE = new XingApi(); + } + + public static XingApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://api.xing.com/v1/access_token"; + } + + @Override + public String getRequestTokenEndpoint() { + return "https://api.xing.com/v1/request_token"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } + +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/YahooApi.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/YahooApi.java index 18352fdb0..958ff7081 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/YahooApi.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/YahooApi.java @@ -1,35 +1,35 @@ -package com.github.scribejava.apis; - -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class YahooApi extends DefaultApi10a { - - private static final String AUTHORIZE_URL = "https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=%s"; - - protected YahooApi() { - } - - private static class InstanceHolder { - private static final YahooApi INSTANCE = new YahooApi(); - } - - public static YahooApi instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public String getAccessTokenEndpoint() { - return "https://api.login.yahoo.com/oauth/v2/get_token"; - } - - @Override - public String getRequestTokenEndpoint() { - return "https://api.login.yahoo.com/oauth/v2/get_request_token"; - } - - @Override - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return String.format(AUTHORIZE_URL, requestToken.getToken()); - } -} +package com.github.scribejava.apis; + +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class YahooApi extends DefaultApi10a { + + private static final String AUTHORIZE_URL = "https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=%s"; + + protected YahooApi() { + } + + private static class InstanceHolder { + private static final YahooApi INSTANCE = new YahooApi(); + } + + public static YahooApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://api.login.yahoo.com/oauth/v2/get_token"; + } + + @Override + public String getRequestTokenEndpoint() { + return "https://api.login.yahoo.com/oauth/v2/get_request_token"; + } + + @Override + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return String.format(AUTHORIZE_URL, requestToken.getToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/DoktornaraboteOAuthServiceImpl.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/DoktornaraboteOAuthServiceImpl.java index 837449436..d9c9fb783 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/DoktornaraboteOAuthServiceImpl.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/DoktornaraboteOAuthServiceImpl.java @@ -1,19 +1,19 @@ -package com.github.scribejava.apis.service; - -import com.github.scribejava.core.builder.api.DefaultApi20; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class DoktornaraboteOAuthServiceImpl extends OAuth20Service { - - public DoktornaraboteOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { - super(api, config); - } - - @Override - public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { - request.addHeader("Authorization", "Bearer " + accessToken.getAccessToken()); - } -} +package com.github.scribejava.apis.service; + +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class DoktornaraboteOAuthServiceImpl extends OAuth20Service { + + public DoktornaraboteOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { + super(api, config); + } + + @Override + public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { + request.addHeader("Authorization", "Bearer " + accessToken.getAccessToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/HHOAuthServiceImpl.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/HHOAuthServiceImpl.java index 8d1799272..dec2e19d0 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/HHOAuthServiceImpl.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/HHOAuthServiceImpl.java @@ -1,19 +1,19 @@ -package com.github.scribejava.apis.service; - -import com.github.scribejava.core.builder.api.DefaultApi20; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class HHOAuthServiceImpl extends OAuth20Service { - - public HHOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { - super(api, config); - } - - @Override - public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { - request.addHeader("Authorization", "Bearer " + accessToken.getAccessToken()); - } -} +package com.github.scribejava.apis.service; + +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class HHOAuthServiceImpl extends OAuth20Service { + + public HHOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { + super(api, config); + } + + @Override + public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { + request.addHeader("Authorization", "Bearer " + accessToken.getAccessToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/ImgurOAuthServiceImpl.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/ImgurOAuthServiceImpl.java index ac80b1df6..e56bd7134 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/ImgurOAuthServiceImpl.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/ImgurOAuthServiceImpl.java @@ -1,39 +1,39 @@ -package com.github.scribejava.apis.service; - -import com.github.scribejava.apis.ImgurApi; -import com.github.scribejava.core.builder.api.DefaultApi20; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class ImgurOAuthServiceImpl extends OAuth20Service { - - public ImgurOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { - super(api, config); - } - - @Override - protected T createAccessTokenRequest(String oauthVerifier, T request) { - final OAuthConfig config = getConfig(); - request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); - request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); - - if (ImgurApi.isOob(config)) { - request.addBodyParameter(OAuthConstants.GRANT_TYPE, "pin"); - request.addBodyParameter("pin", oauthVerifier); - } else { - request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); - request.addBodyParameter(OAuthConstants.CODE, oauthVerifier); - } - return request; - } - - @Override - public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { - request.addHeader("Authorization", - accessToken == null - ? "Client-ID " + getConfig().getApiKey() : "Bearer " + accessToken.getAccessToken()); - } -} +package com.github.scribejava.apis.service; + +import com.github.scribejava.apis.ImgurApi; +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class ImgurOAuthServiceImpl extends OAuth20Service { + + public ImgurOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { + super(api, config); + } + + @Override + protected T createAccessTokenRequest(String oauthVerifier, T request) { + final OAuthConfig config = getConfig(); + request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); + request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); + + if (ImgurApi.isOob(config)) { + request.addBodyParameter(OAuthConstants.GRANT_TYPE, "pin"); + request.addBodyParameter("pin", oauthVerifier); + } else { + request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); + request.addBodyParameter(OAuthConstants.CODE, oauthVerifier); + } + return request; + } + + @Override + public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { + request.addHeader("Authorization", + accessToken == null + ? "Client-ID " + getConfig().getApiKey() : "Bearer " + accessToken.getAccessToken()); + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OdnoklassnikiServiceImpl.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OdnoklassnikiServiceImpl.java index baca34604..3c78b94e8 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OdnoklassnikiServiceImpl.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OdnoklassnikiServiceImpl.java @@ -1,39 +1,39 @@ -package com.github.scribejava.apis.service; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import org.apache.commons.codec.CharEncoding; -import static org.apache.commons.codec.digest.DigestUtils.md5Hex; -import com.github.scribejava.core.builder.api.DefaultApi20; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class OdnoklassnikiServiceImpl extends OAuth20Service { - - public OdnoklassnikiServiceImpl(DefaultApi20 api, OAuthConfig config) { - super(api, config); - } - - @Override - public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { - // sig = md5( request_params_composed_string+ md5(access_token + application_secret_key) ) - try { - final String tokenDigest = md5Hex(accessToken.getAccessToken() + getConfig().getApiSecret()); - - final String completeUrl = request.getCompleteUrl(); - final int queryIndex = completeUrl.indexOf('?'); - if (queryIndex != -1) { - final String sigSource - = URLDecoder.decode(completeUrl.substring(queryIndex + 1).replace("&", ""), CharEncoding.UTF_8) - + tokenDigest; - request.addQuerystringParameter("sig", md5Hex(sigSource)); - } - - super.signRequest(accessToken, request); - } catch (UnsupportedEncodingException unex) { - throw new IllegalStateException(unex); - } - } -} +package com.github.scribejava.apis.service; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import org.apache.commons.codec.CharEncoding; +import static org.apache.commons.codec.digest.DigestUtils.md5Hex; +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class OdnoklassnikiServiceImpl extends OAuth20Service { + + public OdnoklassnikiServiceImpl(DefaultApi20 api, OAuthConfig config) { + super(api, config); + } + + @Override + public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { + // sig = md5( request_params_composed_string+ md5(access_token + application_secret_key) ) + try { + final String tokenDigest = md5Hex(accessToken.getAccessToken() + getConfig().getApiSecret()); + + final String completeUrl = request.getCompleteUrl(); + final int queryIndex = completeUrl.indexOf('?'); + if (queryIndex != -1) { + final String sigSource + = URLDecoder.decode(completeUrl.substring(queryIndex + 1).replace("&", ""), CharEncoding.UTF_8) + + tokenDigest; + request.addQuerystringParameter("sig", md5Hex(sigSource)); + } + + super.signRequest(accessToken, request); + } catch (UnsupportedEncodingException unex) { + throw new IllegalStateException(unex); + } + } +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OsChinaOAuthServiceImpl.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OsChinaOAuthServiceImpl.java new file mode 100644 index 000000000..0391d1b5f --- /dev/null +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/OsChinaOAuthServiceImpl.java @@ -0,0 +1,26 @@ +package com.github.scribejava.apis.service; + +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class OsChinaOAuthServiceImpl extends OAuth20Service { + + public OsChinaOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { + super(api, config); + } + + @Override + protected T createAccessTokenRequest(String code, T request) { + super.createAccessTokenRequest(code, request); +// if (!getConfig().hasGrantType()) { +// request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); +// } + request.addParameter("dataType", "json"); + return request; + } + + +} diff --git a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/TutByOAuthServiceImpl.java b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/TutByOAuthServiceImpl.java index 21a61d13e..a624d9795 100644 --- a/scribejava-apis/src/main/java/com/github/scribejava/apis/service/TutByOAuthServiceImpl.java +++ b/scribejava-apis/src/main/java/com/github/scribejava/apis/service/TutByOAuthServiceImpl.java @@ -1,20 +1,20 @@ -package com.github.scribejava.apis.service; - -import com.github.scribejava.core.builder.api.DefaultApi20; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class TutByOAuthServiceImpl extends OAuth20Service { - - public TutByOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { - super(api, config); - } - - @Override - public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { - request.addQuerystringParameter(OAuthConstants.TOKEN, accessToken.getAccessToken()); - } -} +package com.github.scribejava.apis.service; + +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class TutByOAuthServiceImpl extends OAuth20Service { + + public TutByOAuthServiceImpl(DefaultApi20 api, OAuthConfig config) { + super(api, config); + } + + @Override + public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { + request.addQuerystringParameter(OAuthConstants.TOKEN, accessToken.getAccessToken()); + } +} diff --git a/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/OsChinaExample.java b/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/OsChinaExample.java new file mode 100644 index 000000000..e46dffb5c --- /dev/null +++ b/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/OsChinaExample.java @@ -0,0 +1,18 @@ +package com.github.scribejava.apis.examples; + +import com.github.scribejava.apis.OschinaApi; +import com.github.scribejava.apis.QQApi; +import com.github.scribejava.apis.SinaWeiboApi20; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class OsChinaExample { + + public static void main(String[] args) { + + final OAuth20Service oschina = new ServiceBuilder().apiKey("CTJlkYcnBaZCsi4GGgUk") + .apiSecret("TlKrmPCKImAKEzk1ORZtdwooJKDIgXrF").callback("http://www.yichisancun.com/oschinalogin.htm") + .responseType("code").build(OschinaApi.instance()); + System.out.println(oschina.getAuthorizationUrl()); + } +} diff --git a/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/QQExample.java b/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/QQExample.java new file mode 100644 index 000000000..9508b995e --- /dev/null +++ b/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/QQExample.java @@ -0,0 +1,20 @@ +package com.github.scribejava.apis.examples; + +import com.github.scribejava.apis.QQApi; +import com.github.scribejava.apis.SinaWeiboApi20; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class QQExample { + + public static void main(String[] args) { + + final String apiKey = "101303927"; + final String apiSecret = "0c3ac6430d6e2f60dfb637101252417e "; + final OAuth20Service service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret) + .callback("http://www.yichisancun.com/qqlogin.htm").state("xxxx") + .scope("get_user_info,list_album,upload_pic,do_like").build(QQApi.instance()); + + System.out.println(service.getAuthorizationUrl()); + } +} diff --git a/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/WeiXinExample.java b/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/WeiXinExample.java new file mode 100644 index 000000000..01a816e00 --- /dev/null +++ b/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/WeiXinExample.java @@ -0,0 +1,18 @@ +package com.github.scribejava.apis.examples; + +import com.github.scribejava.apis.WeiXinApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class WeiXinExample { + + public static void main(String[] args) { + + final String apiKey = "x"; + final String apiSecret = "x "; + final OAuth20Service service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret) + .callback("url").state("xxxx").scope("snsapi_login") + .build(WeiXinApi.instance()); + System.out.println(service.getAuthorizationUrl()); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/async/ahc/OAuthAsyncCompletionHandler.java b/scribejava-core/src/main/java/com/github/scribejava/core/async/ahc/OAuthAsyncCompletionHandler.java index b556fb6ad..2c778ac94 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/async/ahc/OAuthAsyncCompletionHandler.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/async/ahc/OAuthAsyncCompletionHandler.java @@ -1,47 +1,47 @@ -package com.github.scribejava.core.async.ahc; - -import com.github.scribejava.core.model.OAuthAsyncRequestCallback; -import com.github.scribejava.core.model.OAuthRequestAsync; -import com.github.scribejava.core.model.Response; -import io.netty.handler.codec.http.HttpHeaders; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import org.asynchttpclient.AsyncCompletionHandler; - -public class OAuthAsyncCompletionHandler extends AsyncCompletionHandler { - - private final OAuthAsyncRequestCallback callback; - private final OAuthRequestAsync.ResponseConverter converter; - - public OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback callback, - OAuthRequestAsync.ResponseConverter converter) { - this.callback = callback; - this.converter = converter; - } - - @Override - public T onCompleted(org.asynchttpclient.Response ahcResponse) throws IOException { - final HttpHeaders map = ahcResponse.getHeaders(); - final Map headersMap = new HashMap<>(); - for (Map.Entry header : map) { - headersMap.put(header.getKey(), header.getValue()); - } - final Response response = new Response(ahcResponse.getStatusCode(), ahcResponse.getStatusText(), headersMap, - ahcResponse.getResponseBody(), ahcResponse.getResponseBodyAsStream()); - - @SuppressWarnings("unchecked") - final T t = converter == null ? (T) response : converter.convert(response); - if (callback != null) { - callback.onCompleted(t); - } - return t; - } - - @Override - public void onThrowable(Throwable t) { - if (callback != null) { - callback.onThrowable(t); - } - } -}; +package com.github.scribejava.core.async.ahc; + +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.OAuthRequestAsync; +import com.github.scribejava.core.model.Response; +import io.netty.handler.codec.http.HttpHeaders; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.asynchttpclient.AsyncCompletionHandler; + +public class OAuthAsyncCompletionHandler extends AsyncCompletionHandler { + + private final OAuthAsyncRequestCallback callback; + private final OAuthRequestAsync.ResponseConverter converter; + + public OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback callback, + OAuthRequestAsync.ResponseConverter converter) { + this.callback = callback; + this.converter = converter; + } + + @Override + public T onCompleted(org.asynchttpclient.Response ahcResponse) throws IOException { + final HttpHeaders map = ahcResponse.getHeaders(); + final Map headersMap = new HashMap<>(); + for (Map.Entry header : map) { + headersMap.put(header.getKey(), header.getValue()); + } + final Response response = new Response(ahcResponse.getStatusCode(), ahcResponse.getStatusText(), headersMap, + ahcResponse.getResponseBody(), ahcResponse.getResponseBodyAsStream()); + + @SuppressWarnings("unchecked") + final T t = converter == null ? (T) response : converter.convert(response); + if (callback != null) { + callback.onCompleted(t); + } + return t; + } + + @Override + public void onThrowable(Throwable t) { + if (callback != null) { + callback.onThrowable(t); + } + } +}; diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/async/ning/OAuthAsyncCompletionHandler.java b/scribejava-core/src/main/java/com/github/scribejava/core/async/ning/OAuthAsyncCompletionHandler.java index adbcf10bb..20abd802d 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/async/ning/OAuthAsyncCompletionHandler.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/async/ning/OAuthAsyncCompletionHandler.java @@ -1,52 +1,52 @@ -package com.github.scribejava.core.async.ning; - -import com.github.scribejava.core.model.OAuthAsyncRequestCallback; -import com.github.scribejava.core.model.OAuthRequestAsync; -import com.github.scribejava.core.model.Response; -import com.ning.http.client.AsyncCompletionHandler; -import com.ning.http.client.FluentCaseInsensitiveStringsMap; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class OAuthAsyncCompletionHandler extends AsyncCompletionHandler { - - private final OAuthAsyncRequestCallback callback; - private final OAuthRequestAsync.ResponseConverter converter; - - public OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback callback, - OAuthRequestAsync.ResponseConverter converter) { - this.callback = callback; - this.converter = converter; - } - - @Override - public T onCompleted(com.ning.http.client.Response ningResponse) throws IOException { - final FluentCaseInsensitiveStringsMap map = ningResponse.getHeaders(); - final Map headersMap = new HashMap<>(); - for (FluentCaseInsensitiveStringsMap.Entry> header : map) { - final StringBuilder value = new StringBuilder(); - for (String str : header.getValue()) { - value.append(str); - } - headersMap.put(header.getKey(), value.toString()); - } - final Response response = new Response(ningResponse.getStatusCode(), ningResponse.getStatusText(), headersMap, - ningResponse.getResponseBody(), ningResponse.getResponseBodyAsStream()); - - @SuppressWarnings("unchecked") - final T t = converter == null ? (T) response : converter.convert(response); - if (callback != null) { - callback.onCompleted(t); - } - return t; - } - - @Override - public void onThrowable(Throwable t) { - if (callback != null) { - callback.onThrowable(t); - } - } -}; +package com.github.scribejava.core.async.ning; + +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.OAuthRequestAsync; +import com.github.scribejava.core.model.Response; +import com.ning.http.client.AsyncCompletionHandler; +import com.ning.http.client.FluentCaseInsensitiveStringsMap; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OAuthAsyncCompletionHandler extends AsyncCompletionHandler { + + private final OAuthAsyncRequestCallback callback; + private final OAuthRequestAsync.ResponseConverter converter; + + public OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback callback, + OAuthRequestAsync.ResponseConverter converter) { + this.callback = callback; + this.converter = converter; + } + + @Override + public T onCompleted(com.ning.http.client.Response ningResponse) throws IOException { + final FluentCaseInsensitiveStringsMap map = ningResponse.getHeaders(); + final Map headersMap = new HashMap<>(); + for (FluentCaseInsensitiveStringsMap.Entry> header : map) { + final StringBuilder value = new StringBuilder(); + for (String str : header.getValue()) { + value.append(str); + } + headersMap.put(header.getKey(), value.toString()); + } + final Response response = new Response(ningResponse.getStatusCode(), ningResponse.getStatusText(), headersMap, + ningResponse.getResponseBody(), ningResponse.getResponseBodyAsStream()); + + @SuppressWarnings("unchecked") + final T t = converter == null ? (T) response : converter.convert(response); + if (callback != null) { + callback.onCompleted(t); + } + return t; + } + + @Override + public void onThrowable(Throwable t) { + if (callback != null) { + callback.onThrowable(t); + } + } +}; diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java b/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java index 12195ab56..5bd19e3af 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java @@ -1,190 +1,190 @@ -package com.github.scribejava.core.builder; - -import com.github.scribejava.core.builder.api.BaseApi; -import com.github.scribejava.core.model.OAuthConfig; -import java.io.OutputStream; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.SignatureType; -import com.github.scribejava.core.oauth.OAuthService; -import com.github.scribejava.core.utils.Preconditions; - -/** - * Implementation of the Builder pattern, with a fluent interface that creates a {@link OAuthService} - */ -public class ServiceBuilder { - - private String callback; - private String apiKey; - private String apiSecret; - private String scope; - private String state; - private SignatureType signatureType; - private OutputStream debugStream; - private String responseType = "code"; - private String userAgent; - - //sync version only - private Integer connectTimeout; - private Integer readTimeout; - - //async version only - //ning 1.9 - private com.ning.http.client.AsyncHttpClientConfig ningAsyncHttpClientConfig; - private String ningAsyncHttpProviderClassName; - //AHC 2.0 - private org.asynchttpclient.AsyncHttpClientConfig ahcAsyncHttpClientConfig; - - public ServiceBuilder() { - callback = OAuthConstants.OUT_OF_BAND; - signatureType = SignatureType.Header; - } - - /** - * Adds an OAuth callback url - * - * @param callback callback url. Must be a valid url or 'oob' for out of band OAuth - * @return the {@link ServiceBuilder} instance for method chaining - */ - public ServiceBuilder callback(String callback) { - Preconditions.checkNotNull(callback, "Callback can't be null"); - this.callback = callback; - return this; - } - - /** - * Configures the api key - * - * @param apiKey The api key for your application - * @return the {@link ServiceBuilder} instance for method chaining - */ - public ServiceBuilder apiKey(String apiKey) { - Preconditions.checkEmptyString(apiKey, "Invalid Api key"); - this.apiKey = apiKey; - return this; - } - - /** - * Configures the api secret - * - * @param apiSecret The api secret for your application - * @return the {@link ServiceBuilder} instance for method chaining - */ - public ServiceBuilder apiSecret(String apiSecret) { - Preconditions.checkEmptyString(apiSecret, "Invalid Api secret"); - this.apiSecret = apiSecret; - return this; - } - - /** - * Configures the OAuth scope. This is only necessary in some APIs (like Google's). - * - * @param scope The OAuth scope - * @return the {@link ServiceBuilder} instance for method chaining - */ - public ServiceBuilder scope(String scope) { - Preconditions.checkEmptyString(scope, "Invalid OAuth scope"); - this.scope = scope; - return this; - } - - /** - * Configures the anti forgery session state. This is available in some APIs (like Google's). - * - * @param state The OAuth state - * @return the {@link ServiceBuilder} instance for method chaining - */ - public ServiceBuilder state(String state) { - Preconditions.checkEmptyString(state, "Invalid OAuth state"); - this.state = state; - return this; - } - - /** - * Configures the signature type, choose between header, querystring, etc. Defaults to Header - * - * @param signatureType SignatureType - * @return the {@link ServiceBuilder} instance for method chaining - */ - public ServiceBuilder signatureType(SignatureType signatureType) { - Preconditions.checkNotNull(signatureType, "Signature type can't be null"); - this.signatureType = signatureType; - return this; - } - - public ServiceBuilder debugStream(OutputStream debugStream) { - Preconditions.checkNotNull(debugStream, "debug stream can't be null"); - this.debugStream = debugStream; - return this; - } - - public ServiceBuilder responseType(String responseType) { - Preconditions.checkEmptyString(responseType, "Invalid OAuth responseType"); - this.responseType = responseType; - return this; - } - - public ServiceBuilder connectTimeout(Integer connectTimeout) { - Preconditions.checkNotNull(connectTimeout, "Connection timeout can't be null"); - this.connectTimeout = connectTimeout; - return this; - } - - public ServiceBuilder readTimeout(Integer readTimeout) { - Preconditions.checkNotNull(readTimeout, "Read timeout can't be null"); - this.readTimeout = readTimeout; - return this; - } - - public ServiceBuilder asyncNingHttpClientConfig(com.ning.http.client.AsyncHttpClientConfig asyncHttpClientConfig) { - Preconditions.checkNotNull(asyncHttpClientConfig, "asyncHttpClientConfig can't be null"); - ningAsyncHttpClientConfig = asyncHttpClientConfig; - ahcAsyncHttpClientConfig = null; - return this; - } - - public ServiceBuilder asyncNingHttpProviderClassName(String asyncHttpProviderClassName) { - this.ningAsyncHttpProviderClassName = asyncHttpProviderClassName; - ahcAsyncHttpClientConfig = null; - return this; - } - - public ServiceBuilder asyncAHCHttpClientConfig(org.asynchttpclient.AsyncHttpClientConfig asyncHttpClientConfig) { - Preconditions.checkNotNull(asyncHttpClientConfig, "asyncHttpClientConfig can't be null"); - ahcAsyncHttpClientConfig = asyncHttpClientConfig; - ningAsyncHttpClientConfig = null; - ningAsyncHttpProviderClassName = null; - return this; - } - - public ServiceBuilder userAgent(String userAgent) { - this.userAgent = userAgent; - return this; - } - - public ServiceBuilder debug() { - debugStream(System.out); - return this; - } - - public void checkPreconditions() { - Preconditions.checkEmptyString(apiKey, "You must provide an api key"); - } - - private OAuthConfig createConfig() { - checkPreconditions(); - return new OAuthConfig(apiKey, apiSecret, callback, signatureType, scope, debugStream, state, responseType, - userAgent, connectTimeout, readTimeout, ningAsyncHttpClientConfig, ningAsyncHttpProviderClassName, - ahcAsyncHttpClientConfig); - } - - /** - * Returns the fully configured {@link S} - * - * @param OAuthService implementation (OAuth1/OAuth2/any API specific) - * @param api will build Service for this API - * @return fully configured {@link S} - */ - public S build(BaseApi api) { - return api.createService(createConfig()); - } -} +package com.github.scribejava.core.builder; + +import com.github.scribejava.core.builder.api.BaseApi; +import com.github.scribejava.core.model.OAuthConfig; +import java.io.OutputStream; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.SignatureType; +import com.github.scribejava.core.oauth.OAuthService; +import com.github.scribejava.core.utils.Preconditions; + +/** + * Implementation of the Builder pattern, with a fluent interface that creates a {@link OAuthService} + */ +public class ServiceBuilder { + + private String callback; + private String apiKey; + private String apiSecret; + private String scope; + private String state; + private SignatureType signatureType; + private OutputStream debugStream; + private String responseType = "code"; + private String userAgent; + + //sync version only + private Integer connectTimeout; + private Integer readTimeout; + + //async version only + //ning 1.9 + private com.ning.http.client.AsyncHttpClientConfig ningAsyncHttpClientConfig; + private String ningAsyncHttpProviderClassName; + //AHC 2.0 + private org.asynchttpclient.AsyncHttpClientConfig ahcAsyncHttpClientConfig; + + public ServiceBuilder() { + callback = OAuthConstants.OUT_OF_BAND; + signatureType = SignatureType.Header; + } + + /** + * Adds an OAuth callback url + * + * @param callback callback url. Must be a valid url or 'oob' for out of band OAuth + * @return the {@link ServiceBuilder} instance for method chaining + */ + public ServiceBuilder callback(String callback) { + Preconditions.checkNotNull(callback, "Callback can't be null"); + this.callback = callback; + return this; + } + + /** + * Configures the api key + * + * @param apiKey The api key for your application + * @return the {@link ServiceBuilder} instance for method chaining + */ + public ServiceBuilder apiKey(String apiKey) { + Preconditions.checkEmptyString(apiKey, "Invalid Api key"); + this.apiKey = apiKey; + return this; + } + + /** + * Configures the api secret + * + * @param apiSecret The api secret for your application + * @return the {@link ServiceBuilder} instance for method chaining + */ + public ServiceBuilder apiSecret(String apiSecret) { + Preconditions.checkEmptyString(apiSecret, "Invalid Api secret"); + this.apiSecret = apiSecret; + return this; + } + + /** + * Configures the OAuth scope. This is only necessary in some APIs (like Google's). + * + * @param scope The OAuth scope + * @return the {@link ServiceBuilder} instance for method chaining + */ + public ServiceBuilder scope(String scope) { + Preconditions.checkEmptyString(scope, "Invalid OAuth scope"); + this.scope = scope; + return this; + } + + /** + * Configures the anti forgery session state. This is available in some APIs (like Google's). + * + * @param state The OAuth state + * @return the {@link ServiceBuilder} instance for method chaining + */ + public ServiceBuilder state(String state) { + Preconditions.checkEmptyString(state, "Invalid OAuth state"); + this.state = state; + return this; + } + + /** + * Configures the signature type, choose between header, querystring, etc. Defaults to Header + * + * @param signatureType SignatureType + * @return the {@link ServiceBuilder} instance for method chaining + */ + public ServiceBuilder signatureType(SignatureType signatureType) { + Preconditions.checkNotNull(signatureType, "Signature type can't be null"); + this.signatureType = signatureType; + return this; + } + + public ServiceBuilder debugStream(OutputStream debugStream) { + Preconditions.checkNotNull(debugStream, "debug stream can't be null"); + this.debugStream = debugStream; + return this; + } + + public ServiceBuilder responseType(String responseType) { + Preconditions.checkEmptyString(responseType, "Invalid OAuth responseType"); + this.responseType = responseType; + return this; + } + + public ServiceBuilder connectTimeout(Integer connectTimeout) { + Preconditions.checkNotNull(connectTimeout, "Connection timeout can't be null"); + this.connectTimeout = connectTimeout; + return this; + } + + public ServiceBuilder readTimeout(Integer readTimeout) { + Preconditions.checkNotNull(readTimeout, "Read timeout can't be null"); + this.readTimeout = readTimeout; + return this; + } + + public ServiceBuilder asyncNingHttpClientConfig(com.ning.http.client.AsyncHttpClientConfig asyncHttpClientConfig) { + Preconditions.checkNotNull(asyncHttpClientConfig, "asyncHttpClientConfig can't be null"); + ningAsyncHttpClientConfig = asyncHttpClientConfig; + ahcAsyncHttpClientConfig = null; + return this; + } + + public ServiceBuilder asyncNingHttpProviderClassName(String asyncHttpProviderClassName) { + this.ningAsyncHttpProviderClassName = asyncHttpProviderClassName; + ahcAsyncHttpClientConfig = null; + return this; + } + + public ServiceBuilder asyncAHCHttpClientConfig(org.asynchttpclient.AsyncHttpClientConfig asyncHttpClientConfig) { + Preconditions.checkNotNull(asyncHttpClientConfig, "asyncHttpClientConfig can't be null"); + ahcAsyncHttpClientConfig = asyncHttpClientConfig; + ningAsyncHttpClientConfig = null; + ningAsyncHttpProviderClassName = null; + return this; + } + + public ServiceBuilder userAgent(String userAgent) { + this.userAgent = userAgent; + return this; + } + + public ServiceBuilder debug() { + debugStream(System.out); + return this; + } + + public void checkPreconditions() { + Preconditions.checkEmptyString(apiKey, "You must provide an api key"); + } + + private OAuthConfig createConfig() { + checkPreconditions(); + return new OAuthConfig(apiKey, apiSecret, callback, signatureType, scope, debugStream, state, responseType, + userAgent, connectTimeout, readTimeout, ningAsyncHttpClientConfig, ningAsyncHttpProviderClassName, + ahcAsyncHttpClientConfig); + } + + /** + * Returns the fully configured {@link S} + * + * @param OAuthService implementation (OAuth1/OAuth2/any API specific) + * @param api will build Service for this API + * @return fully configured {@link S} + */ + public S build(BaseApi api) { + return api.createService(createConfig()); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/BaseApi.java b/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/BaseApi.java index a42fe35fa..fdfce3d62 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/BaseApi.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/BaseApi.java @@ -1,9 +1,9 @@ -package com.github.scribejava.core.builder.api; - -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.oauth.OAuthService; - -public interface BaseApi { - - T createService(OAuthConfig config); -} +package com.github.scribejava.core.builder.api; + +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.oauth.OAuthService; + +public interface BaseApi { + + T createService(OAuthConfig config); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi10a.java b/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi10a.java index 3b4b148c6..bb2b6bdd9 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi10a.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi10a.java @@ -1,143 +1,143 @@ -package com.github.scribejava.core.builder.api; - -import com.github.scribejava.core.extractors.BaseStringExtractor; -import com.github.scribejava.core.extractors.BaseStringExtractorImpl; -import com.github.scribejava.core.extractors.HeaderExtractor; -import com.github.scribejava.core.extractors.HeaderExtractorImpl; -import com.github.scribejava.core.extractors.OAuth1AccessTokenExtractor; -import com.github.scribejava.core.extractors.OAuth1RequestTokenExtractor; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.Verb; -import com.github.scribejava.core.oauth.OAuth10aService; -import com.github.scribejava.core.services.HMACSha1SignatureService; -import com.github.scribejava.core.services.SignatureService; -import com.github.scribejava.core.services.TimestampService; -import com.github.scribejava.core.services.TimestampServiceImpl; -import com.github.scribejava.core.extractors.TokenExtractor; -import com.github.scribejava.core.model.OAuth1AccessToken; -import com.github.scribejava.core.model.OAuth1RequestToken; - -/** - * Default implementation of the OAuth protocol, version 1.0a - * - * This class is meant to be extended by concrete implementations of the API, providing the endpoints and - * endpoint-http-verbs. - * - * If your Api adheres to the 1.0a protocol correctly, you just need to extend this class and define the getters for - * your endpoints. - * - * If your Api does something a bit different, you can override the different extractors or services, in order to - * fine-tune the process. Please read the javadocs of the interfaces to get an idea of what to do. - * - */ -public abstract class DefaultApi10a implements BaseApi { - - /** - * Returns the access token extractor. - * - * @return access token extractor - */ - public TokenExtractor getAccessTokenExtractor() { - return OAuth1AccessTokenExtractor.instance(); - } - - /** - * Returns the base string extractor. - * - * @return base string extractor - */ - public BaseStringExtractor getBaseStringExtractor() { - return new BaseStringExtractorImpl(); - } - - /** - * Returns the header extractor. - * - * @return header extractor - */ - public HeaderExtractor getHeaderExtractor() { - return new HeaderExtractorImpl(); - } - - /** - * Returns the request token extractor. - * - * @return request token extractor - */ - public TokenExtractor getRequestTokenExtractor() { - return OAuth1RequestTokenExtractor.instance(); - } - - /** - * Returns the signature service. - * - * @return signature service - */ - public SignatureService getSignatureService() { - return new HMACSha1SignatureService(); - } - - /** - * Returns the timestamp service. - * - * @return timestamp service - */ - public TimestampService getTimestampService() { - return new TimestampServiceImpl(); - } - - /** - * Returns the verb for the access token endpoint (defaults to POST) - * - * @return access token endpoint verb - */ - public Verb getAccessTokenVerb() { - return Verb.POST; - } - - /** - * Returns the verb for the request token endpoint (defaults to POST) - * - * @return request token endpoint verb - */ - public Verb getRequestTokenVerb() { - return Verb.POST; - } - - /** - * Returns the URL that receives the request token requests. - * - * @return request token URL - */ - public abstract String getRequestTokenEndpoint(); - - /** - * Returns the URL that receives the access token requests. - * - * @return access token URL - */ - public abstract String getAccessTokenEndpoint(); - - /** - * Returns the URL where you should redirect your users to authenticate your application. - * - * @param requestToken the request token you need to authorize - * @return the URL where you should redirect your users - */ - public abstract String getAuthorizationUrl(OAuth1RequestToken requestToken); - - @Override - public OAuth10aService createService(OAuthConfig config) { - return new OAuth10aService(this, config); - } - - /** - * http://tools.ietf.org/html/rfc5849 says that "The client MAY omit the empty "oauth_token" protocol parameter from - * the request", but not all oauth servers are good boys. - * - * @return whether to inlcude empty oauth_token param to the request - */ - public boolean isEmptyOAuthTokenParamIsRequired() { - return false; - } -} +package com.github.scribejava.core.builder.api; + +import com.github.scribejava.core.extractors.BaseStringExtractor; +import com.github.scribejava.core.extractors.BaseStringExtractorImpl; +import com.github.scribejava.core.extractors.HeaderExtractor; +import com.github.scribejava.core.extractors.HeaderExtractorImpl; +import com.github.scribejava.core.extractors.OAuth1AccessTokenExtractor; +import com.github.scribejava.core.extractors.OAuth1RequestTokenExtractor; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth10aService; +import com.github.scribejava.core.services.HMACSha1SignatureService; +import com.github.scribejava.core.services.SignatureService; +import com.github.scribejava.core.services.TimestampService; +import com.github.scribejava.core.services.TimestampServiceImpl; +import com.github.scribejava.core.extractors.TokenExtractor; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuth1RequestToken; + +/** + * Default implementation of the OAuth protocol, version 1.0a + * + * This class is meant to be extended by concrete implementations of the API, providing the endpoints and + * endpoint-http-verbs. + * + * If your Api adheres to the 1.0a protocol correctly, you just need to extend this class and define the getters for + * your endpoints. + * + * If your Api does something a bit different, you can override the different extractors or services, in order to + * fine-tune the process. Please read the javadocs of the interfaces to get an idea of what to do. + * + */ +public abstract class DefaultApi10a implements BaseApi { + + /** + * Returns the access token extractor. + * + * @return access token extractor + */ + public TokenExtractor getAccessTokenExtractor() { + return OAuth1AccessTokenExtractor.instance(); + } + + /** + * Returns the base string extractor. + * + * @return base string extractor + */ + public BaseStringExtractor getBaseStringExtractor() { + return new BaseStringExtractorImpl(); + } + + /** + * Returns the header extractor. + * + * @return header extractor + */ + public HeaderExtractor getHeaderExtractor() { + return new HeaderExtractorImpl(); + } + + /** + * Returns the request token extractor. + * + * @return request token extractor + */ + public TokenExtractor getRequestTokenExtractor() { + return OAuth1RequestTokenExtractor.instance(); + } + + /** + * Returns the signature service. + * + * @return signature service + */ + public SignatureService getSignatureService() { + return new HMACSha1SignatureService(); + } + + /** + * Returns the timestamp service. + * + * @return timestamp service + */ + public TimestampService getTimestampService() { + return new TimestampServiceImpl(); + } + + /** + * Returns the verb for the access token endpoint (defaults to POST) + * + * @return access token endpoint verb + */ + public Verb getAccessTokenVerb() { + return Verb.POST; + } + + /** + * Returns the verb for the request token endpoint (defaults to POST) + * + * @return request token endpoint verb + */ + public Verb getRequestTokenVerb() { + return Verb.POST; + } + + /** + * Returns the URL that receives the request token requests. + * + * @return request token URL + */ + public abstract String getRequestTokenEndpoint(); + + /** + * Returns the URL that receives the access token requests. + * + * @return access token URL + */ + public abstract String getAccessTokenEndpoint(); + + /** + * Returns the URL where you should redirect your users to authenticate your application. + * + * @param requestToken the request token you need to authorize + * @return the URL where you should redirect your users + */ + public abstract String getAuthorizationUrl(OAuth1RequestToken requestToken); + + @Override + public OAuth10aService createService(OAuthConfig config) { + return new OAuth10aService(this, config); + } + + /** + * http://tools.ietf.org/html/rfc5849 says that "The client MAY omit the empty "oauth_token" protocol parameter from + * the request", but not all oauth servers are good boys. + * + * @return whether to inlcude empty oauth_token param to the request + */ + public boolean isEmptyOAuthTokenParamIsRequired() { + return false; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi20.java b/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi20.java index 480a7a34d..9f10b4350 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi20.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/builder/api/DefaultApi20.java @@ -1,93 +1,93 @@ -package com.github.scribejava.core.builder.api; - -import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor; -import com.github.scribejava.core.extractors.TokenExtractor; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.ParameterList; -import com.github.scribejava.core.model.Verb; -import com.github.scribejava.core.oauth.OAuth20Service; -import java.util.Map; - -/** - * Default implementation of the OAuth protocol, version 2.0 - * - * This class is meant to be extended by concrete implementations of the API, providing the endpoints and - * endpoint-http-verbs. - * - * If your API adheres to the 2.0 protocol correctly, you just need to extend this class and define the getters for your - * endpoints. - * - * If your API does something a bit different, you can override the different extractors or services, in order to - * fine-tune the process. Please read the javadocs of the interfaces to get an idea of what to do. - * - */ -public abstract class DefaultApi20 implements BaseApi { - - /** - * Returns the access token extractor. - * - * @return access token extractor - */ - public TokenExtractor getAccessTokenExtractor() { - return OAuth2AccessTokenJsonExtractor.instance(); - } - - /** - * Returns the verb for the access token endpoint (defaults to POST) - * - * @return access token endpoint verb - */ - public Verb getAccessTokenVerb() { - return Verb.POST; - } - - /** - * Returns the URL that receives the access token requests. - * - * @return access token URL - */ - public abstract String getAccessTokenEndpoint(); - - public String getRefreshTokenEndpoint() { - return getAccessTokenEndpoint(); - } - - protected abstract String getAuthorizationBaseUrl(); - - /** - * Returns the URL where you should redirect your users to authenticate your application. - * - * @param config OAuth 2.0 configuration param object - * @param additionalParams any additional GET params to add to the URL - * @return the URL where you should redirect your users - */ - public String getAuthorizationUrl(OAuthConfig config, Map additionalParams) { - final ParameterList parameters = new ParameterList(additionalParams); - parameters.add(OAuthConstants.RESPONSE_TYPE, config.getResponseType()); - parameters.add(OAuthConstants.CLIENT_ID, config.getApiKey()); - - final String callback = config.getCallback(); - if (callback != null) { - parameters.add(OAuthConstants.REDIRECT_URI, callback); - } - - final String scope = config.getScope(); - if (scope != null) { - parameters.add(OAuthConstants.SCOPE, scope); - } - - final String state = config.getState(); - if (state != null) { - parameters.add(OAuthConstants.STATE, state); - } - - return parameters.appendTo(getAuthorizationBaseUrl()); - } - - @Override - public OAuth20Service createService(OAuthConfig config) { - return new OAuth20Service(this, config); - } -} +package com.github.scribejava.core.builder.api; + +import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor; +import com.github.scribejava.core.extractors.TokenExtractor; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.ParameterList; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; +import java.util.Map; + +/** + * Default implementation of the OAuth protocol, version 2.0 + * + * This class is meant to be extended by concrete implementations of the API, providing the endpoints and + * endpoint-http-verbs. + * + * If your API adheres to the 2.0 protocol correctly, you just need to extend this class and define the getters for your + * endpoints. + * + * If your API does something a bit different, you can override the different extractors or services, in order to + * fine-tune the process. Please read the javadocs of the interfaces to get an idea of what to do. + * + */ +public abstract class DefaultApi20 implements BaseApi { + + /** + * Returns the access token extractor. + * + * @return access token extractor + */ + public TokenExtractor getAccessTokenExtractor() { + return OAuth2AccessTokenJsonExtractor.instance(); + } + + /** + * Returns the verb for the access token endpoint (defaults to POST) + * + * @return access token endpoint verb + */ + public Verb getAccessTokenVerb() { + return Verb.POST; + } + + /** + * Returns the URL that receives the access token requests. + * + * @return access token URL + */ + public abstract String getAccessTokenEndpoint(); + + public String getRefreshTokenEndpoint() { + return getAccessTokenEndpoint(); + } + + protected abstract String getAuthorizationBaseUrl(); + + /** + * Returns the URL where you should redirect your users to authenticate your application. + * + * @param config OAuth 2.0 configuration param object + * @param additionalParams any additional GET params to add to the URL + * @return the URL where you should redirect your users + */ + public String getAuthorizationUrl(OAuthConfig config, Map additionalParams) { + final ParameterList parameters = new ParameterList(additionalParams); + parameters.add(OAuthConstants.RESPONSE_TYPE, config.getResponseType()); + parameters.add(OAuthConstants.CLIENT_ID, config.getApiKey()); + + final String callback = config.getCallback(); + if (callback != null) { + parameters.add(OAuthConstants.REDIRECT_URI, callback); + } + + final String scope = config.getScope(); + if (scope != null) { + parameters.add(OAuthConstants.SCOPE, scope); + } + + final String state = config.getState(); + if (state != null) { + parameters.add(OAuthConstants.STATE, state); + } + + return parameters.appendTo(getAuthorizationBaseUrl()); + } + + @Override + public OAuth20Service createService(OAuthConfig config) { + return new OAuth20Service(this, config); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthConnectionException.java b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthConnectionException.java index 93feb8c42..9b2717e7d 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthConnectionException.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthConnectionException.java @@ -1,11 +1,11 @@ -package com.github.scribejava.core.exceptions; - -public class OAuthConnectionException extends OAuthException { - - private static final long serialVersionUID = 6901269342236961310L; - private static final String MSG = "There was a problem while creating a connection to the remote service: "; - - public OAuthConnectionException(String url, Exception e) { - super(MSG + url, e); - } -} +package com.github.scribejava.core.exceptions; + +public class OAuthConnectionException extends OAuthException { + + private static final long serialVersionUID = 6901269342236961310L; + private static final String MSG = "There was a problem while creating a connection to the remote service: "; + + public OAuthConnectionException(String url, Exception e) { + super(MSG + url, e); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthException.java b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthException.java index 1680b2a44..d0d24269d 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthException.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthException.java @@ -1,38 +1,38 @@ -package com.github.scribejava.core.exceptions; - -/** - * Default ScribeJava exception. Represents a problem in the OAuth signing - * process - */ -public class OAuthException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Default constructor - * - * @param message message explaining what went wrong - * @param e original exception - */ - public OAuthException(String message, Exception e) { - super(message, e); - } - - /** - * No-exception constructor. Used when there is no original exception - * - * @param message message explaining what went wrong - */ - public OAuthException(String message) { - super(message, null); - } - - /** - * Exception constructor. Used to simply wrap an exception. - * - * @param e original exception - */ - public OAuthException(Exception e) { - super(e); - } -} +package com.github.scribejava.core.exceptions; + +/** + * Default ScribeJava exception. Represents a problem in the OAuth signing + * process + */ +public class OAuthException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Default constructor + * + * @param message message explaining what went wrong + * @param e original exception + */ + public OAuthException(String message, Exception e) { + super(message, e); + } + + /** + * No-exception constructor. Used when there is no original exception + * + * @param message message explaining what went wrong + */ + public OAuthException(String message) { + super(message, null); + } + + /** + * Exception constructor. Used to simply wrap an exception. + * + * @param e original exception + */ + public OAuthException(Exception e) { + super(e); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthParametersMissingException.java b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthParametersMissingException.java index ddf77ab78..003ac0c80 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthParametersMissingException.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthParametersMissingException.java @@ -1,22 +1,22 @@ -package com.github.scribejava.core.exceptions; - -import com.github.scribejava.core.model.AbstractRequest; - -/** - * Specialized exception that represents a missing OAuth parameter. - */ -public class OAuthParametersMissingException extends OAuthException { - - private static final long serialVersionUID = 1745308760111976671L; - private static final String MSG = "Could not find oauth parameters in request: %s. " - + "OAuth parameters must be specified with the addOAuthParameter() method"; - - /** - * Default constructor. - * - * @param request OAuthRequest that caused the error - */ - public OAuthParametersMissingException(AbstractRequest request) { - super(String.format(MSG, request)); - } -} +package com.github.scribejava.core.exceptions; + +import com.github.scribejava.core.model.AbstractRequest; + +/** + * Specialized exception that represents a missing OAuth parameter. + */ +public class OAuthParametersMissingException extends OAuthException { + + private static final long serialVersionUID = 1745308760111976671L; + private static final String MSG = "Could not find oauth parameters in request: %s. " + + "OAuth parameters must be specified with the addOAuthParameter() method"; + + /** + * Default constructor. + * + * @param request OAuthRequest that caused the error + */ + public OAuthParametersMissingException(AbstractRequest request) { + super(String.format(MSG, request)); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthSignatureException.java b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthSignatureException.java index 53bffbb7c..673888363 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthSignatureException.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/exceptions/OAuthSignatureException.java @@ -1,21 +1,21 @@ -package com.github.scribejava.core.exceptions; - -/** - * Specialized exception that represents a problem in the signature - */ -public class OAuthSignatureException extends OAuthException { - - private static final long serialVersionUID = 1L; - private static final String MSG = "Error while signing string: %s"; - - /** - * Default constructor - * - * @param stringToSign plain string that gets signed (HMAC-SHA, etc) - * @param e original exception - */ - public OAuthSignatureException(String stringToSign, Exception e) { - super(String.format(MSG, stringToSign), e); - } - -} +package com.github.scribejava.core.exceptions; + +/** + * Specialized exception that represents a problem in the signature + */ +public class OAuthSignatureException extends OAuthException { + + private static final long serialVersionUID = 1L; + private static final String MSG = "Error while signing string: %s"; + + /** + * Default constructor + * + * @param stringToSign plain string that gets signed (HMAC-SHA, etc) + * @param e original exception + */ + public OAuthSignatureException(String stringToSign, Exception e) { + super(String.format(MSG, stringToSign), e); + } + +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/AbstractOAuth1TokenExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/AbstractOAuth1TokenExtractor.java index 4d968d83c..47b5e62fc 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/AbstractOAuth1TokenExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/AbstractOAuth1TokenExtractor.java @@ -1,45 +1,45 @@ -package com.github.scribejava.core.extractors; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.model.OAuth1Token; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -/** - * Abstract base implementation of {@link TokenExtractor} for OAuth 1.0a - * - * The process for extracting access and request tokens is similar so this class can do both things. - * - * @param concrete type of OAuth1Token. access or request - */ -public abstract class AbstractOAuth1TokenExtractor implements TokenExtractor { - - private static final String OAUTH_TOKEN_REGEXP = "oauth_token=([^&]+)"; - private static final String OAUTH_TOKEN_SECRET_REGEXP = "oauth_token_secret=([^&]*)"; - - /** - * {@inheritDoc} - */ - @Override - public T extract(String response) { - Preconditions.checkEmptyString(response, - "Response body is incorrect. Can't extract a token from an empty string"); - final String token = extract(response, Pattern.compile(OAUTH_TOKEN_REGEXP)); - final String secret = extract(response, Pattern.compile(OAUTH_TOKEN_SECRET_REGEXP)); - return createToken(token, secret, response); - } - - private String extract(String response, Pattern p) { - final Matcher matcher = p.matcher(response); - if (matcher.find() && matcher.groupCount() >= 1) { - return OAuthEncoder.decode(matcher.group(1)); - } else { - throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '" - + response + "'", null); - } - } - - protected abstract T createToken(String token, String secret, String response); -} +package com.github.scribejava.core.extractors; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.model.OAuth1Token; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +/** + * Abstract base implementation of {@link TokenExtractor} for OAuth 1.0a + * + * The process for extracting access and request tokens is similar so this class can do both things. + * + * @param concrete type of OAuth1Token. access or request + */ +public abstract class AbstractOAuth1TokenExtractor implements TokenExtractor { + + private static final String OAUTH_TOKEN_REGEXP = "oauth_token=([^&]+)"; + private static final String OAUTH_TOKEN_SECRET_REGEXP = "oauth_token_secret=([^&]*)"; + + /** + * {@inheritDoc} + */ + @Override + public T extract(String response) { + Preconditions.checkEmptyString(response, + "Response body is incorrect. Can't extract a token from an empty string"); + final String token = extract(response, Pattern.compile(OAUTH_TOKEN_REGEXP)); + final String secret = extract(response, Pattern.compile(OAUTH_TOKEN_SECRET_REGEXP)); + return createToken(token, secret, response); + } + + private String extract(String response, Pattern p) { + final Matcher matcher = p.matcher(response); + if (matcher.find() && matcher.groupCount() >= 1) { + return OAuthEncoder.decode(matcher.group(1)); + } else { + throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '" + + response + "'", null); + } + } + + protected abstract T createToken(String token, String secret, String response); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractor.java index 113dc3515..156ffa0cf 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractor.java @@ -1,19 +1,19 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.model.AbstractRequest; - -/** - * Simple command object that extracts a base string from a {@link AbstractRequest} - */ -public interface BaseStringExtractor { - - /** - * Extracts an url-encoded base string from the {@link AbstractRequest}. - * - * See the oauth spec for more info on this. - * - * @param request the OAuthRequest - * @return the url-encoded base string - */ - String extract(AbstractRequest request); -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.model.AbstractRequest; + +/** + * Simple command object that extracts a base string from a {@link AbstractRequest} + */ +public interface BaseStringExtractor { + + /** + * Extracts an url-encoded base string from the {@link AbstractRequest}. + * + * See the oauth spec for more info on this. + * + * @param request the OAuthRequest + * @return the url-encoded base string + */ + String extract(AbstractRequest request); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractorImpl.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractorImpl.java index e2ba3b950..4712d1bcc 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractorImpl.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/BaseStringExtractorImpl.java @@ -1,51 +1,51 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.exceptions.OAuthParametersMissingException; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.ParameterList; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -/** - * Default implementation of {@link BaseStringExtractor}. Conforms to OAuth 1.0a - */ -public class BaseStringExtractorImpl implements BaseStringExtractor { - - protected static final String AMPERSAND_SEPARATED_STRING = "%s&%s&%s"; - - /** - * {@inheritDoc} - */ - @Override - public String extract(AbstractRequest request) { - checkPreconditions(request); - final String verb = OAuthEncoder.encode(getVerb(request)); - final String url = OAuthEncoder.encode(getUrl(request)); - final String params = getSortedAndEncodedParams(request); - return String.format(AMPERSAND_SEPARATED_STRING, verb, url, params); - } - - protected String getVerb(AbstractRequest request) { - return request.getVerb().name(); - } - - protected String getUrl(AbstractRequest request) { - return request.getSanitizedUrl(); - } - - protected String getSortedAndEncodedParams(AbstractRequest request) { - final ParameterList params = new ParameterList(); - params.addAll(request.getQueryStringParams()); - params.addAll(request.getBodyParams()); - params.addAll(new ParameterList(request.getOauthParameters())); - return params.sort().asOauthBaseString(); - } - - protected void checkPreconditions(AbstractRequest request) { - Preconditions.checkNotNull(request, "Cannot extract base string from a null object"); - - if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0) { - throw new OAuthParametersMissingException(request); - } - } -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.exceptions.OAuthParametersMissingException; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.ParameterList; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +/** + * Default implementation of {@link BaseStringExtractor}. Conforms to OAuth 1.0a + */ +public class BaseStringExtractorImpl implements BaseStringExtractor { + + protected static final String AMPERSAND_SEPARATED_STRING = "%s&%s&%s"; + + /** + * {@inheritDoc} + */ + @Override + public String extract(AbstractRequest request) { + checkPreconditions(request); + final String verb = OAuthEncoder.encode(getVerb(request)); + final String url = OAuthEncoder.encode(getUrl(request)); + final String params = getSortedAndEncodedParams(request); + return String.format(AMPERSAND_SEPARATED_STRING, verb, url, params); + } + + protected String getVerb(AbstractRequest request) { + return request.getVerb().name(); + } + + protected String getUrl(AbstractRequest request) { + return request.getSanitizedUrl(); + } + + protected String getSortedAndEncodedParams(AbstractRequest request) { + final ParameterList params = new ParameterList(); + params.addAll(request.getQueryStringParams()); + params.addAll(request.getBodyParams()); + params.addAll(new ParameterList(request.getOauthParameters())); + return params.sort().asOauthBaseString(); + } + + protected void checkPreconditions(AbstractRequest request) { + Preconditions.checkNotNull(request, "Cannot extract base string from a null object"); + + if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0) { + throw new OAuthParametersMissingException(request); + } + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractor.java index d84390a91..d9913e2a2 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractor.java @@ -1,17 +1,17 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.model.AbstractRequest; - -/** - * Simple command object that generates an OAuth Authorization header to include in the request. - */ -public interface HeaderExtractor { - - /** - * Generates an OAuth 'Authorization' Http header to include in requests as the signature. - * - * @param request the AbstractRequest to inspect and generate the header - * @return the Http header value - */ - String extract(AbstractRequest request); -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.model.AbstractRequest; + +/** + * Simple command object that generates an OAuth Authorization header to include in the request. + */ +public interface HeaderExtractor { + + /** + * Generates an OAuth 'Authorization' Http header to include in requests as the signature. + * + * @param request the AbstractRequest to inspect and generate the header + * @return the Http header value + */ + String extract(AbstractRequest request); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractorImpl.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractorImpl.java index a3c142a10..568ac8bbd 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractorImpl.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/HeaderExtractorImpl.java @@ -1,51 +1,51 @@ -package com.github.scribejava.core.extractors; - -import java.util.Map; -import com.github.scribejava.core.exceptions.OAuthParametersMissingException; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -/** - * Default implementation of {@link HeaderExtractor}. Conforms to OAuth 1.0a - */ -public class HeaderExtractorImpl implements HeaderExtractor { - - public static final int ESTIMATED_PARAM_LENGTH = 20; - private static final String PARAM_SEPARATOR = ", "; - private static final String PREAMBLE = "OAuth "; - - /** - * {@inheritDoc} - */ - @Override - public String extract(AbstractRequest request) { - checkPreconditions(request); - final Map parameters = request.getOauthParameters(); - final StringBuilder header = new StringBuilder(parameters.size() * ESTIMATED_PARAM_LENGTH); - header.append(PREAMBLE); - for (Map.Entry entry : parameters.entrySet()) { - if (header.length() > PREAMBLE.length()) { - header.append(PARAM_SEPARATOR); - } - header.append(String.format("%s=\"%s\"", entry.getKey(), OAuthEncoder.encode(entry.getValue()))); - } - - if (request.getRealm() != null && !request.getRealm().isEmpty()) { - header.append(PARAM_SEPARATOR); - header.append(String.format("%s=\"%s\"", OAuthConstants.REALM, request.getRealm())); - } - - return header.toString(); - } - - private void checkPreconditions(AbstractRequest request) { - Preconditions.checkNotNull(request, "Cannot extract a header from a null object"); - - if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0) { - throw new OAuthParametersMissingException(request); - } - } - -} +package com.github.scribejava.core.extractors; + +import java.util.Map; +import com.github.scribejava.core.exceptions.OAuthParametersMissingException; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +/** + * Default implementation of {@link HeaderExtractor}. Conforms to OAuth 1.0a + */ +public class HeaderExtractorImpl implements HeaderExtractor { + + public static final int ESTIMATED_PARAM_LENGTH = 20; + private static final String PARAM_SEPARATOR = ", "; + private static final String PREAMBLE = "OAuth "; + + /** + * {@inheritDoc} + */ + @Override + public String extract(AbstractRequest request) { + checkPreconditions(request); + final Map parameters = request.getOauthParameters(); + final StringBuilder header = new StringBuilder(parameters.size() * ESTIMATED_PARAM_LENGTH); + header.append(PREAMBLE); + for (Map.Entry entry : parameters.entrySet()) { + if (header.length() > PREAMBLE.length()) { + header.append(PARAM_SEPARATOR); + } + header.append(String.format("%s=\"%s\"", entry.getKey(), OAuthEncoder.encode(entry.getValue()))); + } + + if (request.getRealm() != null && !request.getRealm().isEmpty()) { + header.append(PARAM_SEPARATOR); + header.append(String.format("%s=\"%s\"", OAuthConstants.REALM, request.getRealm())); + } + + return header.toString(); + } + + private void checkPreconditions(AbstractRequest request) { + Preconditions.checkNotNull(request, "Cannot extract a header from a null object"); + + if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0) { + throw new OAuthParametersMissingException(request); + } + } + +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractor.java index 33c9c2e35..9fafa9425 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractor.java @@ -1,24 +1,24 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.model.OAuth1AccessToken; - -public class OAuth1AccessTokenExtractor extends AbstractOAuth1TokenExtractor { - - protected OAuth1AccessTokenExtractor() { - } - - private static class InstanceHolder { - - private static final OAuth1AccessTokenExtractor INSTANCE = new OAuth1AccessTokenExtractor(); - } - - public static OAuth1AccessTokenExtractor instance() { - return InstanceHolder.INSTANCE; - } - - @Override - protected OAuth1AccessToken createToken(String token, String secret, String response) { - return new OAuth1AccessToken(token, secret, response); - } - -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.model.OAuth1AccessToken; + +public class OAuth1AccessTokenExtractor extends AbstractOAuth1TokenExtractor { + + protected OAuth1AccessTokenExtractor() { + } + + private static class InstanceHolder { + + private static final OAuth1AccessTokenExtractor INSTANCE = new OAuth1AccessTokenExtractor(); + } + + public static OAuth1AccessTokenExtractor instance() { + return InstanceHolder.INSTANCE; + } + + @Override + protected OAuth1AccessToken createToken(String token, String secret, String response) { + return new OAuth1AccessToken(token, secret, response); + } + +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1RequestTokenExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1RequestTokenExtractor.java index 516612713..7a72e44af 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1RequestTokenExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth1RequestTokenExtractor.java @@ -1,23 +1,23 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.model.OAuth1RequestToken; - -public class OAuth1RequestTokenExtractor extends AbstractOAuth1TokenExtractor { - - protected OAuth1RequestTokenExtractor() { - } - - private static class InstanceHolder { - - private static final OAuth1RequestTokenExtractor INSTANCE = new OAuth1RequestTokenExtractor(); - } - - public static OAuth1RequestTokenExtractor instance() { - return InstanceHolder.INSTANCE; - } - - @Override - protected OAuth1RequestToken createToken(String token, String secret, String response) { - return new OAuth1RequestToken(token, secret, response); - } -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.model.OAuth1RequestToken; + +public class OAuth1RequestTokenExtractor extends AbstractOAuth1TokenExtractor { + + protected OAuth1RequestTokenExtractor() { + } + + private static class InstanceHolder { + + private static final OAuth1RequestTokenExtractor INSTANCE = new OAuth1RequestTokenExtractor(); + } + + public static OAuth1RequestTokenExtractor instance() { + return InstanceHolder.INSTANCE; + } + + @Override + protected OAuth1RequestToken createToken(String token, String secret, String response) { + return new OAuth1RequestToken(token, secret, response); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractor.java index 251226338..792d44658 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractor.java @@ -1,67 +1,67 @@ -package com.github.scribejava.core.extractors; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -/** - * Custom implementation of {@link TokenExtractor} for OAuth 2.0 - */ -public class OAuth2AccessTokenExtractor implements TokenExtractor { - - private static final String ACCESS_TOKEN_REGEX = "access_token=([^&]+)"; - private static final String TOKEN_TYPE_REGEX = "token_type=([^&]+)"; - private static final String EXPIRES_IN_REGEX = "expires_in=([^&]+)"; - private static final String REFRESH_TOKEN_REGEX = "refresh_token=([^&]+)"; - private static final String SCOPE_REGEX = "scope=([^&]+)"; - - protected OAuth2AccessTokenExtractor() { - } - - private static class InstanceHolder { - - private static final OAuth2AccessTokenExtractor INSTANCE = new OAuth2AccessTokenExtractor(); - } - - public static OAuth2AccessTokenExtractor instance() { - return InstanceHolder.INSTANCE; - } - - /** - * {@inheritDoc} - */ - @Override - public OAuth2AccessToken extract(String response) { - Preconditions.checkEmptyString(response, - "Response body is incorrect. Can't extract a token from an empty string"); - - final String accessToken = extractParameter(response, ACCESS_TOKEN_REGEX, true); - final String tokenType = extractParameter(response, TOKEN_TYPE_REGEX, false); - final String expiresInString = extractParameter(response, EXPIRES_IN_REGEX, false); - Integer expiresIn; - try { - expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString); - } catch (NumberFormatException nfe) { - expiresIn = null; - } - final String refreshToken = extractParameter(response, REFRESH_TOKEN_REGEX, false); - final String scope = extractParameter(response, SCOPE_REGEX, false); - - return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); - } - - private static String extractParameter(String response, String regex, boolean required) throws OAuthException { - final Matcher matcher = Pattern.compile(regex).matcher(response); - if (matcher.find()) { - return OAuthEncoder.decode(matcher.group(1)); - } else if (required) { - throw new OAuthException("Response body is incorrect. Can't extract a '" + regex - + "' from this: '" + response + "'", null); - } else { - return null; - } - } -} +package com.github.scribejava.core.extractors; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +/** + * Custom implementation of {@link TokenExtractor} for OAuth 2.0 + */ +public class OAuth2AccessTokenExtractor implements TokenExtractor { + + private static final String ACCESS_TOKEN_REGEX = "access_token=([^&]+)"; + private static final String TOKEN_TYPE_REGEX = "token_type=([^&]+)"; + private static final String EXPIRES_IN_REGEX = "expires_in=([^&]+)"; + private static final String REFRESH_TOKEN_REGEX = "refresh_token=([^&]+)"; + private static final String SCOPE_REGEX = "scope=([^&]+)"; + + protected OAuth2AccessTokenExtractor() { + } + + private static class InstanceHolder { + + private static final OAuth2AccessTokenExtractor INSTANCE = new OAuth2AccessTokenExtractor(); + } + + public static OAuth2AccessTokenExtractor instance() { + return InstanceHolder.INSTANCE; + } + + /** + * {@inheritDoc} + */ + @Override + public OAuth2AccessToken extract(String response) { + Preconditions.checkEmptyString(response, + "Response body is incorrect. Can't extract a token from an empty string"); + + final String accessToken = extractParameter(response, ACCESS_TOKEN_REGEX, true); + final String tokenType = extractParameter(response, TOKEN_TYPE_REGEX, false); + final String expiresInString = extractParameter(response, EXPIRES_IN_REGEX, false); + Integer expiresIn; + try { + expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString); + } catch (NumberFormatException nfe) { + expiresIn = null; + } + final String refreshToken = extractParameter(response, REFRESH_TOKEN_REGEX, false); + final String scope = extractParameter(response, SCOPE_REGEX, false); + + return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); + } + + private static String extractParameter(String response, String regex, boolean required) throws OAuthException { + final Matcher matcher = Pattern.compile(regex).matcher(response); + if (matcher.find()) { + return OAuthEncoder.decode(matcher.group(1)); + } else if (required) { + throw new OAuthException("Response body is incorrect. Can't extract a '" + regex + + "' from this: '" + response + "'", null); + } else { + return null; + } + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractor.java index f6250f9b2..05394e868 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractor.java @@ -1,70 +1,70 @@ -package com.github.scribejava.core.extractors; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.utils.Preconditions; - -/** - * JSON (default) implementation of {@link TokenExtractor} for OAuth 2.0 - */ -public class OAuth2AccessTokenJsonExtractor implements TokenExtractor { - - private static final String ACCESS_TOKEN_REGEX = "\"access_token\"\\s*:\\s*\"(\\S*?)\""; - private static final String TOKEN_TYPE_REGEX = "\"token_type\"\\s*:\\s*\"(\\S*?)\""; - private static final String EXPIRES_IN_REGEX = "\"expires_in\"\\s*:\\s*\"?(\\d*?)\"?\\D"; - private static final String REFRESH_TOKEN_REGEX = "\"refresh_token\"\\s*:\\s*\"(\\S*?)\""; - private static final String SCOPE_REGEX = "\"scope\"\\s*:\\s*\"(\\S*?)\""; - - protected OAuth2AccessTokenJsonExtractor() { - } - - private static class InstanceHolder { - - private static final OAuth2AccessTokenJsonExtractor INSTANCE = new OAuth2AccessTokenJsonExtractor(); - } - - public static OAuth2AccessTokenJsonExtractor instance() { - return InstanceHolder.INSTANCE; - } - - @Override - public OAuth2AccessToken extract(String response) { - Preconditions.checkEmptyString(response, - "Response body is incorrect. Can't extract a token from an empty string"); - - final String accessToken = extractParameter(response, ACCESS_TOKEN_REGEX, true); - final String tokenType = extractParameter(response, TOKEN_TYPE_REGEX, false); - final String expiresInString = extractParameter(response, EXPIRES_IN_REGEX, false); - Integer expiresIn; - try { - expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString); - } catch (NumberFormatException nfe) { - expiresIn = null; - } - final String refreshToken = extractParameter(response, REFRESH_TOKEN_REGEX, false); - final String scope = extractParameter(response, SCOPE_REGEX, false); - - return createToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); - } - - protected OAuth2AccessToken createToken(String accessToken, String tokenType, Integer expiresIn, - String refreshToken, String scope, String response) { - return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); - } - - protected static String extractParameter(String response, String regex, boolean required) throws OAuthException { - final Matcher matcher = Pattern.compile(regex).matcher(response); - if (matcher.find()) { - return matcher.group(1); - } - - if (required) { - throw new OAuthException("Response body is incorrect. Can't extract a '" + regex - + "' from this: '" + response + "'", null); - } - - return null; - } -} +package com.github.scribejava.core.extractors; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.utils.Preconditions; + +/** + * JSON (default) implementation of {@link TokenExtractor} for OAuth 2.0 + */ +public class OAuth2AccessTokenJsonExtractor implements TokenExtractor { + + private static final String ACCESS_TOKEN_REGEX = "\"access_token\"\\s*:\\s*\"(\\S*?)\""; + private static final String TOKEN_TYPE_REGEX = "\"token_type\"\\s*:\\s*\"(\\S*?)\""; + private static final String EXPIRES_IN_REGEX = "\"expires_in\"\\s*:\\s*\"?(\\d*?)\"?\\D"; + private static final String REFRESH_TOKEN_REGEX = "\"refresh_token\"\\s*:\\s*\"(\\S*?)\""; + private static final String SCOPE_REGEX = "\"scope\"\\s*:\\s*\"(\\S*?)\""; + + protected OAuth2AccessTokenJsonExtractor() { + } + + private static class InstanceHolder { + + private static final OAuth2AccessTokenJsonExtractor INSTANCE = new OAuth2AccessTokenJsonExtractor(); + } + + public static OAuth2AccessTokenJsonExtractor instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public OAuth2AccessToken extract(String response) { + Preconditions.checkEmptyString(response, + "Response body is incorrect. Can't extract a token from an empty string"); + + final String accessToken = extractParameter(response, ACCESS_TOKEN_REGEX, true); + final String tokenType = extractParameter(response, TOKEN_TYPE_REGEX, false); + final String expiresInString = extractParameter(response, EXPIRES_IN_REGEX, false); + Integer expiresIn; + try { + expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString); + } catch (NumberFormatException nfe) { + expiresIn = null; + } + final String refreshToken = extractParameter(response, REFRESH_TOKEN_REGEX, false); + final String scope = extractParameter(response, SCOPE_REGEX, false); + + return createToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); + } + + protected OAuth2AccessToken createToken(String accessToken, String tokenType, Integer expiresIn, + String refreshToken, String scope, String response) { + return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); + } + + protected static String extractParameter(String response, String regex, boolean required) throws OAuthException { + final Matcher matcher = Pattern.compile(regex).matcher(response); + if (matcher.find()) { + return matcher.group(1); + } + + if (required) { + throw new OAuthException("Response body is incorrect. Can't extract a '" + regex + + "' from this: '" + response + "'", null); + } + + return null; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/TokenExtractor.java b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/TokenExtractor.java index eec9546cc..b86cbf126 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/extractors/TokenExtractor.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/extractors/TokenExtractor.java @@ -1,18 +1,18 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.model.Token; - -/** - * Simple command object that extracts a concrete {@link Token} from a String - * @param concrete type of Token - */ -public interface TokenExtractor { - - /** - * Extracts the concrete type of token from the contents of an Http Response - * - * @param response the contents of the response - * @return OAuth access token - */ - T extract(String response); -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.model.Token; + +/** + * Simple command object that extracts a concrete {@link Token} from a String + * @param concrete type of Token + */ +public interface TokenExtractor { + + /** + * Extracts the concrete type of token from the contents of an Http Response + * + * @param response the contents of the response + * @return OAuth access token + */ + T extract(String response); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/AbstractRequest.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/AbstractRequest.java index 4db6ccec7..0ab0c3361 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/AbstractRequest.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/AbstractRequest.java @@ -1,294 +1,294 @@ -package com.github.scribejava.core.model; - -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.oauth.OAuthService; - -/** - * The representation of an OAuth HttpRequest. - */ -public abstract class AbstractRequest { - - public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded"; - public static final String CONTENT_TYPE = "Content-Type"; - protected static final String CONTENT_LENGTH = "Content-Length"; - private static final String OAUTH_PREFIX = "oauth_"; - - private final String url; - private final Verb verb; - private final ParameterList querystringParams = new ParameterList(); - private final ParameterList bodyParams = new ParameterList(); - private final Map headers = new HashMap<>(); - private boolean connectionKeepAlive; - private boolean followRedirects = true; - private final OAuthService service; - - private String payload; - private String charset; - private byte[] bytePayload; - private final Map oauthParameters = new HashMap<>(); - - private String realm; - - /** - * Default constructor. - * - * @param verb Http verb/method - * @param url resource URL - * @param service OAuthService - */ - public AbstractRequest(Verb verb, String url, OAuthService service) { - this.verb = verb; - this.url = url; - this.service = service; - } - - /** - * Adds an OAuth parameter. - * - * @param key name of the parameter - * @param value value of the parameter - * @throws IllegalArgumentException if the parameter is not an OAuth parameter - */ - public void addOAuthParameter(String key, String value) { - oauthParameters.put(checkKey(key), value); - } - - private String checkKey(String key) { - if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE) || key.equals(OAuthConstants.REALM)) { - return key; - } else { - throw new IllegalArgumentException( - String.format("OAuth parameters must either be '%s', '%s' or start with '%s'", OAuthConstants.SCOPE, - OAuthConstants.REALM, OAUTH_PREFIX)); - } - } - - public Map getOauthParameters() { - return oauthParameters; - } - - public void setRealm(String realm) { - this.realm = realm; - } - - public String getRealm() { - return realm; - } - - /** - * Returns the complete url (host + resource + encoded querystring parameters). - * - * @return the complete url. - */ - public String getCompleteUrl() { - return querystringParams.appendTo(url); - } - - /** - * Add an HTTP Header to the Request - * - * @param key the header name - * @param value the header value - */ - public void addHeader(String key, String value) { - this.headers.put(key, value); - } - - /** - * Add a body Parameter (for POST/ PUT Requests) - * - * @param key the parameter name - * @param value the parameter value - */ - public void addBodyParameter(String key, String value) { - this.bodyParams.add(key, value); - } - - /** - * Add a QueryString parameter - * - * @param key the parameter name - * @param value the parameter value - */ - public void addQuerystringParameter(String key, String value) { - this.querystringParams.add(key, value); - } - - public void addParameter(String key, String value) { - if (hasBodyContent()) { - bodyParams.add(key, value); - } else { - querystringParams.add(key, value); - } - } - - protected boolean hasBodyContent() { - return verb == Verb.PUT || verb == Verb.POST; - } - - /** - * Add body payload. This method is used when the HTTP body is not a form-url-encoded string, but another thing. - * Like for example XML. Note: The contents are not part of the OAuth signature - * - * @param payload the body of the request - */ - public void addPayload(String payload) { - this.payload = payload; - } - - /** - * Overloaded version for byte arrays - * - * @param payload byte[] - */ - public void addPayload(byte[] payload) { - this.bytePayload = payload.clone(); - } - - /** - * Get a {@link ParameterList} with the query string parameters. - * - * @return a {@link ParameterList} containing the query string parameters. - * @throws OAuthException if the request URL is not valid. - */ - public ParameterList getQueryStringParams() { - try { - final ParameterList result = new ParameterList(); - final String queryString = new URL(url).getQuery(); - result.addQuerystring(queryString); - result.addAll(querystringParams); - return result; - } catch (MalformedURLException mue) { - throw new OAuthException("Malformed URL", mue); - } - } - - /** - * Obtains a {@link ParameterList} of the body parameters. - * - * @return a {@link ParameterList}containing the body parameters. - */ - public ParameterList getBodyParams() { - return bodyParams; - } - - /** - * Obtains the URL of the HTTP Request. - * - * @return the original URL of the HTTP Request - */ - public String getUrl() { - return url; - } - - /** - * Returns the URL without the port and the query string part. - * - * @return the OAuth-sanitized URL - */ - public String getSanitizedUrl() { - if (url.startsWith("http://") && (url.endsWith(":80") || url.contains(":80/"))) { - return url.replaceAll("\\?.*", "").replaceAll(":80", ""); - } else if (url.startsWith("https://") && (url.endsWith(":443") || url.contains(":443/"))) { - return url.replaceAll("\\?.*", "").replaceAll(":443", ""); - } else { - return url.replaceAll("\\?.*", ""); - } - } - - /** - * Returns the body of the request - * - * @return form encoded string - * - * @throws OAuthException if the charset chosen is not supported - */ - public String getBodyContents() { - try { - return new String(getByteBodyContents(), getCharset()); - } catch (UnsupportedEncodingException uee) { - throw new OAuthException("Unsupported Charset: " + charset, uee); - } - } - - byte[] getByteBodyContents() { - if (bytePayload != null) { - return bytePayload; - } - final String body = (payload == null) ? bodyParams.asFormUrlEncodedString() : payload; - try { - return body.getBytes(getCharset()); - } catch (UnsupportedEncodingException uee) { - throw new OAuthException("Unsupported Charset: " + getCharset(), uee); - } - } - - @Override - public String toString() { - return String.format("@Request(%s %s)", getVerb(), getUrl()); - } - - public Verb getVerb() { - return verb; - } - - public Map getHeaders() { - return headers; - } - - public String getCharset() { - return charset == null ? Charset.defaultCharset().name() : charset; - } - - /** - * Set the charset of the body of the request - * - * @param charsetName name of the charset of the request - */ - public void setCharset(String charsetName) { - charset = charsetName; - } - - /** - * Sets whether the underlying Http Connection is persistent or not. - * - * @param connectionKeepAlive boolean - * - * @see http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html - */ - public void setConnectionKeepAlive(boolean connectionKeepAlive) { - this.connectionKeepAlive = connectionKeepAlive; - } - - /** - * Sets whether the underlying Http Connection follows redirects or not. - * - * Defaults to true (follow redirects) - * - * @see http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects(boolean) - * @param followRedirects boolean - */ - public void setFollowRedirects(boolean followRedirects) { - this.followRedirects = followRedirects; - } - - public boolean isConnectionKeepAlive() { - return connectionKeepAlive; - } - - public boolean isFollowRedirects() { - return followRedirects; - } - - public OAuthService getService() { - return service; - } -} +package com.github.scribejava.core.model; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.oauth.OAuthService; + +/** + * The representation of an OAuth HttpRequest. + */ +public abstract class AbstractRequest { + + public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded"; + public static final String CONTENT_TYPE = "Content-Type"; + protected static final String CONTENT_LENGTH = "Content-Length"; + private static final String OAUTH_PREFIX = "oauth_"; + + private final String url; + private final Verb verb; + private final ParameterList querystringParams = new ParameterList(); + private final ParameterList bodyParams = new ParameterList(); + private final Map headers = new HashMap<>(); + private boolean connectionKeepAlive; + private boolean followRedirects = true; + private final OAuthService service; + + private String payload; + private String charset; + private byte[] bytePayload; + private final Map oauthParameters = new HashMap<>(); + + private String realm; + + /** + * Default constructor. + * + * @param verb Http verb/method + * @param url resource URL + * @param service OAuthService + */ + public AbstractRequest(Verb verb, String url, OAuthService service) { + this.verb = verb; + this.url = url; + this.service = service; + } + + /** + * Adds an OAuth parameter. + * + * @param key name of the parameter + * @param value value of the parameter + * @throws IllegalArgumentException if the parameter is not an OAuth parameter + */ + public void addOAuthParameter(String key, String value) { + oauthParameters.put(checkKey(key), value); + } + + private String checkKey(String key) { + if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE) || key.equals(OAuthConstants.REALM)) { + return key; + } else { + throw new IllegalArgumentException( + String.format("OAuth parameters must either be '%s', '%s' or start with '%s'", OAuthConstants.SCOPE, + OAuthConstants.REALM, OAUTH_PREFIX)); + } + } + + public Map getOauthParameters() { + return oauthParameters; + } + + public void setRealm(String realm) { + this.realm = realm; + } + + public String getRealm() { + return realm; + } + + /** + * Returns the complete url (host + resource + encoded querystring parameters). + * + * @return the complete url. + */ + public String getCompleteUrl() { + return querystringParams.appendTo(url); + } + + /** + * Add an HTTP Header to the Request + * + * @param key the header name + * @param value the header value + */ + public void addHeader(String key, String value) { + this.headers.put(key, value); + } + + /** + * Add a body Parameter (for POST/ PUT Requests) + * + * @param key the parameter name + * @param value the parameter value + */ + public void addBodyParameter(String key, String value) { + this.bodyParams.add(key, value); + } + + /** + * Add a QueryString parameter + * + * @param key the parameter name + * @param value the parameter value + */ + public void addQuerystringParameter(String key, String value) { + this.querystringParams.add(key, value); + } + + public void addParameter(String key, String value) { + if (hasBodyContent()) { + bodyParams.add(key, value); + } else { + querystringParams.add(key, value); + } + } + + protected boolean hasBodyContent() { + return verb == Verb.PUT || verb == Verb.POST; + } + + /** + * Add body payload. This method is used when the HTTP body is not a form-url-encoded string, but another thing. + * Like for example XML. Note: The contents are not part of the OAuth signature + * + * @param payload the body of the request + */ + public void addPayload(String payload) { + this.payload = payload; + } + + /** + * Overloaded version for byte arrays + * + * @param payload byte[] + */ + public void addPayload(byte[] payload) { + this.bytePayload = payload.clone(); + } + + /** + * Get a {@link ParameterList} with the query string parameters. + * + * @return a {@link ParameterList} containing the query string parameters. + * @throws OAuthException if the request URL is not valid. + */ + public ParameterList getQueryStringParams() { + try { + final ParameterList result = new ParameterList(); + final String queryString = new URL(url).getQuery(); + result.addQuerystring(queryString); + result.addAll(querystringParams); + return result; + } catch (MalformedURLException mue) { + throw new OAuthException("Malformed URL", mue); + } + } + + /** + * Obtains a {@link ParameterList} of the body parameters. + * + * @return a {@link ParameterList}containing the body parameters. + */ + public ParameterList getBodyParams() { + return bodyParams; + } + + /** + * Obtains the URL of the HTTP Request. + * + * @return the original URL of the HTTP Request + */ + public String getUrl() { + return url; + } + + /** + * Returns the URL without the port and the query string part. + * + * @return the OAuth-sanitized URL + */ + public String getSanitizedUrl() { + if (url.startsWith("http://") && (url.endsWith(":80") || url.contains(":80/"))) { + return url.replaceAll("\\?.*", "").replaceAll(":80", ""); + } else if (url.startsWith("https://") && (url.endsWith(":443") || url.contains(":443/"))) { + return url.replaceAll("\\?.*", "").replaceAll(":443", ""); + } else { + return url.replaceAll("\\?.*", ""); + } + } + + /** + * Returns the body of the request + * + * @return form encoded string + * + * @throws OAuthException if the charset chosen is not supported + */ + public String getBodyContents() { + try { + return new String(getByteBodyContents(), getCharset()); + } catch (UnsupportedEncodingException uee) { + throw new OAuthException("Unsupported Charset: " + charset, uee); + } + } + + byte[] getByteBodyContents() { + if (bytePayload != null) { + return bytePayload; + } + final String body = (payload == null) ? bodyParams.asFormUrlEncodedString() : payload; + try { + return body.getBytes(getCharset()); + } catch (UnsupportedEncodingException uee) { + throw new OAuthException("Unsupported Charset: " + getCharset(), uee); + } + } + + @Override + public String toString() { + return String.format("@Request(%s %s)", getVerb(), getUrl()); + } + + public Verb getVerb() { + return verb; + } + + public Map getHeaders() { + return headers; + } + + public String getCharset() { + return charset == null ? Charset.defaultCharset().name() : charset; + } + + /** + * Set the charset of the body of the request + * + * @param charsetName name of the charset of the request + */ + public void setCharset(String charsetName) { + charset = charsetName; + } + + /** + * Sets whether the underlying Http Connection is persistent or not. + * + * @param connectionKeepAlive boolean + * + * @see http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html + */ + public void setConnectionKeepAlive(boolean connectionKeepAlive) { + this.connectionKeepAlive = connectionKeepAlive; + } + + /** + * Sets whether the underlying Http Connection follows redirects or not. + * + * Defaults to true (follow redirects) + * + * @see http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects(boolean) + * @param followRedirects boolean + */ + public void setFollowRedirects(boolean followRedirects) { + this.followRedirects = followRedirects; + } + + public boolean isConnectionKeepAlive() { + return connectionKeepAlive; + } + + public boolean isFollowRedirects() { + return followRedirects; + } + + public OAuthService getService() { + return service; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/ForceTypeOfHttpRequest.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/ForceTypeOfHttpRequest.java index b0387a535..7194a4806 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/ForceTypeOfHttpRequest.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/ForceTypeOfHttpRequest.java @@ -1,10 +1,10 @@ -package com.github.scribejava.core.model; - -public enum ForceTypeOfHttpRequest { - - NONE, - FORCE_ASYNC_ONLY_HTTP_REQUESTS, - FORCE_SYNC_ONLY_HTTP_REQUESTS, - PREFER_ASYNC_ONLY_HTTP_REQUESTS, - PREFER_SYNC_ONLY_HTTP_REQUESTS -} +package com.github.scribejava.core.model; + +public enum ForceTypeOfHttpRequest { + + NONE, + FORCE_ASYNC_ONLY_HTTP_REQUESTS, + FORCE_SYNC_ONLY_HTTP_REQUESTS, + PREFER_ASYNC_ONLY_HTTP_REQUESTS, + PREFER_SYNC_ONLY_HTTP_REQUESTS +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1AccessToken.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1AccessToken.java index e57a7db39..a62591c84 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1AccessToken.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1AccessToken.java @@ -1,72 +1,72 @@ -package com.github.scribejava.core.model; - -import java.util.Objects; - -/** - * Represents an OAuth 1 Access Token http://tools.ietf.org/html/rfc5849#section-2.3 - */ -public class OAuth1AccessToken extends OAuth1Token { - - private static final long serialVersionUID = -103999293167210966L; - - public OAuth1AccessToken(String token, String tokenSecret) { - this(token, tokenSecret, null); - } - - public OAuth1AccessToken(String token, String tokenSecret, String rawResponse) { - super(token, tokenSecret, rawResponse); - } - - /** - * The token identifier. - * - * @return oauth_token - */ - @Override - public String getToken() { - return super.getToken(); - } - - /** - * The token shared-secret. - * - * @return oauth_token_secret - */ - @Override - public String getTokenSecret() { - return super.getTokenSecret(); - } - - @Override - public int hashCode() { - int hash = 3; - hash = 73 * hash + Objects.hashCode(getToken()); - hash = 73 * hash + Objects.hashCode(getTokenSecret()); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final OAuth1AccessToken other = (OAuth1AccessToken) obj; - if (!Objects.equals(getToken(), other.getToken())) { - return false; - } - return Objects.equals(getTokenSecret(), other.getTokenSecret()); - } - - @Override - public String toString() { - return "OAuth1AccessToken{" - + "oauth_token=" + getToken() - + ", oauth_token_secret=" + getTokenSecret() + '}'; - } -} +package com.github.scribejava.core.model; + +import java.util.Objects; + +/** + * Represents an OAuth 1 Access Token http://tools.ietf.org/html/rfc5849#section-2.3 + */ +public class OAuth1AccessToken extends OAuth1Token { + + private static final long serialVersionUID = -103999293167210966L; + + public OAuth1AccessToken(String token, String tokenSecret) { + this(token, tokenSecret, null); + } + + public OAuth1AccessToken(String token, String tokenSecret, String rawResponse) { + super(token, tokenSecret, rawResponse); + } + + /** + * The token identifier. + * + * @return oauth_token + */ + @Override + public String getToken() { + return super.getToken(); + } + + /** + * The token shared-secret. + * + * @return oauth_token_secret + */ + @Override + public String getTokenSecret() { + return super.getTokenSecret(); + } + + @Override + public int hashCode() { + int hash = 3; + hash = 73 * hash + Objects.hashCode(getToken()); + hash = 73 * hash + Objects.hashCode(getTokenSecret()); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final OAuth1AccessToken other = (OAuth1AccessToken) obj; + if (!Objects.equals(getToken(), other.getToken())) { + return false; + } + return Objects.equals(getTokenSecret(), other.getTokenSecret()); + } + + @Override + public String toString() { + return "OAuth1AccessToken{" + + "oauth_token=" + getToken() + + ", oauth_token_secret=" + getTokenSecret() + '}'; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1RequestToken.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1RequestToken.java index 1c53d4932..e8f81b9b7 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1RequestToken.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1RequestToken.java @@ -1,94 +1,94 @@ -package com.github.scribejava.core.model; - -import java.util.Objects; - -/** - * Represents an OAuth 1 Request Token http://tools.ietf.org/html/rfc5849#section-2.1 - */ -public class OAuth1RequestToken extends OAuth1Token { - - private static final long serialVersionUID = 6185104114662587991L; - - /** - * oauth_callback_confirmed: - *

- * MUST be present and set to "true". The parameter is used to differentiate from previous versions of the protocol. - *

- */ - private final boolean oauthCallbackConfirmed; - - public OAuth1RequestToken(String token, String tokenSecret) { - this(token, tokenSecret, null); - } - - public OAuth1RequestToken(String token, String tokenSecret, String rawResponse) { - this(token, tokenSecret, true, rawResponse); - } - - public OAuth1RequestToken(String token, String tokenSecret, boolean oauthCallbackConfirmed, String rawResponse) { - super(token, tokenSecret, rawResponse); - this.oauthCallbackConfirmed = oauthCallbackConfirmed; - } - - /** - * The temporary credentials identifier. - * - * @return oauth_token - */ - @Override - public String getToken() { - return super.getToken(); - } - - /** - * The temporary credentials shared-secret. - * - * @return oauth_token_secret - */ - @Override - public String getTokenSecret() { - return super.getTokenSecret(); - } - - public boolean isOauthCallbackConfirmed() { - return oauthCallbackConfirmed; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 83 * hash + Objects.hashCode(getToken()); - hash = 83 * hash + Objects.hashCode(getTokenSecret()); - hash = 83 * hash + (oauthCallbackConfirmed ? 1 : 0); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final OAuth1RequestToken other = (OAuth1RequestToken) obj; - if (oauthCallbackConfirmed != other.isOauthCallbackConfirmed()) { - return false; - } - if (!Objects.equals(getToken(), other.getToken())) { - return false; - } - return Objects.equals(getTokenSecret(), other.getTokenSecret()); - } - - @Override - public String toString() { - return "OAuth1RequestToken{" - + "oauth_token=" + getToken() - + ", oauth_token_secret=" + getTokenSecret() - + ", oauth_callback_confirmed=" + oauthCallbackConfirmed + '}'; - } -} +package com.github.scribejava.core.model; + +import java.util.Objects; + +/** + * Represents an OAuth 1 Request Token http://tools.ietf.org/html/rfc5849#section-2.1 + */ +public class OAuth1RequestToken extends OAuth1Token { + + private static final long serialVersionUID = 6185104114662587991L; + + /** + * oauth_callback_confirmed: + *

+ * MUST be present and set to "true". The parameter is used to differentiate from previous versions of the protocol. + *

+ */ + private final boolean oauthCallbackConfirmed; + + public OAuth1RequestToken(String token, String tokenSecret) { + this(token, tokenSecret, null); + } + + public OAuth1RequestToken(String token, String tokenSecret, String rawResponse) { + this(token, tokenSecret, true, rawResponse); + } + + public OAuth1RequestToken(String token, String tokenSecret, boolean oauthCallbackConfirmed, String rawResponse) { + super(token, tokenSecret, rawResponse); + this.oauthCallbackConfirmed = oauthCallbackConfirmed; + } + + /** + * The temporary credentials identifier. + * + * @return oauth_token + */ + @Override + public String getToken() { + return super.getToken(); + } + + /** + * The temporary credentials shared-secret. + * + * @return oauth_token_secret + */ + @Override + public String getTokenSecret() { + return super.getTokenSecret(); + } + + public boolean isOauthCallbackConfirmed() { + return oauthCallbackConfirmed; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 83 * hash + Objects.hashCode(getToken()); + hash = 83 * hash + Objects.hashCode(getTokenSecret()); + hash = 83 * hash + (oauthCallbackConfirmed ? 1 : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final OAuth1RequestToken other = (OAuth1RequestToken) obj; + if (oauthCallbackConfirmed != other.isOauthCallbackConfirmed()) { + return false; + } + if (!Objects.equals(getToken(), other.getToken())) { + return false; + } + return Objects.equals(getTokenSecret(), other.getTokenSecret()); + } + + @Override + public String toString() { + return "OAuth1RequestToken{" + + "oauth_token=" + getToken() + + ", oauth_token_secret=" + getTokenSecret() + + ", oauth_callback_confirmed=" + oauthCallbackConfirmed + '}'; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1Token.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1Token.java index 3d02f49aa..266c61d74 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1Token.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth1Token.java @@ -1,38 +1,38 @@ -package com.github.scribejava.core.model; - -import com.github.scribejava.core.utils.Preconditions; - -/** - * Represents an abstract OAuth 1 Token (either request or access token) - */ -public abstract class OAuth1Token extends Token { - - private static final long serialVersionUID = 6285873427974823019L; - - private final String token; - - private final String tokenSecret; - - public OAuth1Token(String token, String tokenSecret, String rawResponse) { - super(rawResponse); - Preconditions.checkNotNull(token, "oauth_token can't be null"); - Preconditions.checkNotNull(tokenSecret, "oauth_token_secret can't be null"); - this.token = token; - this.tokenSecret = tokenSecret; - } - - public String getToken() { - return token; - } - - public String getTokenSecret() { - return tokenSecret; - } - - /** - * @return true if the token is empty (oauth_token = "", oauth_token_secret = "") - */ - public boolean isEmpty() { - return "".equals(token) && "".equals(tokenSecret); - } -} +package com.github.scribejava.core.model; + +import com.github.scribejava.core.utils.Preconditions; + +/** + * Represents an abstract OAuth 1 Token (either request or access token) + */ +public abstract class OAuth1Token extends Token { + + private static final long serialVersionUID = 6285873427974823019L; + + private final String token; + + private final String tokenSecret; + + public OAuth1Token(String token, String tokenSecret, String rawResponse) { + super(rawResponse); + Preconditions.checkNotNull(token, "oauth_token can't be null"); + Preconditions.checkNotNull(tokenSecret, "oauth_token_secret can't be null"); + this.token = token; + this.tokenSecret = tokenSecret; + } + + public String getToken() { + return token; + } + + public String getTokenSecret() { + return tokenSecret; + } + + /** + * @return true if the token is empty (oauth_token = "", oauth_token_secret = "") + */ + public boolean isEmpty() { + return "".equals(token) && "".equals(tokenSecret); + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2AccessToken.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2AccessToken.java index b97e4e0a0..237336da2 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2AccessToken.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2AccessToken.java @@ -1,144 +1,144 @@ -package com.github.scribejava.core.model; - -import com.github.scribejava.core.utils.Preconditions; -import java.util.Objects; - -/** - * Represents an OAuth 2 Access token. - *

- * http://tools.ietf.org/html/rfc6749#section-5.1 - * - * @see OAuth 2 Access Token Specification

- */ -public class OAuth2AccessToken extends Token { - - private static final long serialVersionUID = 8901381135476613449L; - - /** - * access_token - *

- * REQUIRED. The access token issued by the authorization server.

- */ - private String accessToken; - - /** - * token_type - *

- * REQUIRED. The type of the token issued as described in http://tools.ietf.org/html/rfc6749#section-7.1 Value is - * case insensitive.

- */ - private String tokenType; - - /** - * expires_in - *

- * RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access - * token will expire in one hour from the time the response was generated. If omitted, the authorization server - * SHOULD provide the expiration time via other means or document the default value.

- */ - private Integer expiresIn; - - /** - * refresh_token - *

- * OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same authorization grant as - * described in http://tools.ietf.org/html/rfc6749#section-6

- */ - private String refreshToken; - - /** - * scope - *

- * OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token - * as described by http://tools.ietf.org/html/rfc6749#section-3.3

- */ - private String scope; - - public OAuth2AccessToken(String accessToken) { - this(accessToken, null); - } - - public OAuth2AccessToken(String accessToken, String rawResponse) { - this(accessToken, null, null, null, null, rawResponse); - } - - public OAuth2AccessToken(String accessToken, String tokenType, Integer expiresIn, String refreshToken, String scope, - String rawResponse) { - super(rawResponse); - Preconditions.checkNotNull(accessToken, "access_token can't be null"); - this.accessToken = accessToken; - this.tokenType = tokenType; - this.expiresIn = expiresIn; - this.refreshToken = refreshToken; - this.scope = scope; - } - - - public String getAccessToken() { - return accessToken; - } - - public String getTokenType() { - return tokenType; - } - - public Integer getExpiresIn() { - return expiresIn; - } - - public String getRefreshToken() { - return refreshToken; - } - - public String getScope() { - return scope; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 41 * hash + Objects.hashCode(accessToken); - hash = 41 * hash + Objects.hashCode(tokenType); - hash = 41 * hash + Objects.hashCode(expiresIn); - hash = 41 * hash + Objects.hashCode(refreshToken); - hash = 41 * hash + Objects.hashCode(scope); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final OAuth2AccessToken other = (OAuth2AccessToken) obj; - if (!Objects.equals(accessToken, other.getAccessToken())) { - return false; - } - if (!Objects.equals(tokenType, other.getTokenType())) { - return false; - } - if (!Objects.equals(refreshToken, other.getRefreshToken())) { - return false; - } - if (!Objects.equals(scope, other.getScope())) { - return false; - } - return Objects.equals(expiresIn, other.getExpiresIn()); - } - - @Override - public String toString() { - return "OAuth2AccessToken{" - + "access_token=" + accessToken - + ", token_type=" + tokenType - + ", expires_in=" + expiresIn - + ", refresh_token=" + refreshToken - + ", scope=" + scope + '}'; - } -} +package com.github.scribejava.core.model; + +import com.github.scribejava.core.utils.Preconditions; +import java.util.Objects; + +/** + * Represents an OAuth 2 Access token. + *

+ * http://tools.ietf.org/html/rfc6749#section-5.1 + * + * @see OAuth 2 Access Token Specification

+ */ +public class OAuth2AccessToken extends Token { + + private static final long serialVersionUID = 8901381135476613449L; + + /** + * access_token + *

+ * REQUIRED. The access token issued by the authorization server.

+ */ + private String accessToken; + + /** + * token_type + *

+ * REQUIRED. The type of the token issued as described in http://tools.ietf.org/html/rfc6749#section-7.1 Value is + * case insensitive.

+ */ + private String tokenType; + + /** + * expires_in + *

+ * RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access + * token will expire in one hour from the time the response was generated. If omitted, the authorization server + * SHOULD provide the expiration time via other means or document the default value.

+ */ + private Integer expiresIn; + + /** + * refresh_token + *

+ * OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same authorization grant as + * described in http://tools.ietf.org/html/rfc6749#section-6

+ */ + private String refreshToken; + + /** + * scope + *

+ * OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token + * as described by http://tools.ietf.org/html/rfc6749#section-3.3

+ */ + private String scope; + + public OAuth2AccessToken(String accessToken) { + this(accessToken, null); + } + + public OAuth2AccessToken(String accessToken, String rawResponse) { + this(accessToken, null, null, null, null, rawResponse); + } + + public OAuth2AccessToken(String accessToken, String tokenType, Integer expiresIn, String refreshToken, String scope, + String rawResponse) { + super(rawResponse); + Preconditions.checkNotNull(accessToken, "access_token can't be null"); + this.accessToken = accessToken; + this.tokenType = tokenType; + this.expiresIn = expiresIn; + this.refreshToken = refreshToken; + this.scope = scope; + } + + + public String getAccessToken() { + return accessToken; + } + + public String getTokenType() { + return tokenType; + } + + public Integer getExpiresIn() { + return expiresIn; + } + + public String getRefreshToken() { + return refreshToken; + } + + public String getScope() { + return scope; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 41 * hash + Objects.hashCode(accessToken); + hash = 41 * hash + Objects.hashCode(tokenType); + hash = 41 * hash + Objects.hashCode(expiresIn); + hash = 41 * hash + Objects.hashCode(refreshToken); + hash = 41 * hash + Objects.hashCode(scope); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final OAuth2AccessToken other = (OAuth2AccessToken) obj; + if (!Objects.equals(accessToken, other.getAccessToken())) { + return false; + } + if (!Objects.equals(tokenType, other.getTokenType())) { + return false; + } + if (!Objects.equals(refreshToken, other.getRefreshToken())) { + return false; + } + if (!Objects.equals(scope, other.getScope())) { + return false; + } + return Objects.equals(expiresIn, other.getExpiresIn()); + } + + @Override + public String toString() { + return "OAuth2AccessToken{" + + "access_token=" + accessToken + + ", token_type=" + tokenType + + ", expires_in=" + expiresIn + + ", refresh_token=" + refreshToken + + ", scope=" + scope + '}'; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2Authorization.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2Authorization.java index 8c99f395b..74c3fe986 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2Authorization.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuth2Authorization.java @@ -1,43 +1,43 @@ -package com.github.scribejava.core.model; - -/** - * represents Authorization Response http://tools.ietf.org/html/rfc6749#section-4.1.2 - * - * If the resource owner grants the access request, the authorization server issues an authorization code and delivers - * it to the client by adding the following parameters to the query component of the redirection URI using the - * "application/x-www-form-urlencoded" format. - * - */ -public class OAuth2Authorization { - - /** - * REQUIRED. The authorization code generated by the authorization server. The authorization code MUST expire - * shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is - * RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more - * than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously - * issued based on that authorization code. The authorization code is bound to the client identifier and redirection - * URI. - */ - private String code; - /** - * REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from - * the client. - */ - private String state; - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } -} +package com.github.scribejava.core.model; + +/** + * represents Authorization Response http://tools.ietf.org/html/rfc6749#section-4.1.2 + * + * If the resource owner grants the access request, the authorization server issues an authorization code and delivers + * it to the client by adding the following parameters to the query component of the redirection URI using the + * "application/x-www-form-urlencoded" format. + * + */ +public class OAuth2Authorization { + + /** + * REQUIRED. The authorization code generated by the authorization server. The authorization code MUST expire + * shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is + * RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more + * than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously + * issued based on that authorization code. The authorization code is bound to the client identifier and redirection + * URI. + */ + private String code; + /** + * REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from + * the client. + */ + private String state; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthAsyncRequestCallback.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthAsyncRequestCallback.java index 10f398fc4..2065e1317 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthAsyncRequestCallback.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthAsyncRequestCallback.java @@ -1,8 +1,8 @@ -package com.github.scribejava.core.model; - -public interface OAuthAsyncRequestCallback { - - void onCompleted(T response); - - void onThrowable(Throwable t); -} +package com.github.scribejava.core.model; + +public interface OAuthAsyncRequestCallback { + + void onCompleted(T response); + + void onThrowable(Throwable t); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConfig.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConfig.java index d5bba4899..ab421dd32 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConfig.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConfig.java @@ -1,118 +1,118 @@ -package com.github.scribejava.core.model; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Parameter object that groups OAuth config values - */ -public class OAuthConfig { - - private final String apiKey; - private final String apiSecret; - private final String callback; - private final SignatureType signatureType; - private final String scope; - private final OutputStream debugStream; - private final String state; - private final String responseType; - private final String userAgent; - - //sync only version - private final Integer connectTimeout; - private final Integer readTimeout; - - //async version only - //ning 1.9 - private com.ning.http.client.AsyncHttpClientConfig ningAsyncHttpClientConfig; - private String ningAsyncHttpProviderClassName; - //AHC 2.0 - private org.asynchttpclient.AsyncHttpClientConfig ahcAsyncHttpClientConfig; - - public OAuthConfig(String key, String secret) { - this(key, secret, null, null, null, null, null, null, null, null, null, null, null, null); - } - - public OAuthConfig(String apiKey, String apiSecret, String callback, SignatureType signatureType, String scope, - OutputStream debugStream, String state, String responseType, String userAgent, Integer connectTimeout, - Integer readTimeout, com.ning.http.client.AsyncHttpClientConfig ningAsyncHttpClientConfig, - String ningAsyncHttpProviderClassName, org.asynchttpclient.AsyncHttpClientConfig ahcAsyncHttpClientConfig) { - this.apiKey = apiKey; - this.apiSecret = apiSecret; - this.callback = callback; - this.signatureType = signatureType; - this.scope = scope; - this.debugStream = debugStream; - this.state = state; - this.responseType = responseType; - this.userAgent = userAgent; - this.connectTimeout = connectTimeout; - this.readTimeout = readTimeout; - this.ningAsyncHttpClientConfig = ningAsyncHttpClientConfig; - this.ningAsyncHttpProviderClassName = ningAsyncHttpProviderClassName; - this.ahcAsyncHttpClientConfig = ahcAsyncHttpClientConfig; - } - - public String getApiKey() { - return apiKey; - } - - public String getApiSecret() { - return apiSecret; - } - - public String getCallback() { - return callback; - } - - public SignatureType getSignatureType() { - return signatureType; - } - - public String getScope() { - return scope; - } - - public String getState() { - return state; - } - - public String getResponseType() { - return responseType; - } - - public String getUserAgent() { - return userAgent; - } - - public void log(String message) { - if (debugStream != null) { - message += '\n'; - try { - debugStream.write(message.getBytes("UTF8")); - } catch (IOException | RuntimeException e) { - throw new RuntimeException("there were problems while writting to the debug stream", e); - } - } - } - - public Integer getConnectTimeout() { - return connectTimeout; - } - - public Integer getReadTimeout() { - return readTimeout; - } - - public com.ning.http.client.AsyncHttpClientConfig getNingAsyncHttpClientConfig() { - return ningAsyncHttpClientConfig; - } - - public String getNingAsyncHttpProviderClassName() { - return ningAsyncHttpProviderClassName; - } - - public org.asynchttpclient.AsyncHttpClientConfig getAhcAsyncHttpClientConfig() { - return ahcAsyncHttpClientConfig; - } -} +package com.github.scribejava.core.model; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Parameter object that groups OAuth config values + */ +public class OAuthConfig { + + private final String apiKey; + private final String apiSecret; + private final String callback; + private final SignatureType signatureType; + private final String scope; + private final OutputStream debugStream; + private final String state; + private final String responseType; + private final String userAgent; + + //sync only version + private final Integer connectTimeout; + private final Integer readTimeout; + + //async version only + //ning 1.9 + private com.ning.http.client.AsyncHttpClientConfig ningAsyncHttpClientConfig; + private String ningAsyncHttpProviderClassName; + //AHC 2.0 + private org.asynchttpclient.AsyncHttpClientConfig ahcAsyncHttpClientConfig; + + public OAuthConfig(String key, String secret) { + this(key, secret, null, null, null, null, null, null, null, null, null, null, null, null); + } + + public OAuthConfig(String apiKey, String apiSecret, String callback, SignatureType signatureType, String scope, + OutputStream debugStream, String state, String responseType, String userAgent, Integer connectTimeout, + Integer readTimeout, com.ning.http.client.AsyncHttpClientConfig ningAsyncHttpClientConfig, + String ningAsyncHttpProviderClassName, org.asynchttpclient.AsyncHttpClientConfig ahcAsyncHttpClientConfig) { + this.apiKey = apiKey; + this.apiSecret = apiSecret; + this.callback = callback; + this.signatureType = signatureType; + this.scope = scope; + this.debugStream = debugStream; + this.state = state; + this.responseType = responseType; + this.userAgent = userAgent; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.ningAsyncHttpClientConfig = ningAsyncHttpClientConfig; + this.ningAsyncHttpProviderClassName = ningAsyncHttpProviderClassName; + this.ahcAsyncHttpClientConfig = ahcAsyncHttpClientConfig; + } + + public String getApiKey() { + return apiKey; + } + + public String getApiSecret() { + return apiSecret; + } + + public String getCallback() { + return callback; + } + + public SignatureType getSignatureType() { + return signatureType; + } + + public String getScope() { + return scope; + } + + public String getState() { + return state; + } + + public String getResponseType() { + return responseType; + } + + public String getUserAgent() { + return userAgent; + } + + public void log(String message) { + if (debugStream != null) { + message += '\n'; + try { + debugStream.write(message.getBytes("UTF8")); + } catch (IOException | RuntimeException e) { + throw new RuntimeException("there were problems while writting to the debug stream", e); + } + } + } + + public Integer getConnectTimeout() { + return connectTimeout; + } + + public Integer getReadTimeout() { + return readTimeout; + } + + public com.ning.http.client.AsyncHttpClientConfig getNingAsyncHttpClientConfig() { + return ningAsyncHttpClientConfig; + } + + public String getNingAsyncHttpProviderClassName() { + return ningAsyncHttpProviderClassName; + } + + public org.asynchttpclient.AsyncHttpClientConfig getAhcAsyncHttpClientConfig() { + return ahcAsyncHttpClientConfig; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConstants.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConstants.java index 2cf8d236a..0aaf575e8 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConstants.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthConstants.java @@ -1,44 +1,44 @@ -package com.github.scribejava.core.model; - -/** - * This class contains OAuth constants, used project-wide - */ -public interface OAuthConstants { - - String TIMESTAMP = "oauth_timestamp"; - String SIGN_METHOD = "oauth_signature_method"; - String SIGNATURE = "oauth_signature"; - String CONSUMER_SECRET = "oauth_consumer_secret"; - String CONSUMER_KEY = "oauth_consumer_key"; - String CALLBACK = "oauth_callback"; - String VERSION = "oauth_version"; - String NONCE = "oauth_nonce"; - String REALM = "realm"; - String PARAM_PREFIX = "oauth_"; - String TOKEN = "oauth_token"; - String TOKEN_SECRET = "oauth_token_secret"; - String OUT_OF_BAND = "oob"; - String VERIFIER = "oauth_verifier"; - String HEADER = "Authorization"; - String SCOPE = "scope"; - String BASIC = "Basic"; - - // OAuth 2.0 - String ACCESS_TOKEN = "access_token"; - String CLIENT_ID = "client_id"; - String CLIENT_SECRET = "client_secret"; - String REDIRECT_URI = "redirect_uri"; - String CODE = "code"; - String REFRESH_TOKEN = "refresh_token"; - String GRANT_TYPE = "grant_type"; - String AUTHORIZATION_CODE = "authorization_code"; - String STATE = "state"; - String USERNAME = "username"; - String PASSWORD = "password"; - String RESPONSE_TYPE = "response_type"; - String RESPONSE_TYPE_CODE = "code"; - - //not OAuth specific - String USER_AGENT_HEADER_NAME = "User-Agent"; - -} +package com.github.scribejava.core.model; + +/** + * This class contains OAuth constants, used project-wide + */ +public interface OAuthConstants { + + String TIMESTAMP = "oauth_timestamp"; + String SIGN_METHOD = "oauth_signature_method"; + String SIGNATURE = "oauth_signature"; + String CONSUMER_SECRET = "oauth_consumer_secret"; + String CONSUMER_KEY = "oauth_consumer_key"; + String CALLBACK = "oauth_callback"; + String VERSION = "oauth_version"; + String NONCE = "oauth_nonce"; + String REALM = "realm"; + String PARAM_PREFIX = "oauth_"; + String TOKEN = "oauth_token"; + String TOKEN_SECRET = "oauth_token_secret"; + String OUT_OF_BAND = "oob"; + String VERIFIER = "oauth_verifier"; + String HEADER = "Authorization"; + String SCOPE = "scope"; + String BASIC = "Basic"; + + // OAuth 2.0 + String ACCESS_TOKEN = "access_token"; + String CLIENT_ID = "client_id"; + String CLIENT_SECRET = "client_secret"; + String REDIRECT_URI = "redirect_uri"; + String CODE = "code"; + String REFRESH_TOKEN = "refresh_token"; + String GRANT_TYPE = "grant_type"; + String AUTHORIZATION_CODE = "authorization_code"; + String STATE = "state"; + String USERNAME = "username"; + String PASSWORD = "password"; + String RESPONSE_TYPE = "response_type"; + String RESPONSE_TYPE_CODE = "code"; + + //not OAuth specific + String USER_AGENT_HEADER_NAME = "User-Agent"; + +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequest.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequest.java index 230cd15b9..bfd904917 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequest.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequest.java @@ -1,92 +1,92 @@ -package com.github.scribejava.core.model; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import com.github.scribejava.core.exceptions.OAuthConnectionException; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.oauth.OAuthService; - -public class OAuthRequest extends AbstractRequest { - - private HttpURLConnection connection; - - public OAuthRequest(Verb verb, String url, OAuthService service) { - super(verb, url, service); - } - - /** - * Execute the request and return a {@link Response} - * - * @return Http Response - * - * @throws RuntimeException if the connection cannot be created. - */ - public Response send() { - final ForceTypeOfHttpRequest forceTypeOfHttpRequest = ScribeJavaConfig.getForceTypeOfHttpRequests(); - - if (ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - throw new OAuthException("Cannot use sync operations, only async"); - } - if (ForceTypeOfHttpRequest.PREFER_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - getService().getConfig().log("Cannot use sync operations, only async"); - } - try { - createConnection(); - return doSend(); - } catch (IOException | RuntimeException e) { - throw new OAuthConnectionException(getCompleteUrl(), e); - } - } - - Response doSend() throws IOException { - final Verb verb = getVerb(); - connection.setRequestMethod(verb.name()); - final OAuthConfig config = getService().getConfig(); - if (config.getConnectTimeout() != null) { - connection.setConnectTimeout(config.getConnectTimeout()); - } - if (config.getReadTimeout() != null) { - connection.setReadTimeout(config.getReadTimeout()); - } - addHeaders(); - if (hasBodyContent()) { - addBody(getByteBodyContents()); - } - return new Response(connection); - } - - private void createConnection() throws IOException { - final String completeUrl = getCompleteUrl(); - if (connection == null) { - System.setProperty("http.keepAlive", isConnectionKeepAlive() ? "true" : "false"); - connection = (HttpURLConnection) new URL(completeUrl).openConnection(); - connection.setInstanceFollowRedirects(isFollowRedirects()); - } - } - - void addHeaders() { - for (Map.Entry entry : getHeaders().entrySet()) { - connection.setRequestProperty(entry.getKey(), entry.getValue()); - } - final String userAgent = getService().getConfig().getUserAgent(); - if (userAgent != null) { - connection.setRequestProperty(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); - } - } - - void addBody(byte[] content) throws IOException { - connection.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length)); - - if (connection.getRequestProperty(CONTENT_TYPE) == null) { - connection.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); - } - connection.setDoOutput(true); - connection.getOutputStream().write(content); - } - - void setConnection(HttpURLConnection connection) { - this.connection = connection; - } -} +package com.github.scribejava.core.model; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Map; +import com.github.scribejava.core.exceptions.OAuthConnectionException; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.oauth.OAuthService; + +public class OAuthRequest extends AbstractRequest { + + private HttpURLConnection connection; + + public OAuthRequest(Verb verb, String url, OAuthService service) { + super(verb, url, service); + } + + /** + * Execute the request and return a {@link Response} + * + * @return Http Response + * + * @throws RuntimeException if the connection cannot be created. + */ + public Response send() { + final ForceTypeOfHttpRequest forceTypeOfHttpRequest = ScribeJavaConfig.getForceTypeOfHttpRequests(); + + if (ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + throw new OAuthException("Cannot use sync operations, only async"); + } + if (ForceTypeOfHttpRequest.PREFER_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + getService().getConfig().log("Cannot use sync operations, only async"); + } + try { + createConnection(); + return doSend(); + } catch (IOException | RuntimeException e) { + throw new OAuthConnectionException(getCompleteUrl(), e); + } + } + + Response doSend() throws IOException { + final Verb verb = getVerb(); + connection.setRequestMethod(verb.name()); + final OAuthConfig config = getService().getConfig(); + if (config.getConnectTimeout() != null) { + connection.setConnectTimeout(config.getConnectTimeout()); + } + if (config.getReadTimeout() != null) { + connection.setReadTimeout(config.getReadTimeout()); + } + addHeaders(); + if (hasBodyContent()) { + addBody(getByteBodyContents()); + } + return new Response(connection); + } + + private void createConnection() throws IOException { + final String completeUrl = getCompleteUrl(); + if (connection == null) { + System.setProperty("http.keepAlive", isConnectionKeepAlive() ? "true" : "false"); + connection = (HttpURLConnection) new URL(completeUrl).openConnection(); + connection.setInstanceFollowRedirects(isFollowRedirects()); + } + } + + void addHeaders() { + for (Map.Entry entry : getHeaders().entrySet()) { + connection.setRequestProperty(entry.getKey(), entry.getValue()); + } + final String userAgent = getService().getConfig().getUserAgent(); + if (userAgent != null) { + connection.setRequestProperty(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); + } + } + + void addBody(byte[] content) throws IOException { + connection.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length)); + + if (connection.getRequestProperty(CONTENT_TYPE) == null) { + connection.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); + } + connection.setDoOutput(true); + connection.getOutputStream().write(content); + } + + void setConnection(HttpURLConnection connection) { + this.connection = connection; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequestAsync.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequestAsync.java index 1a92f0699..bf5104f9f 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequestAsync.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequestAsync.java @@ -1,36 +1,36 @@ -package com.github.scribejava.core.model; - -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.oauth.OAuthService; - -import java.io.IOException; -import java.util.concurrent.Future; - -public class OAuthRequestAsync extends AbstractRequest { - - public OAuthRequestAsync(Verb verb, String url, OAuthService service) { - super(verb, url, service); - } - - public Future sendAsync(OAuthAsyncRequestCallback callback, ResponseConverter converter) { - final ForceTypeOfHttpRequest forceTypeOfHttpRequest = ScribeJavaConfig.getForceTypeOfHttpRequests(); - if (ForceTypeOfHttpRequest.FORCE_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - throw new OAuthException("Cannot use async operations, only sync"); - } - final OAuthService service = getService(); - final OAuthConfig config = service.getConfig(); - if (ForceTypeOfHttpRequest.PREFER_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - config.log("Cannot use async operations, only sync"); - } - return service.executeAsync(getHeaders(), getVerb(), getCompleteUrl(), getBodyContents(), callback, converter); - } - - public Future sendAsync(OAuthAsyncRequestCallback callback) { - return sendAsync(callback, null); - } - - public interface ResponseConverter { - - T convert(Response response) throws IOException; - } -} +package com.github.scribejava.core.model; + +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.oauth.OAuthService; + +import java.io.IOException; +import java.util.concurrent.Future; + +public class OAuthRequestAsync extends AbstractRequest { + + public OAuthRequestAsync(Verb verb, String url, OAuthService service) { + super(verb, url, service); + } + + public Future sendAsync(OAuthAsyncRequestCallback callback, ResponseConverter converter) { + final ForceTypeOfHttpRequest forceTypeOfHttpRequest = ScribeJavaConfig.getForceTypeOfHttpRequests(); + if (ForceTypeOfHttpRequest.FORCE_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + throw new OAuthException("Cannot use async operations, only sync"); + } + final OAuthService service = getService(); + final OAuthConfig config = service.getConfig(); + if (ForceTypeOfHttpRequest.PREFER_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + config.log("Cannot use async operations, only sync"); + } + return service.executeAsync(getHeaders(), getVerb(), getCompleteUrl(), getBodyContents(), callback, converter); + } + + public Future sendAsync(OAuthAsyncRequestCallback callback) { + return sendAsync(callback, null); + } + + public interface ResponseConverter { + + T convert(Response response) throws IOException; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/Parameter.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/Parameter.java index 9397cb773..9f5ed74d6 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/Parameter.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/Parameter.java @@ -1,54 +1,54 @@ -package com.github.scribejava.core.model; - -import com.github.scribejava.core.utils.OAuthEncoder; - -public class Parameter implements Comparable { - - private final String key; - private final String value; - - public Parameter(String key, String value) { - this.key = key; - this.value = value; - } - - public String asUrlEncodedPair() { - return OAuthEncoder.encode(key).concat("=").concat(OAuthEncoder.encode(value)); - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } - if (other == this) { - return true; - } - if (!(other instanceof Parameter)) { - return false; - } - - final Parameter otherParam = (Parameter) other; - return otherParam.getKey().equals(key) && otherParam.getValue().equals(value); - } - - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - @Override - public int hashCode() { - return key.hashCode() + value.hashCode(); - } - - @Override - public int compareTo(Parameter parameter) { - final int keyDiff = key.compareTo(parameter.getKey()); - - return keyDiff == 0 ? value.compareTo(parameter.getValue()) : keyDiff; - } -} +package com.github.scribejava.core.model; + +import com.github.scribejava.core.utils.OAuthEncoder; + +public class Parameter implements Comparable { + + private final String key; + private final String value; + + public Parameter(String key, String value) { + this.key = key; + this.value = value; + } + + public String asUrlEncodedPair() { + return OAuthEncoder.encode(key).concat("=").concat(OAuthEncoder.encode(value)); + } + + @Override + public boolean equals(Object other) { + if (other == null) { + return false; + } + if (other == this) { + return true; + } + if (!(other instanceof Parameter)) { + return false; + } + + final Parameter otherParam = (Parameter) other; + return otherParam.getKey().equals(key) && otherParam.getValue().equals(value); + } + + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + @Override + public int hashCode() { + return key.hashCode() + value.hashCode(); + } + + @Override + public int compareTo(Parameter parameter) { + final int keyDiff = key.compareTo(parameter.getKey()); + + return keyDiff == 0 ? value.compareTo(parameter.getValue()) : keyDiff; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/ParameterList.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/ParameterList.java index 39d806652..21d111d72 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/ParameterList.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/ParameterList.java @@ -1,100 +1,100 @@ -package com.github.scribejava.core.model; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -public class ParameterList { - - private static final char QUERY_STRING_SEPARATOR = '?'; - private static final String PARAM_SEPARATOR = "&"; - private static final String PAIR_SEPARATOR = "="; - private static final String EMPTY_STRING = ""; - - private final List params; - - public ParameterList() { - params = new ArrayList<>(); - } - - ParameterList(List params) { - this.params = new ArrayList<>(params); - } - - public ParameterList(Map map) { - this(); - if (map != null && !map.isEmpty()) { - for (Map.Entry entry : map.entrySet()) { - params.add(new Parameter(entry.getKey(), entry.getValue())); - } - } - } - - public void add(String key, String value) { - params.add(new Parameter(key, value)); - } - - public String appendTo(String url) { - Preconditions.checkNotNull(url, "Cannot append to null URL"); - final String queryString = asFormUrlEncodedString(); - if (queryString.equals(EMPTY_STRING)) { - return url; - } else { - return url - + (url.indexOf(QUERY_STRING_SEPARATOR) == -1 ? QUERY_STRING_SEPARATOR : PARAM_SEPARATOR) - + queryString; - } - } - - public String asOauthBaseString() { - return OAuthEncoder.encode(asFormUrlEncodedString()); - } - - public String asFormUrlEncodedString() { - if (params.isEmpty()) { - return EMPTY_STRING; - } - - final StringBuilder builder = new StringBuilder(); - for (Parameter p : params) { - builder.append(PARAM_SEPARATOR).append(p.asUrlEncodedPair()); - } - return builder.substring(1); - } - - public void addAll(ParameterList other) { - params.addAll(other.getParams()); - } - - public void addQuerystring(String queryString) { - if (queryString != null && !queryString.isEmpty()) { - for (String param : queryString.split(PARAM_SEPARATOR)) { - final String[] pair = param.split(PAIR_SEPARATOR); - final String key = OAuthEncoder.decode(pair[0]); - final String value = pair.length > 1 ? OAuthEncoder.decode(pair[1]) : EMPTY_STRING; - params.add(new Parameter(key, value)); - } - } - } - - public boolean contains(Parameter param) { - return params.contains(param); - } - - public int size() { - return params.size(); - } - - public List getParams() { - return params; - } - - public ParameterList sort() { - final ParameterList sorted = new ParameterList(params); - Collections.sort(sorted.getParams()); - return sorted; - } -} +package com.github.scribejava.core.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +public class ParameterList { + + private static final char QUERY_STRING_SEPARATOR = '?'; + private static final String PARAM_SEPARATOR = "&"; + private static final String PAIR_SEPARATOR = "="; + private static final String EMPTY_STRING = ""; + + private final List params; + + public ParameterList() { + params = new ArrayList<>(); + } + + ParameterList(List params) { + this.params = new ArrayList<>(params); + } + + public ParameterList(Map map) { + this(); + if (map != null && !map.isEmpty()) { + for (Map.Entry entry : map.entrySet()) { + params.add(new Parameter(entry.getKey(), entry.getValue())); + } + } + } + + public void add(String key, String value) { + params.add(new Parameter(key, value)); + } + + public String appendTo(String url) { + Preconditions.checkNotNull(url, "Cannot append to null URL"); + final String queryString = asFormUrlEncodedString(); + if (queryString.equals(EMPTY_STRING)) { + return url; + } else { + return url + + (url.indexOf(QUERY_STRING_SEPARATOR) == -1 ? QUERY_STRING_SEPARATOR : PARAM_SEPARATOR) + + queryString; + } + } + + public String asOauthBaseString() { + return OAuthEncoder.encode(asFormUrlEncodedString()); + } + + public String asFormUrlEncodedString() { + if (params.isEmpty()) { + return EMPTY_STRING; + } + + final StringBuilder builder = new StringBuilder(); + for (Parameter p : params) { + builder.append(PARAM_SEPARATOR).append(p.asUrlEncodedPair()); + } + return builder.substring(1); + } + + public void addAll(ParameterList other) { + params.addAll(other.getParams()); + } + + public void addQuerystring(String queryString) { + if (queryString != null && !queryString.isEmpty()) { + for (String param : queryString.split(PARAM_SEPARATOR)) { + final String[] pair = param.split(PAIR_SEPARATOR); + final String key = OAuthEncoder.decode(pair[0]); + final String value = pair.length > 1 ? OAuthEncoder.decode(pair[1]) : EMPTY_STRING; + params.add(new Parameter(key, value)); + } + } + } + + public boolean contains(Parameter param) { + return params.contains(param); + } + + public int size() { + return params.size(); + } + + public List getParams() { + return params; + } + + public ParameterList sort() { + final ParameterList sorted = new ParameterList(params); + Collections.sort(sorted.getParams()); + return sorted; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/Response.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/Response.java index 869066788..e3d9a0fd1 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/Response.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/Response.java @@ -1,123 +1,123 @@ -package com.github.scribejava.core.model; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.utils.StreamUtils; - -public class Response { - - private int code; - private String message; - private String body; - private InputStream stream; - private Map headers; - - public Response(int code, String message, Map headers, String body, InputStream stream) { - this.code = code; - this.headers = headers; - this.body = body; - this.message = message; - this.stream = stream; - } - - Response(HttpURLConnection connection) throws IOException { - try { - connection.connect(); - code = connection.getResponseCode(); - message = connection.getResponseMessage(); - headers = parseHeaders(connection); - stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream(); - } catch (UnknownHostException e) { - throw new OAuthException("The IP address of a host could not be determined.", e); - } - } - - private String parseBodyContents() throws IOException { - if ("gzip".equals(getHeader("Content-Encoding"))) { - body = StreamUtils.getGzipStreamContents(getStream()); - } else { - body = StreamUtils.getStreamContents(getStream()); - } - return body; - } - - private Map parseHeaders(HttpURLConnection conn) { - final Map headers = new HashMap<>(); - for (String key : conn.getHeaderFields().keySet()) { - headers.put(key, conn.getHeaderFields().get(key).get(0)); - } - return headers; - } - - public final boolean isSuccessful() { - return getCode() >= 200 && getCode() < 400; - } - - public String getBody() throws IOException { - return body == null ? parseBodyContents() : body; - } - - /** - * Obtains the meaningful stream of the HttpUrlConnection, either inputStream or errorInputStream, depending on the - * status code - * - * @return input stream / error stream - */ - public InputStream getStream() { - return stream; - } - - /** - * Obtains the HTTP status code - * - * @return the status code - */ - public final int getCode() { - return code; - } - - /** - * Obtains the HTTP status message. Returns null if the message can not be discerned from the response - * (not valid HTTP) - * - * @return the status message - */ - public String getMessage() { - return message; - } - - /** - * Obtains a {@link Map} containing the HTTP Response Headers - * - * @return headers - */ - public Map getHeaders() { - return headers; - } - - /** - * Obtains a single HTTP Header value, or null if undefined - * - * @param name the header name. - * - * @return header value or null. - */ - public String getHeader(String name) { - return headers.get(name); - } - - @Override - public String toString() { - return "Response{" + - "code=" + code + - ", message='" + message + '\'' + - ", body='" + body + '\'' + - ", headers=" + headers + - '}'; - } -} +package com.github.scribejava.core.model; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Map; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.utils.StreamUtils; + +public class Response { + + private int code; + private String message; + private String body; + private InputStream stream; + private Map headers; + + public Response(int code, String message, Map headers, String body, InputStream stream) { + this.code = code; + this.headers = headers; + this.body = body; + this.message = message; + this.stream = stream; + } + + Response(HttpURLConnection connection) throws IOException { + try { + connection.connect(); + code = connection.getResponseCode(); + message = connection.getResponseMessage(); + headers = parseHeaders(connection); + stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream(); + } catch (UnknownHostException e) { + throw new OAuthException("The IP address of a host could not be determined.", e); + } + } + + private String parseBodyContents() throws IOException { + if ("gzip".equals(getHeader("Content-Encoding"))) { + body = StreamUtils.getGzipStreamContents(getStream()); + } else { + body = StreamUtils.getStreamContents(getStream()); + } + return body; + } + + private Map parseHeaders(HttpURLConnection conn) { + final Map headers = new HashMap<>(); + for (String key : conn.getHeaderFields().keySet()) { + headers.put(key, conn.getHeaderFields().get(key).get(0)); + } + return headers; + } + + public final boolean isSuccessful() { + return getCode() >= 200 && getCode() < 400; + } + + public String getBody() throws IOException { + return body == null ? parseBodyContents() : body; + } + + /** + * Obtains the meaningful stream of the HttpUrlConnection, either inputStream or errorInputStream, depending on the + * status code + * + * @return input stream / error stream + */ + public InputStream getStream() { + return stream; + } + + /** + * Obtains the HTTP status code + * + * @return the status code + */ + public final int getCode() { + return code; + } + + /** + * Obtains the HTTP status message. Returns null if the message can not be discerned from the response + * (not valid HTTP) + * + * @return the status message + */ + public String getMessage() { + return message; + } + + /** + * Obtains a {@link Map} containing the HTTP Response Headers + * + * @return headers + */ + public Map getHeaders() { + return headers; + } + + /** + * Obtains a single HTTP Header value, or null if undefined + * + * @param name the header name. + * + * @return header value or null. + */ + public String getHeader(String name) { + return headers.get(name); + } + + @Override + public String toString() { + return "Response{" + + "code=" + code + + ", message='" + message + '\'' + + ", body='" + body + '\'' + + ", headers=" + headers + + '}'; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/ScribeJavaConfig.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/ScribeJavaConfig.java index 171bbac1a..9c97ff9bb 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/ScribeJavaConfig.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/ScribeJavaConfig.java @@ -1,14 +1,14 @@ -package com.github.scribejava.core.model; - -public abstract class ScribeJavaConfig { - - private static ForceTypeOfHttpRequest forceTypeOfHttpRequests = ForceTypeOfHttpRequest.NONE; - - public static ForceTypeOfHttpRequest getForceTypeOfHttpRequests() { - return forceTypeOfHttpRequests; - } - - public static void setForceTypeOfHttpRequests(ForceTypeOfHttpRequest forceTypeOfHttpRequests) { - ScribeJavaConfig.forceTypeOfHttpRequests = forceTypeOfHttpRequests; - } -} +package com.github.scribejava.core.model; + +public abstract class ScribeJavaConfig { + + private static ForceTypeOfHttpRequest forceTypeOfHttpRequests = ForceTypeOfHttpRequest.NONE; + + public static ForceTypeOfHttpRequest getForceTypeOfHttpRequests() { + return forceTypeOfHttpRequests; + } + + public static void setForceTypeOfHttpRequests(ForceTypeOfHttpRequest forceTypeOfHttpRequests) { + ScribeJavaConfig.forceTypeOfHttpRequests = forceTypeOfHttpRequests; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/SignatureType.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/SignatureType.java index 26ffe054e..b707f4274 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/SignatureType.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/SignatureType.java @@ -1,7 +1,7 @@ -package com.github.scribejava.core.model; - -public enum SignatureType { - - Header, - QueryString -} +package com.github.scribejava.core.model; + +public enum SignatureType { + + Header, + QueryString +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/Token.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/Token.java index ede417c03..174102f97 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/Token.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/Token.java @@ -1,39 +1,39 @@ -package com.github.scribejava.core.model; - -import java.io.Serializable; - -/** - * Represents an abstract OAuth (1 and 2) token (either request or access token) - */ -public abstract class Token implements Serializable { - - private static final long serialVersionUID = -8409640649946468092L; - - private final String rawResponse; - - protected Token(String rawResponse) { - this.rawResponse = rawResponse; - } - - public String getRawResponse() { - if (rawResponse == null) { - throw new IllegalStateException( - "This token object was not constructed by ScribeJava and does not have a rawResponse"); - } - return rawResponse; - } - - public String getParameter(String parameter) { - String value = null; - for (String str : rawResponse.split("&")) { - if (str.startsWith(parameter + '=')) { - final String[] part = str.split("="); - if (part.length > 1) { - value = part[1].trim(); - } - break; - } - } - return value; - } -} +package com.github.scribejava.core.model; + +import java.io.Serializable; + +/** + * Represents an abstract OAuth (1 and 2) token (either request or access token) + */ +public abstract class Token implements Serializable { + + private static final long serialVersionUID = -8409640649946468092L; + + private final String rawResponse; + + protected Token(String rawResponse) { + this.rawResponse = rawResponse; + } + + public String getRawResponse() { + if (rawResponse == null) { + throw new IllegalStateException( + "This token object was not constructed by ScribeJava and does not have a rawResponse"); + } + return rawResponse; + } + + public String getParameter(String parameter) { + String value = null; + for (String str : rawResponse.split("&")) { + if (str.startsWith(parameter + '=')) { + final String[] part = str.split("="); + if (part.length > 1) { + value = part[1].trim(); + } + break; + } + } + return value; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/model/Verb.java b/scribejava-core/src/main/java/com/github/scribejava/core/model/Verb.java index 6ca83a517..6a3f8780a 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/model/Verb.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/model/Verb.java @@ -1,9 +1,9 @@ -package com.github.scribejava.core.model; - -/** - * An enumeration containing the most common HTTP Verbs. - */ -public enum Verb { - - GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH -} +package com.github.scribejava.core.model; + +/** + * An enumeration containing the most common HTTP Verbs. + */ +public enum Verb { + + GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth10aService.java b/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth10aService.java index e707486bc..e777fff52 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth10aService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth10aService.java @@ -1,201 +1,201 @@ -package com.github.scribejava.core.oauth; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.Future; -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth1AccessToken; -import com.github.scribejava.core.model.OAuth1RequestToken; -import com.github.scribejava.core.model.OAuthAsyncRequestCallback; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.OAuthRequest; -import com.github.scribejava.core.model.OAuthRequestAsync; -import com.github.scribejava.core.model.Response; -import com.github.scribejava.core.services.Base64Encoder; -import com.github.scribejava.core.utils.MapUtils; - -/** - * OAuth 1.0a implementation of {@link OAuthService} - */ -public class OAuth10aService extends OAuthService { - - private static final String VERSION = "1.0"; - private final DefaultApi10a api; - - /** - * Default constructor - * - * @param api OAuth1.0a api information - * @param config OAuth 1.0a configuration param object - */ - public OAuth10aService(DefaultApi10a api, OAuthConfig config) { - super(config); - this.api = api; - } - - public final OAuth1RequestToken getRequestToken() throws IOException { - final OAuthConfig config = getConfig(); - config.log("obtaining request token from " + api.getRequestTokenEndpoint()); - final OAuthRequest request = new OAuthRequest(api.getRequestTokenVerb(), api.getRequestTokenEndpoint(), this); - - prepareRequestTokenRequest(request); - - config.log("sending request..."); - final Response response = request.send(); - final String body = response.getBody(); - - config.log("response status code: " + response.getCode()); - config.log("response body: " + body); - return api.getRequestTokenExtractor().extract(body); - } - - public final Future getRequestTokenAsync( - OAuthAsyncRequestCallback callback) { - final OAuthConfig config = getConfig(); - config.log("async obtaining request token from " + api.getRequestTokenEndpoint()); - final OAuthRequestAsync request - = new OAuthRequestAsync(api.getRequestTokenVerb(), api.getRequestTokenEndpoint(), this); - prepareRequestTokenRequest(request); - return request.sendAsync(callback, new OAuthRequestAsync.ResponseConverter() { - @Override - public OAuth1RequestToken convert(Response response) throws IOException { - return getApi().getRequestTokenExtractor().extract(response.getBody()); - } - }); - } - - protected void prepareRequestTokenRequest(AbstractRequest request) { - final OAuthConfig config = getConfig(); - config.log("setting oauth_callback to " + config.getCallback()); - request.addOAuthParameter(OAuthConstants.CALLBACK, config.getCallback()); - addOAuthParams(request, ""); - appendSignature(request); - } - - private void addOAuthParams(AbstractRequest request, String tokenSecret) { - final OAuthConfig config = getConfig(); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, api.getTimestampService().getTimestampInSeconds()); - request.addOAuthParameter(OAuthConstants.NONCE, api.getTimestampService().getNonce()); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, config.getApiKey()); - request.addOAuthParameter(OAuthConstants.SIGN_METHOD, api.getSignatureService().getSignatureMethod()); - request.addOAuthParameter(OAuthConstants.VERSION, getVersion()); - final String scope = config.getScope(); - if (scope != null) { - request.addOAuthParameter(OAuthConstants.SCOPE, scope); - } - request.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(request, tokenSecret)); - - config.log("appended additional OAuth parameters: " + MapUtils.toString(request.getOauthParameters())); - } - - public final OAuth1AccessToken getAccessToken(OAuth1RequestToken requestToken, String oauthVerifier) - throws IOException { - final OAuthConfig config = getConfig(); - config.log("obtaining access token from " + api.getAccessTokenEndpoint()); - final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this); - prepareAccessTokenRequest(request, requestToken, oauthVerifier); - final Response response = request.send(); - return api.getAccessTokenExtractor().extract(response.getBody()); - } - - /** - * Start the request to retrieve the access token. The optionally provided - * callback will be called with the Token when it is available. - * - * @param requestToken request token (obtained previously or null) - * @param oauthVerifier oauth_verifier - * @param callback optional callback - * @return Future - */ - public final Future getAccessTokenAsync(OAuth1RequestToken requestToken, String oauthVerifier, - OAuthAsyncRequestCallback callback) { - final OAuthConfig config = getConfig(); - config.log("async obtaining access token from " + api.getAccessTokenEndpoint()); - final OAuthRequestAsync request - = new OAuthRequestAsync(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this); - prepareAccessTokenRequest(request, requestToken, oauthVerifier); - return request.sendAsync(callback, new OAuthRequestAsync.ResponseConverter() { - @Override - public OAuth1AccessToken convert(Response response) throws IOException { - return getApi().getAccessTokenExtractor().extract(response.getBody()); - } - }); - } - - protected void prepareAccessTokenRequest(AbstractRequest request, OAuth1RequestToken requestToken, - String oauthVerifier) { - final OAuthConfig config = getConfig(); - request.addOAuthParameter(OAuthConstants.TOKEN, requestToken.getToken()); - request.addOAuthParameter(OAuthConstants.VERIFIER, oauthVerifier); - config.log("setting token to: " + requestToken + " and verifier to: " + oauthVerifier); - addOAuthParams(request, requestToken.getTokenSecret()); - appendSignature(request); - } - - public void signRequest(OAuth1AccessToken token, AbstractRequest request) { - final OAuthConfig config = getConfig(); - config.log("signing request: " + request.getCompleteUrl()); - - if (!token.isEmpty() || api.isEmptyOAuthTokenParamIsRequired()) { - request.addOAuthParameter(OAuthConstants.TOKEN, token.getToken()); - } - config.log("setting token to: " + token); - addOAuthParams(request, token.getTokenSecret()); - appendSignature(request); - } - - @Override - public String getVersion() { - return VERSION; - } - - /** - * Returns the URL where you should redirect your users to authenticate your - * application. - * - * @param requestToken the request token you need to authorize - * @return the URL where you should redirect your users - */ - public String getAuthorizationUrl(OAuth1RequestToken requestToken) { - return api.getAuthorizationUrl(requestToken); - } - - private String getSignature(AbstractRequest request, String tokenSecret) { - final OAuthConfig config = getConfig(); - config.log("generating signature..."); - config.log("using base64 encoder: " + Base64Encoder.type()); - final String baseString = api.getBaseStringExtractor().extract(request); - final String signature = api.getSignatureService().getSignature(baseString, config.getApiSecret(), tokenSecret); - - config.log("base string is: " + baseString); - config.log("signature is: " + signature); - return signature; - } - - private void appendSignature(AbstractRequest request) { - final OAuthConfig config = getConfig(); - switch (config.getSignatureType()) { - case Header: - config.log("using Http Header signature"); - - final String oauthHeader = api.getHeaderExtractor().extract(request); - request.addHeader(OAuthConstants.HEADER, oauthHeader); - break; - case QueryString: - config.log("using Querystring signature"); - - for (Map.Entry entry : request.getOauthParameters().entrySet()) { - request.addQuerystringParameter(entry.getKey(), entry.getValue()); - } - break; - default: - throw new IllegalStateException("Unknown new Signature Type '" + config.getSignatureType() + "'."); - } - } - - public DefaultApi10a getApi() { - return api; - } -} +package com.github.scribejava.core.oauth; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.Future; +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.OAuthRequestAsync; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.services.Base64Encoder; +import com.github.scribejava.core.utils.MapUtils; + +/** + * OAuth 1.0a implementation of {@link OAuthService} + */ +public class OAuth10aService extends OAuthService { + + private static final String VERSION = "1.0"; + private final DefaultApi10a api; + + /** + * Default constructor + * + * @param api OAuth1.0a api information + * @param config OAuth 1.0a configuration param object + */ + public OAuth10aService(DefaultApi10a api, OAuthConfig config) { + super(config); + this.api = api; + } + + public final OAuth1RequestToken getRequestToken() throws IOException { + final OAuthConfig config = getConfig(); + config.log("obtaining request token from " + api.getRequestTokenEndpoint()); + final OAuthRequest request = new OAuthRequest(api.getRequestTokenVerb(), api.getRequestTokenEndpoint(), this); + + prepareRequestTokenRequest(request); + + config.log("sending request..."); + final Response response = request.send(); + final String body = response.getBody(); + + config.log("response status code: " + response.getCode()); + config.log("response body: " + body); + return api.getRequestTokenExtractor().extract(body); + } + + public final Future getRequestTokenAsync( + OAuthAsyncRequestCallback callback) { + final OAuthConfig config = getConfig(); + config.log("async obtaining request token from " + api.getRequestTokenEndpoint()); + final OAuthRequestAsync request + = new OAuthRequestAsync(api.getRequestTokenVerb(), api.getRequestTokenEndpoint(), this); + prepareRequestTokenRequest(request); + return request.sendAsync(callback, new OAuthRequestAsync.ResponseConverter() { + @Override + public OAuth1RequestToken convert(Response response) throws IOException { + return getApi().getRequestTokenExtractor().extract(response.getBody()); + } + }); + } + + protected void prepareRequestTokenRequest(AbstractRequest request) { + final OAuthConfig config = getConfig(); + config.log("setting oauth_callback to " + config.getCallback()); + request.addOAuthParameter(OAuthConstants.CALLBACK, config.getCallback()); + addOAuthParams(request, ""); + appendSignature(request); + } + + private void addOAuthParams(AbstractRequest request, String tokenSecret) { + final OAuthConfig config = getConfig(); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, api.getTimestampService().getTimestampInSeconds()); + request.addOAuthParameter(OAuthConstants.NONCE, api.getTimestampService().getNonce()); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, config.getApiKey()); + request.addOAuthParameter(OAuthConstants.SIGN_METHOD, api.getSignatureService().getSignatureMethod()); + request.addOAuthParameter(OAuthConstants.VERSION, getVersion()); + final String scope = config.getScope(); + if (scope != null) { + request.addOAuthParameter(OAuthConstants.SCOPE, scope); + } + request.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(request, tokenSecret)); + + config.log("appended additional OAuth parameters: " + MapUtils.toString(request.getOauthParameters())); + } + + public final OAuth1AccessToken getAccessToken(OAuth1RequestToken requestToken, String oauthVerifier) + throws IOException { + final OAuthConfig config = getConfig(); + config.log("obtaining access token from " + api.getAccessTokenEndpoint()); + final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this); + prepareAccessTokenRequest(request, requestToken, oauthVerifier); + final Response response = request.send(); + return api.getAccessTokenExtractor().extract(response.getBody()); + } + + /** + * Start the request to retrieve the access token. The optionally provided + * callback will be called with the Token when it is available. + * + * @param requestToken request token (obtained previously or null) + * @param oauthVerifier oauth_verifier + * @param callback optional callback + * @return Future + */ + public final Future getAccessTokenAsync(OAuth1RequestToken requestToken, String oauthVerifier, + OAuthAsyncRequestCallback callback) { + final OAuthConfig config = getConfig(); + config.log("async obtaining access token from " + api.getAccessTokenEndpoint()); + final OAuthRequestAsync request + = new OAuthRequestAsync(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this); + prepareAccessTokenRequest(request, requestToken, oauthVerifier); + return request.sendAsync(callback, new OAuthRequestAsync.ResponseConverter() { + @Override + public OAuth1AccessToken convert(Response response) throws IOException { + return getApi().getAccessTokenExtractor().extract(response.getBody()); + } + }); + } + + protected void prepareAccessTokenRequest(AbstractRequest request, OAuth1RequestToken requestToken, + String oauthVerifier) { + final OAuthConfig config = getConfig(); + request.addOAuthParameter(OAuthConstants.TOKEN, requestToken.getToken()); + request.addOAuthParameter(OAuthConstants.VERIFIER, oauthVerifier); + config.log("setting token to: " + requestToken + " and verifier to: " + oauthVerifier); + addOAuthParams(request, requestToken.getTokenSecret()); + appendSignature(request); + } + + public void signRequest(OAuth1AccessToken token, AbstractRequest request) { + final OAuthConfig config = getConfig(); + config.log("signing request: " + request.getCompleteUrl()); + + if (!token.isEmpty() || api.isEmptyOAuthTokenParamIsRequired()) { + request.addOAuthParameter(OAuthConstants.TOKEN, token.getToken()); + } + config.log("setting token to: " + token); + addOAuthParams(request, token.getTokenSecret()); + appendSignature(request); + } + + @Override + public String getVersion() { + return VERSION; + } + + /** + * Returns the URL where you should redirect your users to authenticate your + * application. + * + * @param requestToken the request token you need to authorize + * @return the URL where you should redirect your users + */ + public String getAuthorizationUrl(OAuth1RequestToken requestToken) { + return api.getAuthorizationUrl(requestToken); + } + + private String getSignature(AbstractRequest request, String tokenSecret) { + final OAuthConfig config = getConfig(); + config.log("generating signature..."); + config.log("using base64 encoder: " + Base64Encoder.type()); + final String baseString = api.getBaseStringExtractor().extract(request); + final String signature = api.getSignatureService().getSignature(baseString, config.getApiSecret(), tokenSecret); + + config.log("base string is: " + baseString); + config.log("signature is: " + signature); + return signature; + } + + private void appendSignature(AbstractRequest request) { + final OAuthConfig config = getConfig(); + switch (config.getSignatureType()) { + case Header: + config.log("using Http Header signature"); + + final String oauthHeader = api.getHeaderExtractor().extract(request); + request.addHeader(OAuthConstants.HEADER, oauthHeader); + break; + case QueryString: + config.log("using Querystring signature"); + + for (Map.Entry entry : request.getOauthParameters().entrySet()) { + request.addQuerystringParameter(entry.getKey(), entry.getValue()); + } + break; + default: + throw new IllegalStateException("Unknown new Signature Type '" + config.getSignatureType() + "'."); + } + } + + public DefaultApi10a getApi() { + return api; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth20Service.java b/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth20Service.java index 43bf4c7fa..0839c3d86 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth20Service.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth20Service.java @@ -1,217 +1,217 @@ -package com.github.scribejava.core.oauth; - -import com.github.scribejava.core.services.Base64Encoder; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.concurrent.Future; -import com.github.scribejava.core.builder.api.DefaultApi20; -import com.github.scribejava.core.model.AbstractRequest; -import com.github.scribejava.core.model.OAuth2AccessToken; -import com.github.scribejava.core.model.OAuth2Authorization; -import com.github.scribejava.core.model.OAuthAsyncRequestCallback; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.OAuthRequest; -import com.github.scribejava.core.model.OAuthRequestAsync; -import com.github.scribejava.core.model.Response; -import java.util.Map; - -public class OAuth20Service extends OAuthService { - - private static final String VERSION = "2.0"; - private final DefaultApi20 api; - - /** - * Default constructor - * - * @param api OAuth2.0 api information - * @param config OAuth 2.0 configuration param object - */ - public OAuth20Service(DefaultApi20 api, OAuthConfig config) { - super(config); - this.api = api; - } - - //sync version, protected to facilitate mocking - protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException { - return api.getAccessTokenExtractor().extract(request.send().getBody()); - } - - //async version, protected to facilitate mocking - protected Future sendAccessTokenRequestAsync(OAuthRequestAsync request, - OAuthAsyncRequestCallback callback) { - - return request.sendAsync(callback, new OAuthRequestAsync.ResponseConverter() { - @Override - public OAuth2AccessToken convert(Response response) throws IOException { - return getApi().getAccessTokenExtractor().extract(response.getBody()); - } - }); - } - - public final OAuth2AccessToken getAccessToken(String code) throws IOException { - final OAuthRequest request = createAccessTokenRequest(code, - new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); - - return sendAccessTokenRequestSync(request); - } - - /** - * Start the request to retrieve the access token. The optionally provided callback will be called with the Token - * when it is available. - * - * @param code code - * @param callback optional callback - * @return Future - */ - public final Future getAccessTokenAsync(String code, - OAuthAsyncRequestCallback callback) { - final OAuthRequestAsync request = createAccessTokenRequest(code, - new OAuthRequestAsync(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); - - return sendAccessTokenRequestAsync(request, callback); - } - - protected T createAccessTokenRequest(String code, T request) { - final OAuthConfig config = getConfig(); - request.addParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); - request.addParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); - request.addParameter(OAuthConstants.CODE, code); - request.addParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); - final String scope = config.getScope(); - if (scope != null) { - request.addParameter(OAuthConstants.SCOPE, scope); - } - request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); - return request; - } - - public final OAuth2AccessToken refreshAccessToken(String refreshToken) throws IOException { - final OAuthRequest request = createRefreshTokenRequest(refreshToken, - new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); - - return sendAccessTokenRequestSync(request); - } - - public final Future refreshAccessTokenAsync(String refreshToken, - OAuthAsyncRequestCallback callback) { - final OAuthRequestAsync request = createRefreshTokenRequest(refreshToken, - new OAuthRequestAsync(api.getAccessTokenVerb(), api.getRefreshTokenEndpoint(), this)); - - return sendAccessTokenRequestAsync(request, callback); - } - - protected T createRefreshTokenRequest(String refreshToken, T request) { - if (refreshToken == null || refreshToken.isEmpty()) { - throw new IllegalArgumentException("The refreshToken cannot be null or empty"); - } - final OAuthConfig config = getConfig(); - request.addParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); - request.addParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); - request.addParameter(OAuthConstants.REFRESH_TOKEN, refreshToken); - request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.REFRESH_TOKEN); - return request; - } - - public final OAuth2AccessToken getAccessTokenPasswordGrant(String uname, String password) throws IOException { - final OAuthRequest request = createAccessTokenPasswordGrantRequest(uname, password, - new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); - - return sendAccessTokenRequestSync(request); - } - - /** - * Request Access Token Password Grant async version - * - * @param uname User name - * @param password User password - * @param callback Optional callback - * @return Future - */ - public final Future getAccessTokenPasswordGrantAsync(String uname, String password, - OAuthAsyncRequestCallback callback) { - final OAuthRequestAsync request = createAccessTokenPasswordGrantRequest(uname, password, - new OAuthRequestAsync(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); - - return sendAccessTokenRequestAsync(request, callback); - } - - protected T createAccessTokenPasswordGrantRequest(String username, String password, - T request) { - final OAuthConfig config = getConfig(); - request.addParameter(OAuthConstants.USERNAME, username); - request.addParameter(OAuthConstants.PASSWORD, password); - - final String scope = config.getScope(); - if (scope != null) { - request.addParameter(OAuthConstants.SCOPE, scope); - } - - request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.PASSWORD); - - final String apiKey = config.getApiKey(); - final String apiSecret = config.getApiSecret(); - if (apiKey != null && apiSecret != null) { - request.addHeader(OAuthConstants.HEADER, - OAuthConstants.BASIC + ' ' - + Base64Encoder.getInstance() - .encode(String.format("%s:%s", apiKey, apiSecret).getBytes(Charset.forName("UTF-8")))); - } - - return request; - } - - /** - * {@inheritDoc} - */ - @Override - public String getVersion() { - return VERSION; - } - - public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { - request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getAccessToken()); - } - - /** - * Returns the URL where you should redirect your users to authenticate your application. - * - * @return the URL where you should redirect your users - */ - public final String getAuthorizationUrl() { - return getAuthorizationUrl(null); - } - - /** - * Returns the URL where you should redirect your users to authenticate your application. - * - * @param additionalParams any additional GET params to add to the URL - * @return the URL where you should redirect your users - */ - public String getAuthorizationUrl(Map additionalParams) { - return api.getAuthorizationUrl(getConfig(), additionalParams); - } - - public DefaultApi20 getApi() { - return api; - } - - public OAuth2Authorization extractAuthorization(String redirectLocation) { - final OAuth2Authorization authorization = new OAuth2Authorization(); - for (String param : redirectLocation.substring(redirectLocation.indexOf('?') + 1).split("&")) { - final String[] keyValue = param.split("="); - if (keyValue.length == 2) { - switch (keyValue[0]) { - case "code": - authorization.setCode(keyValue[1]); - break; - case "state": - authorization.setState(keyValue[1]); - break; - default: //just ignore any other param; - } - } - } - return authorization; - } -} +package com.github.scribejava.core.oauth; + +import com.github.scribejava.core.services.Base64Encoder; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.concurrent.Future; +import com.github.scribejava.core.builder.api.DefaultApi20; +import com.github.scribejava.core.model.AbstractRequest; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuth2Authorization; +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.OAuthRequestAsync; +import com.github.scribejava.core.model.Response; +import java.util.Map; + +public class OAuth20Service extends OAuthService { + + private static final String VERSION = "2.0"; + private final DefaultApi20 api; + + /** + * Default constructor + * + * @param api OAuth2.0 api information + * @param config OAuth 2.0 configuration param object + */ + public OAuth20Service(DefaultApi20 api, OAuthConfig config) { + super(config); + this.api = api; + } + + //sync version, protected to facilitate mocking + protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException { + return api.getAccessTokenExtractor().extract(request.send().getBody()); + } + + //async version, protected to facilitate mocking + protected Future sendAccessTokenRequestAsync(OAuthRequestAsync request, + OAuthAsyncRequestCallback callback) { + + return request.sendAsync(callback, new OAuthRequestAsync.ResponseConverter() { + @Override + public OAuth2AccessToken convert(Response response) throws IOException { + return getApi().getAccessTokenExtractor().extract(response.getBody()); + } + }); + } + + public final OAuth2AccessToken getAccessToken(String code) throws IOException { + final OAuthRequest request = createAccessTokenRequest(code, + new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); + + return sendAccessTokenRequestSync(request); + } + + /** + * Start the request to retrieve the access token. The optionally provided callback will be called with the Token + * when it is available. + * + * @param code code + * @param callback optional callback + * @return Future + */ + public final Future getAccessTokenAsync(String code, + OAuthAsyncRequestCallback callback) { + final OAuthRequestAsync request = createAccessTokenRequest(code, + new OAuthRequestAsync(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); + + return sendAccessTokenRequestAsync(request, callback); + } + + protected T createAccessTokenRequest(String code, T request) { + final OAuthConfig config = getConfig(); + request.addParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); + request.addParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); + request.addParameter(OAuthConstants.CODE, code); + request.addParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); + final String scope = config.getScope(); + if (scope != null) { + request.addParameter(OAuthConstants.SCOPE, scope); + } + request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); + return request; + } + + public final OAuth2AccessToken refreshAccessToken(String refreshToken) throws IOException { + final OAuthRequest request = createRefreshTokenRequest(refreshToken, + new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); + + return sendAccessTokenRequestSync(request); + } + + public final Future refreshAccessTokenAsync(String refreshToken, + OAuthAsyncRequestCallback callback) { + final OAuthRequestAsync request = createRefreshTokenRequest(refreshToken, + new OAuthRequestAsync(api.getAccessTokenVerb(), api.getRefreshTokenEndpoint(), this)); + + return sendAccessTokenRequestAsync(request, callback); + } + + protected T createRefreshTokenRequest(String refreshToken, T request) { + if (refreshToken == null || refreshToken.isEmpty()) { + throw new IllegalArgumentException("The refreshToken cannot be null or empty"); + } + final OAuthConfig config = getConfig(); + request.addParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); + request.addParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); + request.addParameter(OAuthConstants.REFRESH_TOKEN, refreshToken); + request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.REFRESH_TOKEN); + return request; + } + + public final OAuth2AccessToken getAccessTokenPasswordGrant(String uname, String password) throws IOException { + final OAuthRequest request = createAccessTokenPasswordGrantRequest(uname, password, + new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); + + return sendAccessTokenRequestSync(request); + } + + /** + * Request Access Token Password Grant async version + * + * @param uname User name + * @param password User password + * @param callback Optional callback + * @return Future + */ + public final Future getAccessTokenPasswordGrantAsync(String uname, String password, + OAuthAsyncRequestCallback callback) { + final OAuthRequestAsync request = createAccessTokenPasswordGrantRequest(uname, password, + new OAuthRequestAsync(api.getAccessTokenVerb(), api.getAccessTokenEndpoint(), this)); + + return sendAccessTokenRequestAsync(request, callback); + } + + protected T createAccessTokenPasswordGrantRequest(String username, String password, + T request) { + final OAuthConfig config = getConfig(); + request.addParameter(OAuthConstants.USERNAME, username); + request.addParameter(OAuthConstants.PASSWORD, password); + + final String scope = config.getScope(); + if (scope != null) { + request.addParameter(OAuthConstants.SCOPE, scope); + } + + request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.PASSWORD); + + final String apiKey = config.getApiKey(); + final String apiSecret = config.getApiSecret(); + if (apiKey != null && apiSecret != null) { + request.addHeader(OAuthConstants.HEADER, + OAuthConstants.BASIC + ' ' + + Base64Encoder.getInstance() + .encode(String.format("%s:%s", apiKey, apiSecret).getBytes(Charset.forName("UTF-8")))); + } + + return request; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return VERSION; + } + + public void signRequest(OAuth2AccessToken accessToken, AbstractRequest request) { + request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getAccessToken()); + } + + /** + * Returns the URL where you should redirect your users to authenticate your application. + * + * @return the URL where you should redirect your users + */ + public final String getAuthorizationUrl() { + return getAuthorizationUrl(null); + } + + /** + * Returns the URL where you should redirect your users to authenticate your application. + * + * @param additionalParams any additional GET params to add to the URL + * @return the URL where you should redirect your users + */ + public String getAuthorizationUrl(Map additionalParams) { + return api.getAuthorizationUrl(getConfig(), additionalParams); + } + + public DefaultApi20 getApi() { + return api; + } + + public OAuth2Authorization extractAuthorization(String redirectLocation) { + final OAuth2Authorization authorization = new OAuth2Authorization(); + for (String param : redirectLocation.substring(redirectLocation.indexOf('?') + 1).split("&")) { + final String[] keyValue = param.split("="); + if (keyValue.length == 2) { + switch (keyValue[0]) { + case "code": + authorization.setCode(keyValue[1]); + break; + case "state": + authorization.setState(keyValue[1]); + break; + default: //just ignore any other param; + } + } + } + return authorization; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuthService.java b/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuthService.java index 47b40b497..05c8ecac2 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuthService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuthService.java @@ -1,173 +1,173 @@ -package com.github.scribejava.core.oauth; - -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.model.AbstractRequest; -import static com.github.scribejava.core.model.AbstractRequest.DEFAULT_CONTENT_TYPE; -import com.github.scribejava.core.model.ForceTypeOfHttpRequest; -import com.github.scribejava.core.model.OAuthAsyncRequestCallback; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.OAuthRequestAsync; -import com.github.scribejava.core.model.ScribeJavaConfig; -import com.github.scribejava.core.model.Verb; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.Future; - -/** - * The main ScribeJava object. - * - * A facade responsible for the retrieval of request and access tokens and for the signing of HTTP requests. - */ -public abstract class OAuthService { - - private final OAuthConfig config; - private final com.ning.http.client.AsyncHttpClient ningAsyncHttpClient; - private final org.asynchttpclient.AsyncHttpClient ahcAsyncHttpClient; - - public OAuthService(OAuthConfig config) { - this.config = config; - final ForceTypeOfHttpRequest forceTypeOfHttpRequest = ScribeJavaConfig.getForceTypeOfHttpRequests(); - final com.ning.http.client.AsyncHttpClientConfig ningConfig = config.getNingAsyncHttpClientConfig(); - final org.asynchttpclient.AsyncHttpClientConfig ahcConfig = config.getAhcAsyncHttpClientConfig(); - - if (ningConfig == null && ahcConfig == null) { - if (ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - throw new OAuthException("Cannot use sync operations, only async"); - } - if (ForceTypeOfHttpRequest.PREFER_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - config.log("Cannot use sync operations, only async"); - } - ningAsyncHttpClient = null; - ahcAsyncHttpClient = null; - } else { - if (ForceTypeOfHttpRequest.FORCE_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - throw new OAuthException("Cannot use async operations, only sync"); - } - if (ForceTypeOfHttpRequest.PREFER_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { - config.log("Cannot use async operations, only sync"); - } - - if (ahcConfig == null) { - ningAsyncHttpClient = NingProvider.createClient(config.getNingAsyncHttpProviderClassName(), ningConfig); - ahcAsyncHttpClient = null; - } else { - ahcAsyncHttpClient = AHCProvider.createClient(ahcConfig); - ningAsyncHttpClient = null; - } - } - } - - public void closeAsyncClient() throws IOException { - if (ahcAsyncHttpClient == null) { - ningAsyncHttpClient.close(); - } else { - ahcAsyncHttpClient.close(); - } - } - - public OAuthConfig getConfig() { - return config; - } - - /** - * Returns the OAuth version of the service. - * - * @return OAuth version as string - */ - public abstract String getVersion(); - - public Future executeAsync(Map headers, Verb httpVerb, String completeUrl, - String bodyContents, OAuthAsyncRequestCallback callback, - OAuthRequestAsync.ResponseConverter converter) { - if (ahcAsyncHttpClient == null) { - return NingProvider.ningExecuteAsync(ningAsyncHttpClient, config.getUserAgent(), headers, httpVerb, - completeUrl, bodyContents, callback, converter); - } else { - return AHCProvider.ahcExecuteAsync(ahcAsyncHttpClient, config.getUserAgent(), headers, httpVerb, - completeUrl, bodyContents, callback, converter); - } - } - - private static class NingProvider { - - private static com.ning.http.client.AsyncHttpClient createClient(String ningAsyncHttpProviderClassName, - com.ning.http.client.AsyncHttpClientConfig ningConfig) { - return ningAsyncHttpProviderClassName == null - ? new com.ning.http.client.AsyncHttpClient(ningConfig) - : new com.ning.http.client.AsyncHttpClient(ningAsyncHttpProviderClassName, ningConfig); - } - - private static Future ningExecuteAsync(com.ning.http.client.AsyncHttpClient ningAsyncHttpClient, - String userAgent, Map headers, Verb httpVerb, String completeUrl, String bodyContents, - OAuthAsyncRequestCallback callback, OAuthRequestAsync.ResponseConverter converter) { - final com.ning.http.client.AsyncHttpClient.BoundRequestBuilder boundRequestBuilder; - switch (httpVerb) { - case GET: - boundRequestBuilder = ningAsyncHttpClient.prepareGet(completeUrl); - break; - case POST: - com.ning.http.client.AsyncHttpClient.BoundRequestBuilder requestBuilder - = ningAsyncHttpClient.preparePost(completeUrl); - if (!headers.containsKey(AbstractRequest.CONTENT_TYPE)) { - requestBuilder = requestBuilder.addHeader(AbstractRequest.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); - } - boundRequestBuilder = requestBuilder.setBody(bodyContents); - break; - default: - throw new IllegalArgumentException("message build error: unknown verb type"); - } - - for (Map.Entry header : headers.entrySet()) { - boundRequestBuilder.addHeader(header.getKey(), header.getValue()); - } - if (userAgent != null) { - boundRequestBuilder.setHeader(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); - } - - return boundRequestBuilder - .execute(new com.github.scribejava.core.async.ning.OAuthAsyncCompletionHandler<>( - callback, converter)); - } - } - - private static class AHCProvider { - - private static org.asynchttpclient.AsyncHttpClient createClient( - org.asynchttpclient.AsyncHttpClientConfig ahcConfig) { - return new org.asynchttpclient.DefaultAsyncHttpClient(ahcConfig); - } - - private static Future ahcExecuteAsync(org.asynchttpclient.AsyncHttpClient ahcAsyncHttpClient, - String userAgent, Map headers, Verb httpVerb, String completeUrl, String bodyContents, - OAuthAsyncRequestCallback callback, OAuthRequestAsync.ResponseConverter converter) { - final org.asynchttpclient.BoundRequestBuilder boundRequestBuilder; - switch (httpVerb) { - case GET: - boundRequestBuilder = ahcAsyncHttpClient.prepareGet(completeUrl); - break; - case POST: - org.asynchttpclient.BoundRequestBuilder requestBuilder - = ahcAsyncHttpClient.preparePost(completeUrl); - if (!headers.containsKey(AbstractRequest.CONTENT_TYPE)) { - requestBuilder = requestBuilder.addHeader(AbstractRequest.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); - } - boundRequestBuilder = requestBuilder.setBody(bodyContents); - break; - default: - throw new IllegalArgumentException("message build error: unknown verb type"); - } - - for (Map.Entry header : headers.entrySet()) { - boundRequestBuilder.addHeader(header.getKey(), header.getValue()); - } - if (userAgent != null) { - boundRequestBuilder.setHeader(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); - } - - return boundRequestBuilder - .execute(new com.github.scribejava.core.async.ahc.OAuthAsyncCompletionHandler<>( - callback, converter)); - } - } -} +package com.github.scribejava.core.oauth; + +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.model.AbstractRequest; +import static com.github.scribejava.core.model.AbstractRequest.DEFAULT_CONTENT_TYPE; +import com.github.scribejava.core.model.ForceTypeOfHttpRequest; +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.OAuthRequestAsync; +import com.github.scribejava.core.model.ScribeJavaConfig; +import com.github.scribejava.core.model.Verb; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.Future; + +/** + * The main ScribeJava object. + * + * A facade responsible for the retrieval of request and access tokens and for the signing of HTTP requests. + */ +public abstract class OAuthService { + + private final OAuthConfig config; + private final com.ning.http.client.AsyncHttpClient ningAsyncHttpClient; + private final org.asynchttpclient.AsyncHttpClient ahcAsyncHttpClient; + + public OAuthService(OAuthConfig config) { + this.config = config; + final ForceTypeOfHttpRequest forceTypeOfHttpRequest = ScribeJavaConfig.getForceTypeOfHttpRequests(); + final com.ning.http.client.AsyncHttpClientConfig ningConfig = config.getNingAsyncHttpClientConfig(); + final org.asynchttpclient.AsyncHttpClientConfig ahcConfig = config.getAhcAsyncHttpClientConfig(); + + if (ningConfig == null && ahcConfig == null) { + if (ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + throw new OAuthException("Cannot use sync operations, only async"); + } + if (ForceTypeOfHttpRequest.PREFER_ASYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + config.log("Cannot use sync operations, only async"); + } + ningAsyncHttpClient = null; + ahcAsyncHttpClient = null; + } else { + if (ForceTypeOfHttpRequest.FORCE_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + throw new OAuthException("Cannot use async operations, only sync"); + } + if (ForceTypeOfHttpRequest.PREFER_SYNC_ONLY_HTTP_REQUESTS == forceTypeOfHttpRequest) { + config.log("Cannot use async operations, only sync"); + } + + if (ahcConfig == null) { + ningAsyncHttpClient = NingProvider.createClient(config.getNingAsyncHttpProviderClassName(), ningConfig); + ahcAsyncHttpClient = null; + } else { + ahcAsyncHttpClient = AHCProvider.createClient(ahcConfig); + ningAsyncHttpClient = null; + } + } + } + + public void closeAsyncClient() throws IOException { + if (ahcAsyncHttpClient == null) { + ningAsyncHttpClient.close(); + } else { + ahcAsyncHttpClient.close(); + } + } + + public OAuthConfig getConfig() { + return config; + } + + /** + * Returns the OAuth version of the service. + * + * @return OAuth version as string + */ + public abstract String getVersion(); + + public Future executeAsync(Map headers, Verb httpVerb, String completeUrl, + String bodyContents, OAuthAsyncRequestCallback callback, + OAuthRequestAsync.ResponseConverter converter) { + if (ahcAsyncHttpClient == null) { + return NingProvider.ningExecuteAsync(ningAsyncHttpClient, config.getUserAgent(), headers, httpVerb, + completeUrl, bodyContents, callback, converter); + } else { + return AHCProvider.ahcExecuteAsync(ahcAsyncHttpClient, config.getUserAgent(), headers, httpVerb, + completeUrl, bodyContents, callback, converter); + } + } + + private static class NingProvider { + + private static com.ning.http.client.AsyncHttpClient createClient(String ningAsyncHttpProviderClassName, + com.ning.http.client.AsyncHttpClientConfig ningConfig) { + return ningAsyncHttpProviderClassName == null + ? new com.ning.http.client.AsyncHttpClient(ningConfig) + : new com.ning.http.client.AsyncHttpClient(ningAsyncHttpProviderClassName, ningConfig); + } + + private static Future ningExecuteAsync(com.ning.http.client.AsyncHttpClient ningAsyncHttpClient, + String userAgent, Map headers, Verb httpVerb, String completeUrl, String bodyContents, + OAuthAsyncRequestCallback callback, OAuthRequestAsync.ResponseConverter converter) { + final com.ning.http.client.AsyncHttpClient.BoundRequestBuilder boundRequestBuilder; + switch (httpVerb) { + case GET: + boundRequestBuilder = ningAsyncHttpClient.prepareGet(completeUrl); + break; + case POST: + com.ning.http.client.AsyncHttpClient.BoundRequestBuilder requestBuilder + = ningAsyncHttpClient.preparePost(completeUrl); + if (!headers.containsKey(AbstractRequest.CONTENT_TYPE)) { + requestBuilder = requestBuilder.addHeader(AbstractRequest.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); + } + boundRequestBuilder = requestBuilder.setBody(bodyContents); + break; + default: + throw new IllegalArgumentException("message build error: unknown verb type"); + } + + for (Map.Entry header : headers.entrySet()) { + boundRequestBuilder.addHeader(header.getKey(), header.getValue()); + } + if (userAgent != null) { + boundRequestBuilder.setHeader(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); + } + + return boundRequestBuilder + .execute(new com.github.scribejava.core.async.ning.OAuthAsyncCompletionHandler<>( + callback, converter)); + } + } + + private static class AHCProvider { + + private static org.asynchttpclient.AsyncHttpClient createClient( + org.asynchttpclient.AsyncHttpClientConfig ahcConfig) { + return new org.asynchttpclient.DefaultAsyncHttpClient(ahcConfig); + } + + private static Future ahcExecuteAsync(org.asynchttpclient.AsyncHttpClient ahcAsyncHttpClient, + String userAgent, Map headers, Verb httpVerb, String completeUrl, String bodyContents, + OAuthAsyncRequestCallback callback, OAuthRequestAsync.ResponseConverter converter) { + final org.asynchttpclient.BoundRequestBuilder boundRequestBuilder; + switch (httpVerb) { + case GET: + boundRequestBuilder = ahcAsyncHttpClient.prepareGet(completeUrl); + break; + case POST: + org.asynchttpclient.BoundRequestBuilder requestBuilder + = ahcAsyncHttpClient.preparePost(completeUrl); + if (!headers.containsKey(AbstractRequest.CONTENT_TYPE)) { + requestBuilder = requestBuilder.addHeader(AbstractRequest.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); + } + boundRequestBuilder = requestBuilder.setBody(bodyContents); + break; + default: + throw new IllegalArgumentException("message build error: unknown verb type"); + } + + for (Map.Entry header : headers.entrySet()) { + boundRequestBuilder.addHeader(header.getKey(), header.getValue()); + } + if (userAgent != null) { + boundRequestBuilder.setHeader(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); + } + + return boundRequestBuilder + .execute(new com.github.scribejava.core.async.ahc.OAuthAsyncCompletionHandler<>( + callback, converter)); + } + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/Base64Encoder.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/Base64Encoder.java index ab564941c..07588c597 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/Base64Encoder.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/Base64Encoder.java @@ -1,31 +1,31 @@ -package com.github.scribejava.core.services; - -public abstract class Base64Encoder { - - private static Base64Encoder instance; - - public static Base64Encoder getInstance() { - synchronized (Base64Encoder.class) { - if (instance == null) { - instance = createEncoderInstance(); - } - } - return instance; - } - - private static Base64Encoder createEncoderInstance() { - if (CommonsEncoder.isPresent()) { - return new CommonsEncoder(); - } else { - return new DatatypeConverterEncoder(); - } - } - - public static String type() { - return getInstance().getType(); - } - - public abstract String encode(byte[] bytes); - - public abstract String getType(); -} +package com.github.scribejava.core.services; + +public abstract class Base64Encoder { + + private static Base64Encoder instance; + + public static Base64Encoder getInstance() { + synchronized (Base64Encoder.class) { + if (instance == null) { + instance = createEncoderInstance(); + } + } + return instance; + } + + private static Base64Encoder createEncoderInstance() { + if (CommonsEncoder.isPresent()) { + return new CommonsEncoder(); + } else { + return new DatatypeConverterEncoder(); + } + } + + public static String type() { + return getInstance().getType(); + } + + public abstract String encode(byte[] bytes); + + public abstract String getType(); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/CommonsEncoder.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/CommonsEncoder.java index 6e2afa24d..614ee99e3 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/CommonsEncoder.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/CommonsEncoder.java @@ -1,31 +1,31 @@ -package com.github.scribejava.core.services; - -import java.io.UnsupportedEncodingException; -import org.apache.commons.codec.binary.Base64; -import com.github.scribejava.core.exceptions.OAuthSignatureException; - -public class CommonsEncoder extends Base64Encoder { - - @Override - public String encode(byte[] bytes) { - try { - return new String(Base64.encodeBase64(bytes), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new OAuthSignatureException("Can't perform base64 encoding", e); - } - } - - @Override - public String getType() { - return "CommonsCodec"; - } - - public static boolean isPresent() { - try { - Class.forName("org.apache.commons.codec.binary.Base64"); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } -} +package com.github.scribejava.core.services; + +import java.io.UnsupportedEncodingException; +import org.apache.commons.codec.binary.Base64; +import com.github.scribejava.core.exceptions.OAuthSignatureException; + +public class CommonsEncoder extends Base64Encoder { + + @Override + public String encode(byte[] bytes) { + try { + return new String(Base64.encodeBase64(bytes), "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new OAuthSignatureException("Can't perform base64 encoding", e); + } + } + + @Override + public String getType() { + return "CommonsCodec"; + } + + public static boolean isPresent() { + try { + Class.forName("org.apache.commons.codec.binary.Base64"); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/DatatypeConverterEncoder.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/DatatypeConverterEncoder.java index eee87714f..35d263035 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/DatatypeConverterEncoder.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/DatatypeConverterEncoder.java @@ -1,16 +1,16 @@ -package com.github.scribejava.core.services; - -import javax.xml.bind.DatatypeConverter; - -public class DatatypeConverterEncoder extends Base64Encoder { - - @Override - public String encode(byte[] bytes) { - return DatatypeConverter.printBase64Binary(bytes); - } - - @Override - public String getType() { - return "DatatypeConverter"; - } -} +package com.github.scribejava.core.services; + +import javax.xml.bind.DatatypeConverter; + +public class DatatypeConverterEncoder extends Base64Encoder { + + @Override + public String encode(byte[] bytes) { + return DatatypeConverter.printBase64Binary(bytes); + } + + @Override + public String getType() { + return "DatatypeConverter"; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/HMACSha1SignatureService.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/HMACSha1SignatureService.java index 824f488d7..7b0891f74 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/HMACSha1SignatureService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/HMACSha1SignatureService.java @@ -1,57 +1,57 @@ -package com.github.scribejava.core.services; - -import java.io.UnsupportedEncodingException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import com.github.scribejava.core.exceptions.OAuthSignatureException; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -/** - * HMAC-SHA1 implementation of {@link SignatureService} - */ -public class HMACSha1SignatureService implements SignatureService { - - private static final String EMPTY_STRING = ""; - private static final String CARRIAGE_RETURN = "\r\n"; - private static final String UTF8 = "UTF-8"; - private static final String HMAC_SHA1 = "HmacSHA1"; - private static final String METHOD = "HMAC-SHA1"; - - /** - * {@inheritDoc} - */ - @Override - public String getSignature(String baseString, String apiSecret, String tokenSecret) { - try { - Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string"); - Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); - return doSign(baseString, OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret)); - } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException | RuntimeException e) { - throw new OAuthSignatureException(baseString, e); - } - } - - private String doSign(String toSign, String keyString) throws UnsupportedEncodingException, - NoSuchAlgorithmException, InvalidKeyException { - final SecretKeySpec key = new SecretKeySpec(keyString.getBytes(UTF8), HMAC_SHA1); - final Mac mac = Mac.getInstance(HMAC_SHA1); - mac.init(key); - final byte[] bytes = mac.doFinal(toSign.getBytes(UTF8)); - return bytesToBase64String(bytes).replace(CARRIAGE_RETURN, EMPTY_STRING); - } - - private String bytesToBase64String(byte[] bytes) { - return Base64Encoder.getInstance().encode(bytes); - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignatureMethod() { - return METHOD; - } -} +package com.github.scribejava.core.services; + +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import com.github.scribejava.core.exceptions.OAuthSignatureException; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +/** + * HMAC-SHA1 implementation of {@link SignatureService} + */ +public class HMACSha1SignatureService implements SignatureService { + + private static final String EMPTY_STRING = ""; + private static final String CARRIAGE_RETURN = "\r\n"; + private static final String UTF8 = "UTF-8"; + private static final String HMAC_SHA1 = "HmacSHA1"; + private static final String METHOD = "HMAC-SHA1"; + + /** + * {@inheritDoc} + */ + @Override + public String getSignature(String baseString, String apiSecret, String tokenSecret) { + try { + Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string"); + Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); + return doSign(baseString, OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret)); + } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException | RuntimeException e) { + throw new OAuthSignatureException(baseString, e); + } + } + + private String doSign(String toSign, String keyString) throws UnsupportedEncodingException, + NoSuchAlgorithmException, InvalidKeyException { + final SecretKeySpec key = new SecretKeySpec(keyString.getBytes(UTF8), HMAC_SHA1); + final Mac mac = Mac.getInstance(HMAC_SHA1); + mac.init(key); + final byte[] bytes = mac.doFinal(toSign.getBytes(UTF8)); + return bytesToBase64String(bytes).replace(CARRIAGE_RETURN, EMPTY_STRING); + } + + private String bytesToBase64String(byte[] bytes) { + return Base64Encoder.getInstance().encode(bytes); + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignatureMethod() { + return METHOD; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/PlaintextSignatureService.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/PlaintextSignatureService.java index 33661f10a..4781666c2 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/PlaintextSignatureService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/PlaintextSignatureService.java @@ -1,34 +1,34 @@ -package com.github.scribejava.core.services; - -import com.github.scribejava.core.exceptions.OAuthSignatureException; -import com.github.scribejava.core.utils.OAuthEncoder; -import com.github.scribejava.core.utils.Preconditions; - -/** - * plaintext implementation of {@link SignatureService} - */ -public class PlaintextSignatureService implements SignatureService { - - private static final String METHOD = "PLAINTEXT"; - - /** - * {@inheritDoc} - */ - @Override - public String getSignature(String baseString, String apiSecret, String tokenSecret) { - try { - Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); - return OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret); - } catch (Exception e) { - throw new OAuthSignatureException(baseString, e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignatureMethod() { - return METHOD; - } -} +package com.github.scribejava.core.services; + +import com.github.scribejava.core.exceptions.OAuthSignatureException; +import com.github.scribejava.core.utils.OAuthEncoder; +import com.github.scribejava.core.utils.Preconditions; + +/** + * plaintext implementation of {@link SignatureService} + */ +public class PlaintextSignatureService implements SignatureService { + + private static final String METHOD = "PLAINTEXT"; + + /** + * {@inheritDoc} + */ + @Override + public String getSignature(String baseString, String apiSecret, String tokenSecret) { + try { + Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); + return OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret); + } catch (Exception e) { + throw new OAuthSignatureException(baseString, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignatureMethod() { + return METHOD; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/RSASha1SignatureService.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/RSASha1SignatureService.java index 78ecfa2a1..9b39ec4b7 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/RSASha1SignatureService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/RSASha1SignatureService.java @@ -1,53 +1,53 @@ -package com.github.scribejava.core.services; - -import java.security.PrivateKey; -import java.security.Signature; -import java.security.SignatureException; -import com.github.scribejava.core.exceptions.OAuthSignatureException; -import java.io.UnsupportedEncodingException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -/** - * A signature service that uses the RSA-SHA1 algorithm. - */ -public class RSASha1SignatureService implements SignatureService { - - private static final String METHOD = "RSA-SHA1"; - private static final String RSA_SHA1 = "SHA1withRSA"; - private static final String UTF8 = "UTF-8"; - - private final PrivateKey privateKey; - - public RSASha1SignatureService(PrivateKey privateKey) { - this.privateKey = privateKey; - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignature(String baseString, String apiSecret, String tokenSecret) { - try { - final Signature signature = Signature.getInstance(RSA_SHA1); - signature.initSign(privateKey); - signature.update(baseString.getBytes(UTF8)); - return bytesToBase64String(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | UnsupportedEncodingException | - RuntimeException e) { - throw new OAuthSignatureException(baseString, e); - } - } - - private String bytesToBase64String(Signature signature) throws SignatureException { - return Base64Encoder.getInstance().encode(signature.sign()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignatureMethod() { - return METHOD; - } -} +package com.github.scribejava.core.services; + +import java.security.PrivateKey; +import java.security.Signature; +import java.security.SignatureException; +import com.github.scribejava.core.exceptions.OAuthSignatureException; +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +/** + * A signature service that uses the RSA-SHA1 algorithm. + */ +public class RSASha1SignatureService implements SignatureService { + + private static final String METHOD = "RSA-SHA1"; + private static final String RSA_SHA1 = "SHA1withRSA"; + private static final String UTF8 = "UTF-8"; + + private final PrivateKey privateKey; + + public RSASha1SignatureService(PrivateKey privateKey) { + this.privateKey = privateKey; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignature(String baseString, String apiSecret, String tokenSecret) { + try { + final Signature signature = Signature.getInstance(RSA_SHA1); + signature.initSign(privateKey); + signature.update(baseString.getBytes(UTF8)); + return bytesToBase64String(signature); + } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | UnsupportedEncodingException | + RuntimeException e) { + throw new OAuthSignatureException(baseString, e); + } + } + + private String bytesToBase64String(Signature signature) throws SignatureException { + return Base64Encoder.getInstance().encode(signature.sign()); + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignatureMethod() { + return METHOD; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/SignatureService.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/SignatureService.java index cf821d089..926f8b28d 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/SignatureService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/SignatureService.java @@ -1,20 +1,20 @@ -package com.github.scribejava.core.services; - -/** - * Signs a base string, returning the OAuth signature - */ -public interface SignatureService { - - /** - * Returns the signature - * - * @param baseString url-encoded string to sign - * @param apiSecret api secret for your app - * @param tokenSecret token secret (empty string for the request token step) - * - * @return signature - */ - String getSignature(String baseString, String apiSecret, String tokenSecret); - - String getSignatureMethod(); -} +package com.github.scribejava.core.services; + +/** + * Signs a base string, returning the OAuth signature + */ +public interface SignatureService { + + /** + * Returns the signature + * + * @param baseString url-encoded string to sign + * @param apiSecret api secret for your app + * @param tokenSecret token secret (empty string for the request token step) + * + * @return signature + */ + String getSignature(String baseString, String apiSecret, String tokenSecret); + + String getSignatureMethod(); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampService.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampService.java index f062b640a..c8571d9d9 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampService.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampService.java @@ -1,23 +1,23 @@ -package com.github.scribejava.core.services; - -/** - * Unix epoch timestamp generator. - * - * This class is useful for stubbing in tests. - */ -public interface TimestampService { - - /** - * Returns the unix epoch timestamp in seconds - * - * @return timestamp - */ - String getTimestampInSeconds(); - - /** - * Returns a nonce (unique value for each request) - * - * @return nonce - */ - String getNonce(); -} +package com.github.scribejava.core.services; + +/** + * Unix epoch timestamp generator. + * + * This class is useful for stubbing in tests. + */ +public interface TimestampService { + + /** + * Returns the unix epoch timestamp in seconds + * + * @return timestamp + */ + String getTimestampInSeconds(); + + /** + * Returns a nonce (unique value for each request) + * + * @return nonce + */ + String getNonce(); +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampServiceImpl.java b/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampServiceImpl.java index 76109f10e..51d7a53aa 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampServiceImpl.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/services/TimestampServiceImpl.java @@ -1,60 +1,60 @@ -package com.github.scribejava.core.services; - -import java.util.Random; - -/** - * Implementation of {@link TimestampService} using plain java classes. - */ -public class TimestampServiceImpl implements TimestampService { - - private Timer timer; - - /** - * Default constructor. - */ - public TimestampServiceImpl() { - timer = new Timer(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getNonce() { - final Long ts = getTs(); - return String.valueOf(ts + timer.getRandomInteger()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getTimestampInSeconds() { - return String.valueOf(getTs()); - } - - private Long getTs() { - return timer.getMilis() / 1000; - } - - void setTimer(Timer timer) { - this.timer = timer; - } - - /** - * Inner class that uses {@link System} for generating the timestamps. - */ - static class Timer { - - private final Random rand = new Random(); - - Long getMilis() { - return System.currentTimeMillis(); - } - - Integer getRandomInteger() { - return rand.nextInt(); - } - } - -} +package com.github.scribejava.core.services; + +import java.util.Random; + +/** + * Implementation of {@link TimestampService} using plain java classes. + */ +public class TimestampServiceImpl implements TimestampService { + + private Timer timer; + + /** + * Default constructor. + */ + public TimestampServiceImpl() { + timer = new Timer(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getNonce() { + final Long ts = getTs(); + return String.valueOf(ts + timer.getRandomInteger()); + } + + /** + * {@inheritDoc} + */ + @Override + public String getTimestampInSeconds() { + return String.valueOf(getTs()); + } + + private Long getTs() { + return timer.getMilis() / 1000; + } + + void setTimer(Timer timer) { + this.timer = timer; + } + + /** + * Inner class that uses {@link System} for generating the timestamps. + */ + static class Timer { + + private final Random rand = new Random(); + + Long getMilis() { + return System.currentTimeMillis(); + } + + Integer getRandomInteger() { + return rand.nextInt(); + } + } + +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/utils/MapUtils.java b/scribejava-core/src/main/java/com/github/scribejava/core/utils/MapUtils.java index bf48341fb..272f5e9fd 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/utils/MapUtils.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/utils/MapUtils.java @@ -1,21 +1,21 @@ -package com.github.scribejava.core.utils; - -import java.util.Map; - -public abstract class MapUtils { - - public static String toString(Map map) { - if (map == null) { - return ""; - } - if (map.isEmpty()) { - return "{}"; - } - - final StringBuilder result = new StringBuilder(); - for (Map.Entry entry : map.entrySet()) { - result.append(String.format(", %s -> %s ", entry.getKey().toString(), entry.getValue().toString())); - } - return "{" + result.substring(1) + "}"; - } -} +package com.github.scribejava.core.utils; + +import java.util.Map; + +public abstract class MapUtils { + + public static String toString(Map map) { + if (map == null) { + return ""; + } + if (map.isEmpty()) { + return "{}"; + } + + final StringBuilder result = new StringBuilder(); + for (Map.Entry entry : map.entrySet()) { + result.append(String.format(", %s -> %s ", entry.getKey().toString(), entry.getValue().toString())); + } + return "{" + result.substring(1) + "}"; + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/utils/OAuthEncoder.java b/scribejava-core/src/main/java/com/github/scribejava/core/utils/OAuthEncoder.java index 83918e7af..d6eb921e8 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/utils/OAuthEncoder.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/utils/OAuthEncoder.java @@ -1,51 +1,51 @@ -package com.github.scribejava.core.utils; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; -import com.github.scribejava.core.exceptions.OAuthException; - -public abstract class OAuthEncoder { - - private static final String CHARSET = "UTF-8"; - private static final Map ENCODING_RULES; - - static { - final Map rules = new HashMap<>(); - rules.put("*", "%2A"); - rules.put("+", "%20"); - rules.put("%7E", "~"); - ENCODING_RULES = Collections.unmodifiableMap(rules); - } - - public static String encode(String plain) { - Preconditions.checkNotNull(plain, "Cannot encode null object"); - String encoded; - try { - encoded = URLEncoder.encode(plain, CHARSET); - } catch (UnsupportedEncodingException uee) { - throw new OAuthException("Charset not found while encoding string: " + CHARSET, uee); - } - for (Map.Entry rule : ENCODING_RULES.entrySet()) { - encoded = applyRule(encoded, rule.getKey(), rule.getValue()); - } - return encoded; - } - - private static String applyRule(String encoded, String toReplace, String replacement) { - return encoded.replaceAll(Pattern.quote(toReplace), replacement); - } - - public static String decode(String encoded) { - Preconditions.checkNotNull(encoded, "Cannot decode null object"); - try { - return URLDecoder.decode(encoded, CHARSET); - } catch (UnsupportedEncodingException uee) { - throw new OAuthException("Charset not found while decoding string: " + CHARSET, uee); - } - } -} +package com.github.scribejava.core.utils; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; +import com.github.scribejava.core.exceptions.OAuthException; + +public abstract class OAuthEncoder { + + private static final String CHARSET = "UTF-8"; + private static final Map ENCODING_RULES; + + static { + final Map rules = new HashMap<>(); + rules.put("*", "%2A"); + rules.put("+", "%20"); + rules.put("%7E", "~"); + ENCODING_RULES = Collections.unmodifiableMap(rules); + } + + public static String encode(String plain) { + Preconditions.checkNotNull(plain, "Cannot encode null object"); + String encoded; + try { + encoded = URLEncoder.encode(plain, CHARSET); + } catch (UnsupportedEncodingException uee) { + throw new OAuthException("Charset not found while encoding string: " + CHARSET, uee); + } + for (Map.Entry rule : ENCODING_RULES.entrySet()) { + encoded = applyRule(encoded, rule.getKey(), rule.getValue()); + } + return encoded; + } + + private static String applyRule(String encoded, String toReplace, String replacement) { + return encoded.replaceAll(Pattern.quote(toReplace), replacement); + } + + public static String decode(String encoded) { + Preconditions.checkNotNull(encoded, "Cannot decode null object"); + try { + return URLDecoder.decode(encoded, CHARSET); + } catch (UnsupportedEncodingException uee) { + throw new OAuthException("Charset not found while decoding string: " + CHARSET, uee); + } + } +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/utils/Preconditions.java b/scribejava-core/src/main/java/com/github/scribejava/core/utils/Preconditions.java index 0858fc89d..887d95e5f 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/utils/Preconditions.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/utils/Preconditions.java @@ -1,75 +1,75 @@ -package com.github.scribejava.core.utils; - -import java.util.Locale; -import java.util.regex.Pattern; -import com.github.scribejava.core.model.OAuthConstants; - -/** - * Utils for checking preconditions and invariants - */ -public abstract class Preconditions { - - private static final String DEFAULT_MESSAGE = "Received an invalid parameter"; - - // scheme = alpha *( alpha | digit | "+" | "-" | "." ) - private static final String URL_REGEXP = "^[a-zA-Z][a-zA-Z0-9+.-]*://\\S+"; - - /** - * Checks that an object is not null. - * - * @param object any object - * @param errorMsg error message - * - * @throws IllegalArgumentException if the object is null - */ - public static void checkNotNull(Object object, String errorMsg) { - check(object != null, errorMsg); - } - - /** - * Checks that a string is not null or empty - * - * @param string any string - * @param errorMsg error message - * - * @throws IllegalArgumentException if the string is null or empty - */ - public static void checkEmptyString(String string, String errorMsg) { - check(string != null && !string.trim().isEmpty(), errorMsg); - } - - /** - * Checks that a URL is valid - * - * @param url any string - * @param errorMsg error message - */ - public static void checkValidUrl(String url, String errorMsg) { - checkEmptyString(url, errorMsg); - check(isUrl(url), errorMsg); - } - - /** - * Checks that a URL is a valid OAuth callback - * - * @param url any string - * @param errorMsg error message - */ - public static void checkValidOAuthCallback(String url, String errorMsg) { - checkEmptyString(url, errorMsg); - if (url.toLowerCase(Locale.getDefault()).compareToIgnoreCase(OAuthConstants.OUT_OF_BAND) != 0) { - check(isUrl(url), errorMsg); - } - } - - private static boolean isUrl(String url) { - return Pattern.compile(URL_REGEXP).matcher(url).matches(); - } - - private static void check(boolean requirements, String error) { - if (!requirements) { - throw new IllegalArgumentException(error == null || error.trim().length() <= 0 ? DEFAULT_MESSAGE : error); - } - } - -} +package com.github.scribejava.core.utils; + +import java.util.Locale; +import java.util.regex.Pattern; +import com.github.scribejava.core.model.OAuthConstants; + +/** + * Utils for checking preconditions and invariants + */ +public abstract class Preconditions { + + private static final String DEFAULT_MESSAGE = "Received an invalid parameter"; + + // scheme = alpha *( alpha | digit | "+" | "-" | "." ) + private static final String URL_REGEXP = "^[a-zA-Z][a-zA-Z0-9+.-]*://\\S+"; + + /** + * Checks that an object is not null. + * + * @param object any object + * @param errorMsg error message + * + * @throws IllegalArgumentException if the object is null + */ + public static void checkNotNull(Object object, String errorMsg) { + check(object != null, errorMsg); + } + + /** + * Checks that a string is not null or empty + * + * @param string any string + * @param errorMsg error message + * + * @throws IllegalArgumentException if the string is null or empty + */ + public static void checkEmptyString(String string, String errorMsg) { + check(string != null && !string.trim().isEmpty(), errorMsg); + } + + /** + * Checks that a URL is valid + * + * @param url any string + * @param errorMsg error message + */ + public static void checkValidUrl(String url, String errorMsg) { + checkEmptyString(url, errorMsg); + check(isUrl(url), errorMsg); + } + + /** + * Checks that a URL is a valid OAuth callback + * + * @param url any string + * @param errorMsg error message + */ + public static void checkValidOAuthCallback(String url, String errorMsg) { + checkEmptyString(url, errorMsg); + if (url.toLowerCase(Locale.getDefault()).compareToIgnoreCase(OAuthConstants.OUT_OF_BAND) != 0) { + check(isUrl(url), errorMsg); + } + } + + private static boolean isUrl(String url) { + return Pattern.compile(URL_REGEXP).matcher(url).matches(); + } + + private static void check(boolean requirements, String error) { + if (!requirements) { + throw new IllegalArgumentException(error == null || error.trim().length() <= 0 ? DEFAULT_MESSAGE : error); + } + } + +} diff --git a/scribejava-core/src/main/java/com/github/scribejava/core/utils/StreamUtils.java b/scribejava-core/src/main/java/com/github/scribejava/core/utils/StreamUtils.java index 7a86318d2..e17437c94 100644 --- a/scribejava-core/src/main/java/com/github/scribejava/core/utils/StreamUtils.java +++ b/scribejava-core/src/main/java/com/github/scribejava/core/utils/StreamUtils.java @@ -1,49 +1,49 @@ -package com.github.scribejava.core.utils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.zip.GZIPInputStream; - -/** - * Utils to deal with Streams. - */ -public abstract class StreamUtils { - - /** - * Returns the stream contents as an UTF-8 encoded string - * - * @param is input stream - * @return string contents - * @throws java.io.IOException in any. SocketTimeout in example - */ - public static String getStreamContents(InputStream is) throws IOException { - Preconditions.checkNotNull(is, "Cannot get String from a null object"); - final char[] buffer = new char[0x10000]; - final StringBuilder out = new StringBuilder(); - try (Reader in = new InputStreamReader(is, "UTF-8")) { - int read; - do { - read = in.read(buffer, 0, buffer.length); - if (read > 0) { - out.append(buffer, 0, read); - } - } while (read >= 0); - } - return out.toString(); - } - - /** - * Return String content from a gzip stream - * - * @param is input stream - * @return string contents - * @throws java.io.IOException in any. SocketTimeout in example - */ - public static String getGzipStreamContents(InputStream is) throws IOException { - Preconditions.checkNotNull(is, "Cannot get String from a null object"); - final GZIPInputStream gis = new GZIPInputStream(is); - return getStreamContents(gis); - } -} +package com.github.scribejava.core.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.zip.GZIPInputStream; + +/** + * Utils to deal with Streams. + */ +public abstract class StreamUtils { + + /** + * Returns the stream contents as an UTF-8 encoded string + * + * @param is input stream + * @return string contents + * @throws java.io.IOException in any. SocketTimeout in example + */ + public static String getStreamContents(InputStream is) throws IOException { + Preconditions.checkNotNull(is, "Cannot get String from a null object"); + final char[] buffer = new char[0x10000]; + final StringBuilder out = new StringBuilder(); + try (Reader in = new InputStreamReader(is, "UTF-8")) { + int read; + do { + read = in.read(buffer, 0, buffer.length); + if (read > 0) { + out.append(buffer, 0, read); + } + } while (read >= 0); + } + return out.toString(); + } + + /** + * Return String content from a gzip stream + * + * @param is input stream + * @return string contents + * @throws java.io.IOException in any. SocketTimeout in example + */ + public static String getGzipStreamContents(InputStream is) throws IOException { + Preconditions.checkNotNull(is, "Cannot get String from a null object"); + final GZIPInputStream gis = new GZIPInputStream(is); + return getStreamContents(gis); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/ObjectMother.java b/scribejava-core/src/test/java/com/github/scribejava/core/ObjectMother.java index 30482b2c6..4987a1afb 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/ObjectMother.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/ObjectMother.java @@ -1,70 +1,70 @@ -package com.github.scribejava.core; - -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthConstants; -import com.github.scribejava.core.model.OAuthRequest; -import com.github.scribejava.core.model.Verb; -import com.github.scribejava.core.oauth.OAuth20Service; - -public abstract class ObjectMother { - - public static OAuthRequest createSampleOAuthRequest() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); - return request; - } - - public static OAuthRequest createSampleOAuthRequestPort80() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com:80", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); - return request; - } - - public static OAuthRequest createSampleOAuthRequestPort80v2() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com:80/test", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); - return request; - } - - public static OAuthRequest createSampleOAuthRequestPort8080() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com:8080", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); - return request; - } - - public static OAuthRequest createSampleOAuthRequestPort443() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "https://example.com:443", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); - return request; - } - - public static OAuthRequest createSampleOAuthRequestPort443v2() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "https://example.com:443/test", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); - return request; - } -} +package com.github.scribejava.core; + +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthConstants; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; + +public abstract class ObjectMother { + + public static OAuthRequest createSampleOAuthRequest() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + return request; + } + + public static OAuthRequest createSampleOAuthRequestPort80() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com:80", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + return request; + } + + public static OAuthRequest createSampleOAuthRequestPort80v2() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com:80/test", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + return request; + } + + public static OAuthRequest createSampleOAuthRequestPort8080() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com:8080", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + return request; + } + + public static OAuthRequest createSampleOAuthRequestPort443() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "https://example.com:443", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + return request; + } + + public static OAuthRequest createSampleOAuthRequestPort443v2() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "https://example.com:443/test", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + return request; + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/BaseStringExtractorTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/BaseStringExtractorTest.java index 3eb4b7404..52fc015d9 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/BaseStringExtractorTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/BaseStringExtractorTest.java @@ -1,108 +1,108 @@ -package com.github.scribejava.core.extractors; - -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.ObjectMother; -import com.github.scribejava.core.exceptions.OAuthParametersMissingException; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthRequest; -import com.github.scribejava.core.model.Verb; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class BaseStringExtractorTest { - - private BaseStringExtractorImpl extractor; - private OAuthRequest request; - private OAuthRequest requestPort80; - private OAuthRequest requestPort80v2; - private OAuthRequest requestPort8080; - private OAuthRequest requestPort443; - private OAuthRequest requestPort443v2; - - @Before - public void setUp() { - request = ObjectMother.createSampleOAuthRequest(); - requestPort80 = ObjectMother.createSampleOAuthRequestPort80(); - requestPort80v2 = ObjectMother.createSampleOAuthRequestPort80v2(); - requestPort8080 = ObjectMother.createSampleOAuthRequestPort8080(); - requestPort443 = ObjectMother.createSampleOAuthRequestPort443(); - requestPort443v2 = ObjectMother.createSampleOAuthRequestPort443v2(); - extractor = new BaseStringExtractorImpl(); - } - - @Test - public void shouldExtractBaseStringFromOAuthRequest() { - final String expected = "GET&http%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback" - + "%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature" - + "%26oauth_timestamp%3D123456"; - final String baseString = extractor.extract(request); - assertEquals(expected, baseString); - } - - @Test - public void shouldExcludePort80() { - final String expected = "GET&http%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback" - + "%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature" - + "%26oauth_timestamp%3D123456"; - final String baseString = extractor.extract(requestPort80); - assertEquals(expected, baseString); - } - - @Test - public void shouldExcludePort80v2() { - final String expected = "GET&http%3A%2F%2Fexample.com%2Ftest&oauth_callback%3Dhttp%253A%252F%252Fexample" - + "%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature" - + "%3DOAuth-Signature%26oauth_timestamp%3D123456"; - final String baseString = extractor.extract(requestPort80v2); - assertEquals(expected, baseString); - } - - @Test - public void shouldIncludePort8080() { - final String expected = "GET&http%3A%2F%2Fexample.com%3A8080&oauth_callback%3Dhttp%253A%252F%252Fexample" - + "%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature" - + "%3DOAuth-Signature%26oauth_timestamp%3D123456"; - final String baseString = extractor.extract(requestPort8080); - assertEquals(expected, baseString); - } - - @Test - public void shouldExcludePort443() { - final String expected = "GET&https%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback" - + "%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature" - + "%26oauth_timestamp%3D123456"; - final String baseString = extractor.extract(requestPort443); - assertEquals(expected, baseString); - } - - @Test - public void shouldExcludePort443v2() { - final String expected = "GET&https%3A%2F%2Fexample.com%2Ftest&oauth_callback%3Dhttp%253A%252F%252Fexample" - + "%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature" - + "%3DOAuth-Signature%26oauth_timestamp%3D123456"; - final String baseString = extractor.extract(requestPort443v2); - assertEquals(expected, baseString); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfRquestIsNull() { - extractor.extract(null); - } - - @Test(expected = OAuthParametersMissingException.class) - public void shouldThrowExceptionIfRquestHasNoOAuthParameters() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - extractor.extract(request); - } - - @Test - public void shouldProperlyEncodeSpaces() { - final String expected = "GET&http%3A%2F%2Fexample.com&body%3Dthis%2520param%2520has%2520whitespace" - + "%26oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback%26oauth_consumer_key" - + "%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature%26oauth_timestamp%3D123456"; - request.addBodyParameter("body", "this param has whitespace"); - assertEquals(expected, extractor.extract(request)); - } -} +package com.github.scribejava.core.extractors; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.ObjectMother; +import com.github.scribejava.core.exceptions.OAuthParametersMissingException; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class BaseStringExtractorTest { + + private BaseStringExtractorImpl extractor; + private OAuthRequest request; + private OAuthRequest requestPort80; + private OAuthRequest requestPort80v2; + private OAuthRequest requestPort8080; + private OAuthRequest requestPort443; + private OAuthRequest requestPort443v2; + + @Before + public void setUp() { + request = ObjectMother.createSampleOAuthRequest(); + requestPort80 = ObjectMother.createSampleOAuthRequestPort80(); + requestPort80v2 = ObjectMother.createSampleOAuthRequestPort80v2(); + requestPort8080 = ObjectMother.createSampleOAuthRequestPort8080(); + requestPort443 = ObjectMother.createSampleOAuthRequestPort443(); + requestPort443v2 = ObjectMother.createSampleOAuthRequestPort443v2(); + extractor = new BaseStringExtractorImpl(); + } + + @Test + public void shouldExtractBaseStringFromOAuthRequest() { + final String expected = "GET&http%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback" + + "%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature" + + "%26oauth_timestamp%3D123456"; + final String baseString = extractor.extract(request); + assertEquals(expected, baseString); + } + + @Test + public void shouldExcludePort80() { + final String expected = "GET&http%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback" + + "%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature" + + "%26oauth_timestamp%3D123456"; + final String baseString = extractor.extract(requestPort80); + assertEquals(expected, baseString); + } + + @Test + public void shouldExcludePort80v2() { + final String expected = "GET&http%3A%2F%2Fexample.com%2Ftest&oauth_callback%3Dhttp%253A%252F%252Fexample" + + "%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature" + + "%3DOAuth-Signature%26oauth_timestamp%3D123456"; + final String baseString = extractor.extract(requestPort80v2); + assertEquals(expected, baseString); + } + + @Test + public void shouldIncludePort8080() { + final String expected = "GET&http%3A%2F%2Fexample.com%3A8080&oauth_callback%3Dhttp%253A%252F%252Fexample" + + "%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature" + + "%3DOAuth-Signature%26oauth_timestamp%3D123456"; + final String baseString = extractor.extract(requestPort8080); + assertEquals(expected, baseString); + } + + @Test + public void shouldExcludePort443() { + final String expected = "GET&https%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback" + + "%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature" + + "%26oauth_timestamp%3D123456"; + final String baseString = extractor.extract(requestPort443); + assertEquals(expected, baseString); + } + + @Test + public void shouldExcludePort443v2() { + final String expected = "GET&https%3A%2F%2Fexample.com%2Ftest&oauth_callback%3Dhttp%253A%252F%252Fexample" + + "%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature" + + "%3DOAuth-Signature%26oauth_timestamp%3D123456"; + final String baseString = extractor.extract(requestPort443v2); + assertEquals(expected, baseString); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfRquestIsNull() { + extractor.extract(null); + } + + @Test(expected = OAuthParametersMissingException.class) + public void shouldThrowExceptionIfRquestHasNoOAuthParameters() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + extractor.extract(request); + } + + @Test + public void shouldProperlyEncodeSpaces() { + final String expected = "GET&http%3A%2F%2Fexample.com&body%3Dthis%2520param%2520has%2520whitespace" + + "%26oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback%26oauth_consumer_key" + + "%3DAS%2523%2524%255E%252A%2540%2526%26oauth_signature%3DOAuth-Signature%26oauth_timestamp%3D123456"; + request.addBodyParameter("body", "this param has whitespace"); + assertEquals(expected, extractor.extract(request)); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/HeaderExtractorTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/HeaderExtractorTest.java index 8de9d5c50..ce4731cd1 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/HeaderExtractorTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/HeaderExtractorTest.java @@ -1,50 +1,50 @@ -package com.github.scribejava.core.extractors; - -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.exceptions.OAuthParametersMissingException; -import com.github.scribejava.core.model.OAuthConfig; -import com.github.scribejava.core.model.OAuthRequest; -import com.github.scribejava.core.model.Verb; -import com.github.scribejava.core.oauth.OAuth20Service; -import com.github.scribejava.core.ObjectMother; - -public class HeaderExtractorTest { - - private HeaderExtractorImpl extractor; - private OAuthRequest request; - - @Before - public void setUp() { - request = ObjectMother.createSampleOAuthRequest(); - extractor = new HeaderExtractorImpl(); - } - - @Test - public void shouldExtractStandardHeader() { - final String header = extractor.extract(request); - try { - assertEquals("OAuth oauth_callback=\"http%3A%2F%2Fexample%2Fcallback\", " - + "oauth_signature=\"OAuth-Signature\", oauth_consumer_key=\"AS%23%24%5E%2A%40%26\", " - + "oauth_timestamp=\"123456\"", header); - } catch (AssertionError ae) { - //maybe this is OpenJDK 8? Different order of elements in HashMap while iterating'em. - assertEquals("OAuth oauth_signature=\"OAuth-Signature\", " - + "oauth_callback=\"http%3A%2F%2Fexample%2Fcallback\", " - + "oauth_consumer_key=\"AS%23%24%5E%2A%40%26\", oauth_timestamp=\"123456\"", header); - } - } - - @Test(expected = IllegalArgumentException.class) - public void shouldExceptionIfRequestIsNull() { - extractor.extract(null); - } - - @Test(expected = OAuthParametersMissingException.class) - public void shouldExceptionIfRequestHasNoOAuthParams() { - final OAuthRequest emptyRequest = new OAuthRequest(Verb.GET, "http://example.com", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - extractor.extract(emptyRequest); - } -} +package com.github.scribejava.core.extractors; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.exceptions.OAuthParametersMissingException; +import com.github.scribejava.core.model.OAuthConfig; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth20Service; +import com.github.scribejava.core.ObjectMother; + +public class HeaderExtractorTest { + + private HeaderExtractorImpl extractor; + private OAuthRequest request; + + @Before + public void setUp() { + request = ObjectMother.createSampleOAuthRequest(); + extractor = new HeaderExtractorImpl(); + } + + @Test + public void shouldExtractStandardHeader() { + final String header = extractor.extract(request); + try { + assertEquals("OAuth oauth_callback=\"http%3A%2F%2Fexample%2Fcallback\", " + + "oauth_signature=\"OAuth-Signature\", oauth_consumer_key=\"AS%23%24%5E%2A%40%26\", " + + "oauth_timestamp=\"123456\"", header); + } catch (AssertionError ae) { + //maybe this is OpenJDK 8? Different order of elements in HashMap while iterating'em. + assertEquals("OAuth oauth_signature=\"OAuth-Signature\", " + + "oauth_callback=\"http%3A%2F%2Fexample%2Fcallback\", " + + "oauth_consumer_key=\"AS%23%24%5E%2A%40%26\", oauth_timestamp=\"123456\"", header); + } + } + + @Test(expected = IllegalArgumentException.class) + public void shouldExceptionIfRequestIsNull() { + extractor.extract(null); + } + + @Test(expected = OAuthParametersMissingException.class) + public void shouldExceptionIfRequestHasNoOAuthParams() { + final OAuthRequest emptyRequest = new OAuthRequest(Verb.GET, "http://example.com", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + extractor.extract(emptyRequest); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractorTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractorTest.java index 7cf3feb95..0436d1507 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractorTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth1AccessTokenExtractorTest.java @@ -1,73 +1,73 @@ -package com.github.scribejava.core.extractors; - -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.model.OAuth1Token; -import static org.junit.Assert.assertEquals; - -public class OAuth1AccessTokenExtractorTest { - - private OAuth1AccessTokenExtractor extractor; - - @Before - public void setUp() { - extractor = OAuth1AccessTokenExtractor.instance(); - } - - @Test - public void shouldExtractTokenFromOAuthStandardResponse() { - final String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03"; - final OAuth1Token extracted = extractor.extract(response); - assertEquals("hh5s93j4hdidpola", extracted.getToken()); - assertEquals("hdhd0244k9j7ao03", extracted.getTokenSecret()); - } - - @Test - public void shouldExtractTokenFromInvertedOAuthStandardResponse() { - final String response = "oauth_token_secret=hh5s93j4hdidpola&oauth_token=hdhd0244k9j7ao03"; - final OAuth1Token extracted = extractor.extract(response); - assertEquals("hh5s93j4hdidpola", extracted.getTokenSecret()); - assertEquals("hdhd0244k9j7ao03", extracted.getToken()); - } - - @Test - public void shouldExtractTokenFromResponseWithCallbackConfirmed() { - final String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03" - + "&callback_confirmed=true"; - final OAuth1Token extracted = extractor.extract(response); - assertEquals("hh5s93j4hdidpola", extracted.getToken()); - assertEquals("hdhd0244k9j7ao03", extracted.getTokenSecret()); - } - - @Test - public void shouldExtractTokenWithEmptySecret() { - final String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret="; - final OAuth1Token extracted = extractor.extract(response); - assertEquals("hh5s93j4hdidpola", extracted.getToken()); - assertEquals("", extracted.getTokenSecret()); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfTokenIsAbsent() { - final String response = "oauth_secret=hh5s93j4hdidpola&callback_confirmed=true"; - extractor.extract(response); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfSecretIsAbsent() { - final String response = "oauth_token=hh5s93j4hdidpola&callback_confirmed=true"; - extractor.extract(response); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfResponseIsNull() { - extractor.extract(null); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfResponseIsEmptyString() { - final String response = ""; - extractor.extract(response); - } -} +package com.github.scribejava.core.extractors; + +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.model.OAuth1Token; +import static org.junit.Assert.assertEquals; + +public class OAuth1AccessTokenExtractorTest { + + private OAuth1AccessTokenExtractor extractor; + + @Before + public void setUp() { + extractor = OAuth1AccessTokenExtractor.instance(); + } + + @Test + public void shouldExtractTokenFromOAuthStandardResponse() { + final String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03"; + final OAuth1Token extracted = extractor.extract(response); + assertEquals("hh5s93j4hdidpola", extracted.getToken()); + assertEquals("hdhd0244k9j7ao03", extracted.getTokenSecret()); + } + + @Test + public void shouldExtractTokenFromInvertedOAuthStandardResponse() { + final String response = "oauth_token_secret=hh5s93j4hdidpola&oauth_token=hdhd0244k9j7ao03"; + final OAuth1Token extracted = extractor.extract(response); + assertEquals("hh5s93j4hdidpola", extracted.getTokenSecret()); + assertEquals("hdhd0244k9j7ao03", extracted.getToken()); + } + + @Test + public void shouldExtractTokenFromResponseWithCallbackConfirmed() { + final String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03" + + "&callback_confirmed=true"; + final OAuth1Token extracted = extractor.extract(response); + assertEquals("hh5s93j4hdidpola", extracted.getToken()); + assertEquals("hdhd0244k9j7ao03", extracted.getTokenSecret()); + } + + @Test + public void shouldExtractTokenWithEmptySecret() { + final String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret="; + final OAuth1Token extracted = extractor.extract(response); + assertEquals("hh5s93j4hdidpola", extracted.getToken()); + assertEquals("", extracted.getTokenSecret()); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfTokenIsAbsent() { + final String response = "oauth_secret=hh5s93j4hdidpola&callback_confirmed=true"; + extractor.extract(response); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfSecretIsAbsent() { + final String response = "oauth_token=hh5s93j4hdidpola&callback_confirmed=true"; + extractor.extract(response); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfResponseIsNull() { + extractor.extract(null); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfResponseIsEmptyString() { + final String response = ""; + extractor.extract(response); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractorTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractorTest.java index fa66956d5..3425ef5fd 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractorTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenExtractorTest.java @@ -1,72 +1,72 @@ -package com.github.scribejava.core.extractors; - -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.model.OAuth2AccessToken; -import static org.junit.Assert.assertEquals; - -public class OAuth2AccessTokenExtractorTest { - - private OAuth2AccessTokenExtractor extractor; - - @Before - public void setUp() { - extractor = OAuth2AccessTokenExtractor.instance(); - } - - @Test - public void shouldExtractTokenFromOAuthStandardResponse() { - final String response = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" - + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE"; - final OAuth2AccessToken extracted = extractor.extract(response); - assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", - extracted.getAccessToken()); - } - - @Test - public void shouldExtractTokenFromResponseWithExpiresParam() { - final String response = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" - + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108"; - final OAuth2AccessToken extracted = extractor.extract(response); - assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", - extracted.getAccessToken()); - assertEquals(Integer.valueOf(5108), extracted.getExpiresIn()); - } - - @Test - public void shouldExtractTokenFromResponseWithExpiresAndRefreshParam() { - final String response = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" - + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108&token_type=bearer&refresh_token=166942940015970"; - final OAuth2AccessToken extracted = extractor.extract(response); - assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", - extracted.getAccessToken()); - assertEquals(Integer.valueOf(5108), extracted.getExpiresIn()); - assertEquals("bearer", extracted.getTokenType()); - assertEquals("166942940015970", extracted.getRefreshToken()); - } - - @Test - public void shouldExtractTokenFromResponseWithManyParameters() { - final String response = "access_token=foo1234&other_stuff=yeah_we_have_this_too&number=42"; - final OAuth2AccessToken extracted = extractor.extract(response); - assertEquals("foo1234", extracted.getAccessToken()); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfTokenIsAbsent() { - final String response = "&expires=5108"; - extractor.extract(response); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfResponseIsNull() { - extractor.extract(null); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfResponseIsEmptyString() { - final String response = ""; - extractor.extract(response); - } -} +package com.github.scribejava.core.extractors; + +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.model.OAuth2AccessToken; +import static org.junit.Assert.assertEquals; + +public class OAuth2AccessTokenExtractorTest { + + private OAuth2AccessTokenExtractor extractor; + + @Before + public void setUp() { + extractor = OAuth2AccessTokenExtractor.instance(); + } + + @Test + public void shouldExtractTokenFromOAuthStandardResponse() { + final String response = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE"; + final OAuth2AccessToken extracted = extractor.extract(response); + assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", + extracted.getAccessToken()); + } + + @Test + public void shouldExtractTokenFromResponseWithExpiresParam() { + final String response = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108"; + final OAuth2AccessToken extracted = extractor.extract(response); + assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", + extracted.getAccessToken()); + assertEquals(Integer.valueOf(5108), extracted.getExpiresIn()); + } + + @Test + public void shouldExtractTokenFromResponseWithExpiresAndRefreshParam() { + final String response = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108&token_type=bearer&refresh_token=166942940015970"; + final OAuth2AccessToken extracted = extractor.extract(response); + assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", + extracted.getAccessToken()); + assertEquals(Integer.valueOf(5108), extracted.getExpiresIn()); + assertEquals("bearer", extracted.getTokenType()); + assertEquals("166942940015970", extracted.getRefreshToken()); + } + + @Test + public void shouldExtractTokenFromResponseWithManyParameters() { + final String response = "access_token=foo1234&other_stuff=yeah_we_have_this_too&number=42"; + final OAuth2AccessToken extracted = extractor.extract(response); + assertEquals("foo1234", extracted.getAccessToken()); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfTokenIsAbsent() { + final String response = "&expires=5108"; + extractor.extract(response); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfResponseIsNull() { + extractor.extract(null); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfResponseIsEmptyString() { + final String response = ""; + extractor.extract(response); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractorTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractorTest.java index 9b2098e6c..abeda3432 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractorTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/extractors/OAuth2AccessTokenJsonExtractorTest.java @@ -1,27 +1,27 @@ -package com.github.scribejava.core.extractors; - -import com.github.scribejava.core.model.OAuth2AccessToken; -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class OAuth2AccessTokenJsonExtractorTest { - - private static final String RESPONSE = "'{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X\"}'"; - private final OAuth2AccessTokenJsonExtractor extractor = OAuth2AccessTokenJsonExtractor.instance(); - - @Test - public void shouldParseResponse() { - final OAuth2AccessToken token = extractor.extract(RESPONSE); - assertEquals(token.getAccessToken(), "I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X"); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfForNullParameters() { - extractor.extract(null); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfForEmptyStrings() { - extractor.extract(""); - } -} +package com.github.scribejava.core.extractors; + +import com.github.scribejava.core.model.OAuth2AccessToken; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class OAuth2AccessTokenJsonExtractorTest { + + private static final String RESPONSE = "'{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X\"}'"; + private final OAuth2AccessTokenJsonExtractor extractor = OAuth2AccessTokenJsonExtractor.instance(); + + @Test + public void shouldParseResponse() { + final OAuth2AccessToken token = extractor.extract(RESPONSE); + assertEquals(token.getAccessToken(), "I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfForNullParameters() { + extractor.extract(null); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfForEmptyStrings() { + extractor.extract(""); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/model/ConnectionStub.java b/scribejava-core/src/test/java/com/github/scribejava/core/model/ConnectionStub.java index b7465527d..83bc51939 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/model/ConnectionStub.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/model/ConnectionStub.java @@ -1,84 +1,84 @@ -package com.github.scribejava.core.model; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ConnectionStub extends HttpURLConnection { - - private final Map headers = new HashMap<>(); - private final Map> responseHeaders = new HashMap<>(); - private int inputStreamCalled; - - public ConnectionStub() throws MalformedURLException { - super(new URL("http://example.com")); - } - - @Override - public void setRequestProperty(String key, String value) { - headers.put(key, value); - } - - @Override - public String getRequestProperty(String s) { - return headers.get(s); - } - - public Map getHeaders() { - return headers; - } - - @Override - public int getResponseCode() throws IOException { - return 200; - } - - @Override - public InputStream getInputStream() throws IOException { - inputStreamCalled++; - return new ByteArrayInputStream("contents".getBytes()); - } - - public int getTimesCalledInpuStream() { - return inputStreamCalled; - } - - @Override - public OutputStream getOutputStream() throws IOException { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write("contents".getBytes()); - return baos; - } - - @Override - public Map> getHeaderFields() { - return responseHeaders; - } - - public void addResponseHeader(String key, String value) { - responseHeaders.put(key, Arrays.asList(value)); - } - - @Override - public void connect() { - } - - @Override - public void disconnect() { - } - - @Override - public boolean usingProxy() { - return false; - } - -} +package com.github.scribejava.core.model; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ConnectionStub extends HttpURLConnection { + + private final Map headers = new HashMap<>(); + private final Map> responseHeaders = new HashMap<>(); + private int inputStreamCalled; + + public ConnectionStub() throws MalformedURLException { + super(new URL("http://example.com")); + } + + @Override + public void setRequestProperty(String key, String value) { + headers.put(key, value); + } + + @Override + public String getRequestProperty(String s) { + return headers.get(s); + } + + public Map getHeaders() { + return headers; + } + + @Override + public int getResponseCode() throws IOException { + return 200; + } + + @Override + public InputStream getInputStream() throws IOException { + inputStreamCalled++; + return new ByteArrayInputStream("contents".getBytes()); + } + + public int getTimesCalledInpuStream() { + return inputStreamCalled; + } + + @Override + public OutputStream getOutputStream() throws IOException { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + baos.write("contents".getBytes()); + return baos; + } + + @Override + public Map> getHeaderFields() { + return responseHeaders; + } + + public void addResponseHeader(String key, String value) { + responseHeaders.put(key, Arrays.asList(value)); + } + + @Override + public void connect() { + } + + @Override + public void disconnect() { + } + + @Override + public boolean usingProxy() { + return false; + } + +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/model/ForceTypeOfHttpRequestTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/model/ForceTypeOfHttpRequestTest.java index 9e60f3fb2..1125acf64 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/model/ForceTypeOfHttpRequestTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/model/ForceTypeOfHttpRequestTest.java @@ -1,45 +1,45 @@ -package com.github.scribejava.core.model; - -import java.util.concurrent.ExecutionException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import com.github.scribejava.core.exceptions.OAuthException; -import com.github.scribejava.core.oauth.OAuth20Service; -import com.github.scribejava.core.oauth.OAuthService; - -public class ForceTypeOfHttpRequestTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - private OAuthRequest request; - private OAuthRequestAsync requestAsync; - - @Before - public void setUp() { - ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.NONE); - final OAuthService oAuthService = new OAuth20Service(null, new OAuthConfig("test", "test")); - request = new OAuthRequest(Verb.GET, "http://example.com?qsparam=value&other+param=value+with+spaces", - oAuthService); - requestAsync = new OAuthRequestAsync(Verb.GET, "http://example.com?qsparam=value&other+param=value+with+spaces", - oAuthService); - } - - @Test - public void shouldNotSendSyncWithForceParameter() { - expectedException.expect(OAuthException.class); - expectedException.expectMessage("Cannot use sync operations, only async"); - ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS); - request.send(); - } - - @Test - public void shouldNotSendAsyncWithForceParameter() throws ExecutionException, InterruptedException { - expectedException.expect(OAuthException.class); - expectedException.expectMessage("Cannot use async operations, only sync"); - ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.FORCE_SYNC_ONLY_HTTP_REQUESTS); - requestAsync.sendAsync(null).get(); - } -} +package com.github.scribejava.core.model; + +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.oauth.OAuth20Service; +import com.github.scribejava.core.oauth.OAuthService; + +public class ForceTypeOfHttpRequestTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private OAuthRequest request; + private OAuthRequestAsync requestAsync; + + @Before + public void setUp() { + ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.NONE); + final OAuthService oAuthService = new OAuth20Service(null, new OAuthConfig("test", "test")); + request = new OAuthRequest(Verb.GET, "http://example.com?qsparam=value&other+param=value+with+spaces", + oAuthService); + requestAsync = new OAuthRequestAsync(Verb.GET, "http://example.com?qsparam=value&other+param=value+with+spaces", + oAuthService); + } + + @Test + public void shouldNotSendSyncWithForceParameter() { + expectedException.expect(OAuthException.class); + expectedException.expectMessage("Cannot use sync operations, only async"); + ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS); + request.send(); + } + + @Test + public void shouldNotSendAsyncWithForceParameter() throws ExecutionException, InterruptedException { + expectedException.expect(OAuthException.class); + expectedException.expectMessage("Cannot use async operations, only sync"); + ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.FORCE_SYNC_ONLY_HTTP_REQUESTS); + requestAsync.sendAsync(null).get(); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/model/OAuthRequestTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/model/OAuthRequestTest.java index d1bae5bfa..fa377eceb 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/model/OAuthRequestTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/model/OAuthRequestTest.java @@ -1,33 +1,33 @@ -package com.github.scribejava.core.model; - -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.oauth.OAuth20Service; - -public class OAuthRequestTest { - - private OAuthRequest request; - - @Before - public void setUp() { - request = new OAuthRequest(Verb.GET, "http://example.com", - new OAuth20Service(null, new OAuthConfig("test", "test"))); - } - - @Test - public void shouldAddOAuthParamters() { - request.addOAuthParameter(OAuthConstants.TOKEN, "token"); - request.addOAuthParameter(OAuthConstants.NONCE, "nonce"); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "ts"); - request.addOAuthParameter(OAuthConstants.SCOPE, "feeds"); - request.addOAuthParameter(OAuthConstants.REALM, "some-realm"); - - assertEquals(5, request.getOauthParameters().size()); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfParameterIsNotOAuth() { - request.addOAuthParameter("otherParam", "value"); - } -} +package com.github.scribejava.core.model; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.oauth.OAuth20Service; + +public class OAuthRequestTest { + + private OAuthRequest request; + + @Before + public void setUp() { + request = new OAuthRequest(Verb.GET, "http://example.com", + new OAuth20Service(null, new OAuthConfig("test", "test"))); + } + + @Test + public void shouldAddOAuthParamters() { + request.addOAuthParameter(OAuthConstants.TOKEN, "token"); + request.addOAuthParameter(OAuthConstants.NONCE, "nonce"); + request.addOAuthParameter(OAuthConstants.TIMESTAMP, "ts"); + request.addOAuthParameter(OAuthConstants.SCOPE, "feeds"); + request.addOAuthParameter(OAuthConstants.REALM, "some-realm"); + + assertEquals(5, request.getOauthParameters().size()); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfParameterIsNotOAuth() { + request.addOAuthParameter("otherParam", "value"); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/model/ParameterListTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/model/ParameterListTest.java index 78a22c9f9..25da5ac28 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/model/ParameterListTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/model/ParameterListTest.java @@ -1,78 +1,78 @@ -package com.github.scribejava.core.model; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertNotSame; - -public class ParameterListTest { - - private ParameterList params; - - @Before - public void setUp() { - this.params = new ParameterList(); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionWhenAppendingNullMapToQuerystring() { - params.appendTo(null); - } - - @Test - public void shouldAppendNothingToQuerystringIfGivenEmptyMap() { - final String url = "http://www.example.com"; - Assert.assertEquals(url, params.appendTo(url)); - } - - @Test - public void shouldAppendParametersToSimpleUrl() { - String url = "http://www.example.com"; - final String expectedUrl = "http://www.example.com?param1=value1¶m2=value%20with%20spaces"; - - params.add("param1", "value1"); - params.add("param2", "value with spaces"); - - url = params.appendTo(url); - Assert.assertEquals(expectedUrl, url); - } - - @Test - public void shouldAppendParametersToUrlWithQuerystring() { - String url = "http://www.example.com?already=present"; - final String expectedUrl = "http://www.example.com?already=present¶m1=value1¶m2=value%20with%20spaces"; - - params.add("param1", "value1"); - params.add("param2", "value with spaces"); - - url = params.appendTo(url); - Assert.assertEquals(expectedUrl, url); - } - - @Test - public void shouldProperlySortParameters() { - params.add("param1", "v1"); - params.add("param6", "v2"); - params.add("a_param", "v3"); - params.add("param2", "v4"); - Assert.assertEquals("a_param=v3¶m1=v1¶m2=v4¶m6=v2", params.sort().asFormUrlEncodedString()); - } - - @Test - public void shouldProperlySortParametersWithTheSameName() { - params.add("param1", "v1"); - params.add("param6", "v2"); - params.add("a_param", "v3"); - params.add("param1", "v4"); - Assert.assertEquals("a_param=v3¶m1=v1¶m1=v4¶m6=v2", params.sort().asFormUrlEncodedString()); - } - - @Test - public void shouldNotModifyTheOriginalParameterList() { - params.add("param1", "v1"); - params.add("param6", "v2"); - - assertNotSame(params, params.sort()); - } -} +package com.github.scribejava.core.model; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertNotSame; + +public class ParameterListTest { + + private ParameterList params; + + @Before + public void setUp() { + this.params = new ParameterList(); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionWhenAppendingNullMapToQuerystring() { + params.appendTo(null); + } + + @Test + public void shouldAppendNothingToQuerystringIfGivenEmptyMap() { + final String url = "http://www.example.com"; + Assert.assertEquals(url, params.appendTo(url)); + } + + @Test + public void shouldAppendParametersToSimpleUrl() { + String url = "http://www.example.com"; + final String expectedUrl = "http://www.example.com?param1=value1¶m2=value%20with%20spaces"; + + params.add("param1", "value1"); + params.add("param2", "value with spaces"); + + url = params.appendTo(url); + Assert.assertEquals(expectedUrl, url); + } + + @Test + public void shouldAppendParametersToUrlWithQuerystring() { + String url = "http://www.example.com?already=present"; + final String expectedUrl = "http://www.example.com?already=present¶m1=value1¶m2=value%20with%20spaces"; + + params.add("param1", "value1"); + params.add("param2", "value with spaces"); + + url = params.appendTo(url); + Assert.assertEquals(expectedUrl, url); + } + + @Test + public void shouldProperlySortParameters() { + params.add("param1", "v1"); + params.add("param6", "v2"); + params.add("a_param", "v3"); + params.add("param2", "v4"); + Assert.assertEquals("a_param=v3¶m1=v1¶m2=v4¶m6=v2", params.sort().asFormUrlEncodedString()); + } + + @Test + public void shouldProperlySortParametersWithTheSameName() { + params.add("param1", "v1"); + params.add("param6", "v2"); + params.add("a_param", "v3"); + params.add("param1", "v4"); + Assert.assertEquals("a_param=v3¶m1=v1¶m1=v4¶m6=v2", params.sort().asFormUrlEncodedString()); + } + + @Test + public void shouldNotModifyTheOriginalParameterList() { + params.add("param1", "v1"); + params.add("param6", "v2"); + + assertNotSame(params, params.sort()); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/model/RequestTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/model/RequestTest.java index 16b060000..22368dca6 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/model/RequestTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/model/RequestTest.java @@ -1,122 +1,122 @@ -package com.github.scribejava.core.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.oauth.OAuth20Service; -import com.github.scribejava.core.oauth.OAuthService; -import java.net.MalformedURLException; - -public class RequestTest { - - private OAuthRequest getRequest; - private OAuthRequest postRequest; - private ConnectionStub connection; - private OAuthService oAuthService; - - @Before - public void setUp() throws MalformedURLException { - connection = new ConnectionStub(); - oAuthService = new OAuth20Service(null, new OAuthConfig("test", "test")); - postRequest = new OAuthRequest(Verb.POST, "http://example.com", oAuthService); - postRequest.addBodyParameter("param", "value"); - postRequest.addBodyParameter("param with spaces", "value with spaces"); - postRequest.setConnection(connection); - getRequest = new OAuthRequest(Verb.GET, "http://example.com?qsparam=value&other+param=value+with+spaces", - oAuthService); - getRequest.setConnection(connection); - } - - @Test - public void shouldSetRequestVerb() { - getRequest.send(); - assertEquals("GET", connection.getRequestMethod()); - } - - @Test - public void shouldGetQueryStringParameters() { - assertEquals(2, getRequest.getQueryStringParams().size()); - assertEquals(0, postRequest.getQueryStringParams().size()); - assertTrue(getRequest.getQueryStringParams().contains(new Parameter("qsparam", "value"))); - } - - @Test - public void shouldAddRequestHeaders() { - getRequest.addHeader("Header", "1"); - getRequest.addHeader("Header2", "2"); - getRequest.send(); - assertEquals(2, getRequest.getHeaders().size()); - assertEquals(2, connection.getHeaders().size()); - } - - @Test - public void shouldSetBodyParamsAndAddContentLength() { - assertEquals("param=value¶m%20with%20spaces=value%20with%20spaces", postRequest.getBodyContents()); - postRequest.send(); - assertTrue(connection.getHeaders().containsKey("Content-Length")); - } - - @Test - public void shouldSetPayloadAndHeaders() { - postRequest.addPayload("PAYLOAD"); - postRequest.send(); - assertEquals("PAYLOAD", postRequest.getBodyContents()); - assertTrue(connection.getHeaders().containsKey("Content-Length")); - } - - @Test - public void shouldAllowAddingQuerystringParametersAfterCreation() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com?one=val", oAuthService); - request.addQuerystringParameter("two", "other val"); - request.addQuerystringParameter("more", "params"); - assertEquals(3, request.getQueryStringParams().size()); - } - - @Test - public void shouldReturnTheCompleteUrl() { - final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com?one=val", oAuthService); - request.addQuerystringParameter("two", "other val"); - request.addQuerystringParameter("more", "params"); - assertEquals("http://example.com?one=val&two=other%20val&more=params", request.getCompleteUrl()); - } - - @Test - public void shouldHandleQueryStringSpaceEncodingProperly() { - assertTrue(getRequest.getQueryStringParams().contains(new Parameter("other param", "value with spaces"))); - } - - @Test - public void shouldAutomaticallyAddContentTypeForPostRequestsWithBytePayload() { - postRequest.addPayload("PAYLOAD".getBytes()); - postRequest.send(); - assertEquals(OAuthRequest.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type")); - } - - @Test - public void shouldAutomaticallyAddContentTypeForPostRequestsWithStringPayload() { - postRequest.addPayload("PAYLOAD"); - postRequest.send(); - assertEquals(OAuthRequest.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type")); - } - - @Test - public void shouldAutomaticallyAddContentTypeForPostRequestsWithBodyParameters() { - postRequest.send(); - assertEquals(OAuthRequest.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type")); - } - - @Test - public void shouldBeAbleToOverrideItsContentType() { - postRequest.addHeader("Content-Type", "my-content-type"); - postRequest.send(); - assertEquals("my-content-type", connection.getHeaders().get("Content-Type")); - } - - @Test - public void shouldNotAddContentTypeForGetRequests() { - getRequest.send(); - assertFalse(connection.getHeaders().containsKey("Content-Type")); - } -} +package com.github.scribejava.core.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.oauth.OAuth20Service; +import com.github.scribejava.core.oauth.OAuthService; +import java.net.MalformedURLException; + +public class RequestTest { + + private OAuthRequest getRequest; + private OAuthRequest postRequest; + private ConnectionStub connection; + private OAuthService oAuthService; + + @Before + public void setUp() throws MalformedURLException { + connection = new ConnectionStub(); + oAuthService = new OAuth20Service(null, new OAuthConfig("test", "test")); + postRequest = new OAuthRequest(Verb.POST, "http://example.com", oAuthService); + postRequest.addBodyParameter("param", "value"); + postRequest.addBodyParameter("param with spaces", "value with spaces"); + postRequest.setConnection(connection); + getRequest = new OAuthRequest(Verb.GET, "http://example.com?qsparam=value&other+param=value+with+spaces", + oAuthService); + getRequest.setConnection(connection); + } + + @Test + public void shouldSetRequestVerb() { + getRequest.send(); + assertEquals("GET", connection.getRequestMethod()); + } + + @Test + public void shouldGetQueryStringParameters() { + assertEquals(2, getRequest.getQueryStringParams().size()); + assertEquals(0, postRequest.getQueryStringParams().size()); + assertTrue(getRequest.getQueryStringParams().contains(new Parameter("qsparam", "value"))); + } + + @Test + public void shouldAddRequestHeaders() { + getRequest.addHeader("Header", "1"); + getRequest.addHeader("Header2", "2"); + getRequest.send(); + assertEquals(2, getRequest.getHeaders().size()); + assertEquals(2, connection.getHeaders().size()); + } + + @Test + public void shouldSetBodyParamsAndAddContentLength() { + assertEquals("param=value¶m%20with%20spaces=value%20with%20spaces", postRequest.getBodyContents()); + postRequest.send(); + assertTrue(connection.getHeaders().containsKey("Content-Length")); + } + + @Test + public void shouldSetPayloadAndHeaders() { + postRequest.addPayload("PAYLOAD"); + postRequest.send(); + assertEquals("PAYLOAD", postRequest.getBodyContents()); + assertTrue(connection.getHeaders().containsKey("Content-Length")); + } + + @Test + public void shouldAllowAddingQuerystringParametersAfterCreation() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com?one=val", oAuthService); + request.addQuerystringParameter("two", "other val"); + request.addQuerystringParameter("more", "params"); + assertEquals(3, request.getQueryStringParams().size()); + } + + @Test + public void shouldReturnTheCompleteUrl() { + final OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com?one=val", oAuthService); + request.addQuerystringParameter("two", "other val"); + request.addQuerystringParameter("more", "params"); + assertEquals("http://example.com?one=val&two=other%20val&more=params", request.getCompleteUrl()); + } + + @Test + public void shouldHandleQueryStringSpaceEncodingProperly() { + assertTrue(getRequest.getQueryStringParams().contains(new Parameter("other param", "value with spaces"))); + } + + @Test + public void shouldAutomaticallyAddContentTypeForPostRequestsWithBytePayload() { + postRequest.addPayload("PAYLOAD".getBytes()); + postRequest.send(); + assertEquals(OAuthRequest.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type")); + } + + @Test + public void shouldAutomaticallyAddContentTypeForPostRequestsWithStringPayload() { + postRequest.addPayload("PAYLOAD"); + postRequest.send(); + assertEquals(OAuthRequest.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type")); + } + + @Test + public void shouldAutomaticallyAddContentTypeForPostRequestsWithBodyParameters() { + postRequest.send(); + assertEquals(OAuthRequest.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type")); + } + + @Test + public void shouldBeAbleToOverrideItsContentType() { + postRequest.addHeader("Content-Type", "my-content-type"); + postRequest.send(); + assertEquals("my-content-type", connection.getHeaders().get("Content-Type")); + } + + @Test + public void shouldNotAddContentTypeForGetRequests() { + getRequest.send(); + assertFalse(connection.getHeaders().containsKey("Content-Type")); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/model/TokenTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/model/TokenTest.java index 7c988ae7b..69e3d3e06 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/model/TokenTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/model/TokenTest.java @@ -1,51 +1,51 @@ -package com.github.scribejava.core.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import org.junit.Test; - -public class TokenTest { - - @Test - public void shouldTestEqualityBasedOnTokenAndSecret() { - final Token expected = new OAuth1AccessToken("access", "secret"); - final Token actual = new OAuth1AccessToken("access", "secret"); - - assertEquals(expected, actual); - assertEquals(actual, actual); - } - - @Test - public void shouldNotDependOnRawString() { - final Token expected = new OAuth1AccessToken("access", "secret", "raw_string"); - final Token actual = new OAuth1AccessToken("access", "secret", "different_raw_string"); - - assertEquals(expected, actual); - } - - @Test - public void shouldReturnSameHashCodeForEqualObjects() { - final Token expected = new OAuth1AccessToken("access", "secret"); - final Token actual = new OAuth1AccessToken("access", "secret"); - - assertEquals(expected.hashCode(), actual.hashCode()); - } - - @Test - public void shouldNotBeEqualToNullOrOtherObjects() { - final Token expected = new OAuth1AccessToken("access", "secret", "response"); - - assertNotSame(expected, null); - assertNotSame(expected, new Object()); - } - - @Test - public void shouldReturnUrlParam() { - final Token actual = new OAuth1AccessToken("acccess", "secret", - "user_id=3107154759&screen_name=someuser&empty=&="); - assertEquals("someuser", actual.getParameter("screen_name")); - assertEquals("3107154759", actual.getParameter("user_id")); - assertEquals(null, actual.getParameter("empty")); - assertEquals(null, actual.getParameter(null)); - } -} +package com.github.scribejava.core.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import org.junit.Test; + +public class TokenTest { + + @Test + public void shouldTestEqualityBasedOnTokenAndSecret() { + final Token expected = new OAuth1AccessToken("access", "secret"); + final Token actual = new OAuth1AccessToken("access", "secret"); + + assertEquals(expected, actual); + assertEquals(actual, actual); + } + + @Test + public void shouldNotDependOnRawString() { + final Token expected = new OAuth1AccessToken("access", "secret", "raw_string"); + final Token actual = new OAuth1AccessToken("access", "secret", "different_raw_string"); + + assertEquals(expected, actual); + } + + @Test + public void shouldReturnSameHashCodeForEqualObjects() { + final Token expected = new OAuth1AccessToken("access", "secret"); + final Token actual = new OAuth1AccessToken("access", "secret"); + + assertEquals(expected.hashCode(), actual.hashCode()); + } + + @Test + public void shouldNotBeEqualToNullOrOtherObjects() { + final Token expected = new OAuth1AccessToken("access", "secret", "response"); + + assertNotSame(expected, null); + assertNotSame(expected, new Object()); + } + + @Test + public void shouldReturnUrlParam() { + final Token actual = new OAuth1AccessToken("acccess", "secret", + "user_id=3107154759&screen_name=someuser&empty=&="); + assertEquals("someuser", actual.getParameter("screen_name")); + assertEquals("3107154759", actual.getParameter("user_id")); + assertEquals(null, actual.getParameter("empty")); + assertEquals(null, actual.getParameter(null)); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/oauth/CompletedFuture.java b/scribejava-core/src/test/java/com/github/scribejava/core/oauth/CompletedFuture.java index 33919d4bf..726d389f9 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/oauth/CompletedFuture.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/oauth/CompletedFuture.java @@ -1,37 +1,37 @@ -package com.github.scribejava.core.oauth; - -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -class CompletedFuture implements Future { - private final V result; - - CompletedFuture(V result) { - this.result = result; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - @Override - public boolean isCancelled() { - return false; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public V get() { - return result; - } - - @Override - public V get(long timeout, TimeUnit unit) { - return result; - } -} +package com.github.scribejava.core.oauth; + +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +class CompletedFuture implements Future { + private final V result; + + CompletedFuture(V result) { + this.result = result; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public V get() { + return result; + } + + @Override + public V get(long timeout, TimeUnit unit) { + return result; + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/services/HMACSha1SignatureServiceTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/services/HMACSha1SignatureServiceTest.java index d3fba9ae2..2bd634c55 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/services/HMACSha1SignatureServiceTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/services/HMACSha1SignatureServiceTest.java @@ -1,51 +1,51 @@ -package com.github.scribejava.core.services; - -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; -import com.github.scribejava.core.exceptions.OAuthException; - -public class HMACSha1SignatureServiceTest { - - private HMACSha1SignatureService service; - - @Before - public void setUp() { - service = new HMACSha1SignatureService(); - } - - @Test - public void shouldReturnSignatureMethodString() { - final String expected = "HMAC-SHA1"; - assertEquals(expected, service.getSignatureMethod()); - } - - @Test - public void shouldReturnSignature() { - final String apiSecret = "api secret"; - final String tokenSecret = "token secret"; - final String baseString = "base string"; - final String signature = "uGymw2KHOTWI699YEaoi5xyLT50="; - assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfBaseStringIsNull() { - service.getSignature(null, "apiSecret", "tokenSecret"); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfBaseStringIsEmpty() { - service.getSignature(" ", "apiSecret", "tokenSecret"); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfApiSecretIsNull() { - service.getSignature("base string", null, "tokenSecret"); - } - - @Test(expected = OAuthException.class) - public void shouldThrowExceptionIfApiSecretIsEmpty() { - service.getSignature("base string", " ", "tokenSecret"); - } -} +package com.github.scribejava.core.services; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import com.github.scribejava.core.exceptions.OAuthException; + +public class HMACSha1SignatureServiceTest { + + private HMACSha1SignatureService service; + + @Before + public void setUp() { + service = new HMACSha1SignatureService(); + } + + @Test + public void shouldReturnSignatureMethodString() { + final String expected = "HMAC-SHA1"; + assertEquals(expected, service.getSignatureMethod()); + } + + @Test + public void shouldReturnSignature() { + final String apiSecret = "api secret"; + final String tokenSecret = "token secret"; + final String baseString = "base string"; + final String signature = "uGymw2KHOTWI699YEaoi5xyLT50="; + assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfBaseStringIsNull() { + service.getSignature(null, "apiSecret", "tokenSecret"); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfBaseStringIsEmpty() { + service.getSignature(" ", "apiSecret", "tokenSecret"); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfApiSecretIsNull() { + service.getSignature("base string", null, "tokenSecret"); + } + + @Test(expected = OAuthException.class) + public void shouldThrowExceptionIfApiSecretIsEmpty() { + service.getSignature("base string", " ", "tokenSecret"); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/services/RSASha1SignatureServiceTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/services/RSASha1SignatureServiceTest.java index 261bc2bb4..aaf9f7e6b 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/services/RSASha1SignatureServiceTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/services/RSASha1SignatureServiceTest.java @@ -1,61 +1,61 @@ -package com.github.scribejava.core.services; - -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import javax.xml.bind.DatatypeConverter; -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -public class RSASha1SignatureServiceTest { - - private final RSASha1SignatureService service = new RSASha1SignatureService(getPrivateKey()); - - @Test - public void shouldReturnSignatureMethodString() { - final String expected = "RSA-SHA1"; - assertEquals(expected, service.getSignatureMethod()); - } - - @Test - public void shouldReturnSignature() { - final String apiSecret = "api secret"; - final String tokenSecret = "token secret"; - final String baseString = "base string"; - final String signature = "LUNRzQAlpdNyM9mLXm96Va6g/qVNnEAb7p7K1KM0g8IopOFQJPoOO7cvppgt7w3QyhijWJnCmvqXaaIAGrqvd" - + "yr3fIzBULh8D/iZQUNLMi08GCOA34P81XBvsc7A5uJjPDsGhJg2MzoVJ8nWJhU/lMMk4c92S1WGskeoDofRwpo="; - assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); - } - - /** - * Created primary key using openssl. - * - * openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com' - * -keyout myrsakey.pem -out /tmp/myrsacert.pem openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8 - */ - private static PrivateKey getPrivateKey() { - final String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" - + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" - + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" - + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" - + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" - + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" - + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" - + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" - + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" - + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" - + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" - + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" - + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww=="; - - try { - final KeyFactory fac = KeyFactory.getInstance("RSA"); - final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str)); - return fac.generatePrivate(privKeySpec); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new RuntimeException(e); - } - } -} +package com.github.scribejava.core.services; + +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import javax.xml.bind.DatatypeConverter; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class RSASha1SignatureServiceTest { + + private final RSASha1SignatureService service = new RSASha1SignatureService(getPrivateKey()); + + @Test + public void shouldReturnSignatureMethodString() { + final String expected = "RSA-SHA1"; + assertEquals(expected, service.getSignatureMethod()); + } + + @Test + public void shouldReturnSignature() { + final String apiSecret = "api secret"; + final String tokenSecret = "token secret"; + final String baseString = "base string"; + final String signature = "LUNRzQAlpdNyM9mLXm96Va6g/qVNnEAb7p7K1KM0g8IopOFQJPoOO7cvppgt7w3QyhijWJnCmvqXaaIAGrqvd" + + "yr3fIzBULh8D/iZQUNLMi08GCOA34P81XBvsc7A5uJjPDsGhJg2MzoVJ8nWJhU/lMMk4c92S1WGskeoDofRwpo="; + assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); + } + + /** + * Created primary key using openssl. + * + * openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com' + * -keyout myrsakey.pem -out /tmp/myrsacert.pem openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8 + */ + private static PrivateKey getPrivateKey() { + final String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww=="; + + try { + final KeyFactory fac = KeyFactory.getInstance("RSA"); + final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str)); + return fac.generatePrivate(privKeySpec); + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + throw new RuntimeException(e); + } + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/services/TimestampServiceTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/services/TimestampServiceTest.java index 4d8f27bc5..35fe7f16c 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/services/TimestampServiceTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/services/TimestampServiceTest.java @@ -1,41 +1,41 @@ -package com.github.scribejava.core.services; - -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; - -public class TimestampServiceTest { - - private TimestampServiceImpl service; - - @Before - public void setUp() { - service = new TimestampServiceImpl(); - service.setTimer(new TimerStub()); - } - - @Test - public void shouldReturnTimestampInSeconds() { - final String expected = "1000"; - assertEquals(expected, service.getTimestampInSeconds()); - } - - @Test - public void shouldReturnNonce() { - final String expected = "1042"; - assertEquals(expected, service.getNonce()); - } - - private static class TimerStub extends TimestampServiceImpl.Timer { - - @Override - public Long getMilis() { - return 1000000L; - } - - @Override - public Integer getRandomInteger() { - return 42; - } - } -} +package com.github.scribejava.core.services; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class TimestampServiceTest { + + private TimestampServiceImpl service; + + @Before + public void setUp() { + service = new TimestampServiceImpl(); + service.setTimer(new TimerStub()); + } + + @Test + public void shouldReturnTimestampInSeconds() { + final String expected = "1000"; + assertEquals(expected, service.getTimestampInSeconds()); + } + + @Test + public void shouldReturnNonce() { + final String expected = "1042"; + assertEquals(expected, service.getNonce()); + } + + private static class TimerStub extends TimestampServiceImpl.Timer { + + @Override + public Long getMilis() { + return 1000000L; + } + + @Override + public Integer getRandomInteger() { + return 42; + } + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/utils/MapUtilsTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/utils/MapUtilsTest.java index dc6bd38d5..b072c1a80 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/utils/MapUtilsTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/utils/MapUtilsTest.java @@ -1,30 +1,30 @@ -package com.github.scribejava.core.utils; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; - -public class MapUtilsTest { - - @Test - public void shouldPrettyPrintMap() { - final Map map = new HashMap<>(); - map.put(1, "one"); - map.put(2, "two"); - map.put(3, "three"); - map.put(4, "four"); - Assert.assertEquals("{ 1 -> one , 2 -> two , 3 -> three , 4 -> four }", MapUtils.toString(map)); - } - - @Test - public void shouldHandleEmptyMap() { - final Map map = new HashMap<>(); - Assert.assertEquals("{}", MapUtils.toString(map)); - } - - @Test - public void shouldHandleNullInputs() { - Assert.assertEquals("", MapUtils.toString(null)); - } -} +package com.github.scribejava.core.utils; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Assert; +import org.junit.Test; + +public class MapUtilsTest { + + @Test + public void shouldPrettyPrintMap() { + final Map map = new HashMap<>(); + map.put(1, "one"); + map.put(2, "two"); + map.put(3, "three"); + map.put(4, "four"); + Assert.assertEquals("{ 1 -> one , 2 -> two , 3 -> three , 4 -> four }", MapUtils.toString(map)); + } + + @Test + public void shouldHandleEmptyMap() { + final Map map = new HashMap<>(); + Assert.assertEquals("{}", MapUtils.toString(map)); + } + + @Test + public void shouldHandleNullInputs() { + Assert.assertEquals("", MapUtils.toString(null)); + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/utils/OAuthEncoderTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/utils/OAuthEncoderTest.java index 1a1489b41..3cbb2bbb0 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/utils/OAuthEncoderTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/utils/OAuthEncoderTest.java @@ -1,59 +1,59 @@ -package com.github.scribejava.core.utils; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -public class OAuthEncoderTest { - - @Test - public void shouldPercentEncodeString() { - final String plain = "this is a test &^"; - final String encoded = "this%20is%20a%20test%20%26%5E"; - assertEquals(encoded, OAuthEncoder.encode(plain)); - } - - @Test - public void shouldFormURLDecodeString() { - final String encoded = "this+is+a+test+%26%5E"; - final String plain = "this is a test &^"; - assertEquals(plain, OAuthEncoder.decode(encoded)); - } - - @Test - public void shouldPercentEncodeAllSpecialCharacters() { - final String plain = "!*'();:@&=+$,/?#[]"; - final String encoded = "%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%23%5B%5D"; - assertEquals(encoded, OAuthEncoder.encode(plain)); - assertEquals(plain, OAuthEncoder.decode(encoded)); - } - - @Test - public void shouldNotPercentEncodeReservedCharacters() { - final String plain = "abcde123456-._~"; - final String encoded = plain; - assertEquals(encoded, OAuthEncoder.encode(plain)); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfStringToEncodeIsNull() { - OAuthEncoder.encode(null); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionIfStringToDecodeIsNull() { - OAuthEncoder.decode(null); - } - - @Test - public void shouldPercentEncodeCorrectlyTwitterCodingExamples() { - // These tests are part of the Twitter dev examples here - // -> https://dev.twitter.com/docs/auth/percent-encoding-parameters - final String[] sources = {"Ladies + Gentlemen", "An encoded string!", "Dogs, Cats & Mice"}; - final String[] encoded = {"Ladies%20%2B%20Gentlemen", "An%20encoded%20string%21", - "Dogs%2C%20Cats%20%26%20Mice"}; - - for (int i = 0; i < sources.length; i++) { - assertEquals(encoded[i], OAuthEncoder.encode(sources[i])); - } - } -} +package com.github.scribejava.core.utils; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class OAuthEncoderTest { + + @Test + public void shouldPercentEncodeString() { + final String plain = "this is a test &^"; + final String encoded = "this%20is%20a%20test%20%26%5E"; + assertEquals(encoded, OAuthEncoder.encode(plain)); + } + + @Test + public void shouldFormURLDecodeString() { + final String encoded = "this+is+a+test+%26%5E"; + final String plain = "this is a test &^"; + assertEquals(plain, OAuthEncoder.decode(encoded)); + } + + @Test + public void shouldPercentEncodeAllSpecialCharacters() { + final String plain = "!*'();:@&=+$,/?#[]"; + final String encoded = "%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%23%5B%5D"; + assertEquals(encoded, OAuthEncoder.encode(plain)); + assertEquals(plain, OAuthEncoder.decode(encoded)); + } + + @Test + public void shouldNotPercentEncodeReservedCharacters() { + final String plain = "abcde123456-._~"; + final String encoded = plain; + assertEquals(encoded, OAuthEncoder.encode(plain)); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfStringToEncodeIsNull() { + OAuthEncoder.encode(null); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionIfStringToDecodeIsNull() { + OAuthEncoder.decode(null); + } + + @Test + public void shouldPercentEncodeCorrectlyTwitterCodingExamples() { + // These tests are part of the Twitter dev examples here + // -> https://dev.twitter.com/docs/auth/percent-encoding-parameters + final String[] sources = {"Ladies + Gentlemen", "An encoded string!", "Dogs, Cats & Mice"}; + final String[] encoded = {"Ladies%20%2B%20Gentlemen", "An%20encoded%20string%21", + "Dogs%2C%20Cats%20%26%20Mice"}; + + for (int i = 0; i < sources.length; i++) { + assertEquals(encoded[i], OAuthEncoder.encode(sources[i])); + } + } +} diff --git a/scribejava-core/src/test/java/com/github/scribejava/core/utils/PreconditionsTest.java b/scribejava-core/src/test/java/com/github/scribejava/core/utils/PreconditionsTest.java index 76d64c5ba..6dd002021 100644 --- a/scribejava-core/src/test/java/com/github/scribejava/core/utils/PreconditionsTest.java +++ b/scribejava-core/src/test/java/com/github/scribejava/core/utils/PreconditionsTest.java @@ -1,73 +1,73 @@ -package com.github.scribejava.core.utils; - -import org.junit.Test; - -public class PreconditionsTest { - - private static final String ERROR_MSG = ""; - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionForNullObjects() { - Preconditions.checkNotNull(null, ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionForNullStrings() { - Preconditions.checkEmptyString(null, ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionForEmptyStrings() { - Preconditions.checkEmptyString("", ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionForSpacesOnlyStrings() { - Preconditions.checkEmptyString(" ", ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionForInvalidUrls() { - Preconditions.checkValidUrl("this/is/not/a/valid/url", ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionForNullUrls() { - Preconditions.checkValidUrl(null, ERROR_MSG); - } - - @Test - public void shouldAllowValidUrls() { - Preconditions.checkValidUrl("http://www.example.com", ERROR_MSG); - } - - @Test - public void shouldAllowSSLUrls() { - Preconditions.checkValidUrl("https://www.example.com", ERROR_MSG); - } - - @Test - public void shouldAllowSpecialCharsInScheme() { - Preconditions.checkValidUrl("custom+9.3-1://www.example.com", ERROR_MSG); - } - - @Test - public void shouldAllowNonStandarProtocolsForAndroid() { - Preconditions.checkValidUrl("x-url-custom://www.example.com", ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldNotAllowStrangeProtocolNames() { - Preconditions.checkValidUrl("$weird*://www.example.com", ERROR_MSG); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldNotAllowUnderscoreInScheme() { - Preconditions.checkValidUrl("http_custom://www.example.com", ERROR_MSG); - } - - @Test - public void shouldAllowOutOfBandAsValidCallbackValue() { - Preconditions.checkValidOAuthCallback("oob", ERROR_MSG); - } -} +package com.github.scribejava.core.utils; + +import org.junit.Test; + +public class PreconditionsTest { + + private static final String ERROR_MSG = ""; + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionForNullObjects() { + Preconditions.checkNotNull(null, ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionForNullStrings() { + Preconditions.checkEmptyString(null, ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionForEmptyStrings() { + Preconditions.checkEmptyString("", ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionForSpacesOnlyStrings() { + Preconditions.checkEmptyString(" ", ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionForInvalidUrls() { + Preconditions.checkValidUrl("this/is/not/a/valid/url", ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionForNullUrls() { + Preconditions.checkValidUrl(null, ERROR_MSG); + } + + @Test + public void shouldAllowValidUrls() { + Preconditions.checkValidUrl("http://www.example.com", ERROR_MSG); + } + + @Test + public void shouldAllowSSLUrls() { + Preconditions.checkValidUrl("https://www.example.com", ERROR_MSG); + } + + @Test + public void shouldAllowSpecialCharsInScheme() { + Preconditions.checkValidUrl("custom+9.3-1://www.example.com", ERROR_MSG); + } + + @Test + public void shouldAllowNonStandarProtocolsForAndroid() { + Preconditions.checkValidUrl("x-url-custom://www.example.com", ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldNotAllowStrangeProtocolNames() { + Preconditions.checkValidUrl("$weird*://www.example.com", ERROR_MSG); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldNotAllowUnderscoreInScheme() { + Preconditions.checkValidUrl("http_custom://www.example.com", ERROR_MSG); + } + + @Test + public void shouldAllowOutOfBandAsValidCallbackValue() { + Preconditions.checkValidOAuthCallback("oob", ERROR_MSG); + } +} diff --git a/v1-changelog b/v1-changelog index 5423c6237..b1de15e7c 100644 --- a/v1-changelog +++ b/v1-changelog @@ -1,98 +1,98 @@ -[1.0.6] - - * FEATURE: Available in maven central repositories. - -[1.0.7] - - * FEATURE: Added support for Yammer and Evernote ( thanks oparrsih ) - * FIX: Fixed bug that preventing setting the scope param on Google Api - -[1.0.8] - - * FEATURE: Added setConnectTimeout and setReadTimeout for the Request Object - * FIX: Fixed Evernote Api (uses GET for request and access tokens) - * REFACTOR: URLEncoding stuff. LinkedIn specific decoder is no longer needed - * FEATURE: Added Google example - -[1.0.9] - - * FEATURE: Token made Serializable - * FIX: Google Api encoding issues (thanks @roger and @klakegg) - -[1.1.0] - - * FEATURE: OAuth 2.0 Support and Facebook support out of the box (thanks Diego Silveira) - * REFACTOR: Api creation and OAuthService refactors - * REFACTOR: Connections are created lazily (just before sending the request) - -[1.1.1] - - * FIX: Removed isEmpty() from OAuth2.0 code in order to support older JVMs - * FEATURE: Overloaded provider() method to support instances as well as classes (thanks dustismo) - * FIX: White-space parameter bug (thanks Krogoth) - * FEATURE: OAuth 2.0 now implements server-flow (thanks Diego Silveira) - -[1.1.2] - - * FIX: Fixed ugly bug that made 1.1.1 practically unusable (thanks Stubbs) - -[1.1.3] - - * FEATURE: Added rawResponse to Token, for extracting additional parameters (thanks Dirk McCormick) - * FEATURE: Added Dropbox Api - * FIX: Token responses now work despite of the token/secret order - * FEATURE: Added Foursquare OAuth 2.0 Api (thanks Tom Tasche) - * FEATURE: Added support for OAuth1.0a signatures via querystring parameters - * FEATURE: Added ConstantContact Api (thanks Matthew Laudato) - -[1.2] - * REFACTOR: Moved scope inside OAuthConfig (breaks backwards compatibility) - * FEATURE: Added scopes to Facebook 2.0 Api - * FEATURE: Added Plaintext signature for Yammer - * FEATURE: Added Twitter SSL endpoints (use TwitterApi.SSL.class) - -[1.2.1] - * FEATURE: Added custom charset support to Request (thanks Eric Genet) - * FEATURE: Added support for Vkontakte (thanks dotbg) - * FEATURE: Added Sohu Weibo, Netease Weibo & Sina Weibo Apis (thanks Arthur Wang) - * FEATURE: Added support for persistent Http Connections (thanks Craig Minton) - -[1.2.2] - * FIX: Added support for JDK 1.5. Issue #146 (thanks Sripathi Krishnan) - * FIX: Invalid character constant error message. Issue #137 (thanks Scott Scoble) - * FEATURE: Added a Api class to handle windows live authentication. Issue #135 (thanks Tomas Lin) - * FEATURE: Added refresh token feature for Yahoo! API. Issue #134 (thanks Aaron Foltz) - * FEATURE: Added support for Plurk API. Issue #130 (thanks Chia-Wei Li) - * FIX: Request.setConnectTimeout() and setReadTimeout() throw NPE. Issue #123 (thanks thepizzle) - -[1.2.3] - * FEATURE: Added default Content-Type header - * FEATURE: Sapo Api - * FEATURE: Plurk Mobile Api - * FEATURE: Kaixin and QWeibo Apis - * FEATURE: SimpleGeo Api - -[1.3.0] - * FEATURE: Multiple parameters with the same name supported. - * FEAUTRE: 'debug' mode that logs useful information about the signature making - -[1.3.1] - * FEATURE: Meetup.com Api - * FEATURE: NetProspex Api - * FEATURE: Kaixin2, SinaWeibo2 and Renren Apis - * FEATURE: ImgUr Api - * FEATURE: Freelancer Api (thanks Juan Palacios!) - * FIX: Allow digits in url schemes - * FEATURE: Specific exception for connection problems (OAuthConnectionException) - * FIX: Dropbox Api and Evernote Api updated to their latests versions - * FEATURE: Digg and Skyrock Apis - -[1.3.2] - * FIX: Don't include oauth_token in 2legged calls. - * FEATURE: RSA-SHA1 Signatures. - * FEATURE: equals & hashcode on Token object. - * FEATURE: ConstantContact Api - -[1.3.3] - * FEATURE: accessToken and requestToken timeouts default to 2 seconds and can be specified. - * FEATURE: New Apis. +[1.0.6] + + * FEATURE: Available in maven central repositories. + +[1.0.7] + + * FEATURE: Added support for Yammer and Evernote ( thanks oparrsih ) + * FIX: Fixed bug that preventing setting the scope param on Google Api + +[1.0.8] + + * FEATURE: Added setConnectTimeout and setReadTimeout for the Request Object + * FIX: Fixed Evernote Api (uses GET for request and access tokens) + * REFACTOR: URLEncoding stuff. LinkedIn specific decoder is no longer needed + * FEATURE: Added Google example + +[1.0.9] + + * FEATURE: Token made Serializable + * FIX: Google Api encoding issues (thanks @roger and @klakegg) + +[1.1.0] + + * FEATURE: OAuth 2.0 Support and Facebook support out of the box (thanks Diego Silveira) + * REFACTOR: Api creation and OAuthService refactors + * REFACTOR: Connections are created lazily (just before sending the request) + +[1.1.1] + + * FIX: Removed isEmpty() from OAuth2.0 code in order to support older JVMs + * FEATURE: Overloaded provider() method to support instances as well as classes (thanks dustismo) + * FIX: White-space parameter bug (thanks Krogoth) + * FEATURE: OAuth 2.0 now implements server-flow (thanks Diego Silveira) + +[1.1.2] + + * FIX: Fixed ugly bug that made 1.1.1 practically unusable (thanks Stubbs) + +[1.1.3] + + * FEATURE: Added rawResponse to Token, for extracting additional parameters (thanks Dirk McCormick) + * FEATURE: Added Dropbox Api + * FIX: Token responses now work despite of the token/secret order + * FEATURE: Added Foursquare OAuth 2.0 Api (thanks Tom Tasche) + * FEATURE: Added support for OAuth1.0a signatures via querystring parameters + * FEATURE: Added ConstantContact Api (thanks Matthew Laudato) + +[1.2] + * REFACTOR: Moved scope inside OAuthConfig (breaks backwards compatibility) + * FEATURE: Added scopes to Facebook 2.0 Api + * FEATURE: Added Plaintext signature for Yammer + * FEATURE: Added Twitter SSL endpoints (use TwitterApi.SSL.class) + +[1.2.1] + * FEATURE: Added custom charset support to Request (thanks Eric Genet) + * FEATURE: Added support for Vkontakte (thanks dotbg) + * FEATURE: Added Sohu Weibo, Netease Weibo & Sina Weibo Apis (thanks Arthur Wang) + * FEATURE: Added support for persistent Http Connections (thanks Craig Minton) + +[1.2.2] + * FIX: Added support for JDK 1.5. Issue #146 (thanks Sripathi Krishnan) + * FIX: Invalid character constant error message. Issue #137 (thanks Scott Scoble) + * FEATURE: Added a Api class to handle windows live authentication. Issue #135 (thanks Tomas Lin) + * FEATURE: Added refresh token feature for Yahoo! API. Issue #134 (thanks Aaron Foltz) + * FEATURE: Added support for Plurk API. Issue #130 (thanks Chia-Wei Li) + * FIX: Request.setConnectTimeout() and setReadTimeout() throw NPE. Issue #123 (thanks thepizzle) + +[1.2.3] + * FEATURE: Added default Content-Type header + * FEATURE: Sapo Api + * FEATURE: Plurk Mobile Api + * FEATURE: Kaixin and QWeibo Apis + * FEATURE: SimpleGeo Api + +[1.3.0] + * FEATURE: Multiple parameters with the same name supported. + * FEAUTRE: 'debug' mode that logs useful information about the signature making + +[1.3.1] + * FEATURE: Meetup.com Api + * FEATURE: NetProspex Api + * FEATURE: Kaixin2, SinaWeibo2 and Renren Apis + * FEATURE: ImgUr Api + * FEATURE: Freelancer Api (thanks Juan Palacios!) + * FIX: Allow digits in url schemes + * FEATURE: Specific exception for connection problems (OAuthConnectionException) + * FIX: Dropbox Api and Evernote Api updated to their latests versions + * FEATURE: Digg and Skyrock Apis + +[1.3.2] + * FIX: Don't include oauth_token in 2legged calls. + * FEATURE: RSA-SHA1 Signatures. + * FEATURE: equals & hashcode on Token object. + * FEATURE: ConstantContact Api + +[1.3.3] + * FEATURE: accessToken and requestToken timeouts default to 2 seconds and can be specified. + * FEATURE: New Apis. diff --git a/v2pre-changelog b/v2pre-changelog index 6f456136e..1a128b98e 100644 --- a/v2pre-changelog +++ b/v2pre-changelog @@ -1,57 +1,57 @@ -[SNAPSHOT] - * prepare to merge back to the ScribeJava - * backport 'news' from scribejava - -[3.4] - * add doktornarabote.ru API support - -[3.3] - * upgrade ning async http client 1.9.20 -> 1.9.26 - * add possibility to use ProxyServer per-request (async only) - * rename maven modules, add "subscribe-" prefix - * backport anything new from scribe-java - -[3.2] - * add possibility to set non-default httpProvider Class Name for ning async http client - -[3.1] - * update FaceBook API version from 2.0 to 2.2 - * update ning dependency for async functionality - * allow 'realm' parameter in OAuthParameters - -[3.0] - * make compilable with OpenJDK8 - * add async functionality - * add GitHub API - * split on two maven modules (+repackaging) - -[2.3] - - * add state parameter in LinkedInAPI 2.0 - * update FB Graph API to version 2.0 - * add tut.by OAuth API - * add default parameter grant_type for Google, LinkedIn and Mail.ru - * update host for requests in VkontakteExample - * add Yinxiang Biji endpoint in EvernoteApi - * switch Flickr and Twitter to https - * update domain for LiveAPI - * add support for the Authorization parameter 'realm' - * add TumblrExample - * update TwitterExample to v1.1 - * merge Request class in OAuthRequest. No need in separate Request class. - No planned usages of 'clean' http requests. - * add required OAuthService parameter in constructor for OAuthRequest, - so it can use OAuthConfig always (Default timeouts for all OAuthRequests - per OAuthService instance are now possible 'from-the-box'). - * remove messy RequestTuner. Use OAuthConfig instead of it. - -[2.1] - - * add OpenID id_token parsing from response to GoogleAPI 2.0 - * add optional OAuth 'state' request parameter - * Add hh api support - * fix Mailru API - -[2.0] - - * New release. First release. Formalizations of new project. +[SNAPSHOT] + * prepare to merge back to the ScribeJava + * backport 'news' from scribejava + +[3.4] + * add doktornarabote.ru API support + +[3.3] + * upgrade ning async http client 1.9.20 -> 1.9.26 + * add possibility to use ProxyServer per-request (async only) + * rename maven modules, add "subscribe-" prefix + * backport anything new from scribe-java + +[3.2] + * add possibility to set non-default httpProvider Class Name for ning async http client + +[3.1] + * update FaceBook API version from 2.0 to 2.2 + * update ning dependency for async functionality + * allow 'realm' parameter in OAuthParameters + +[3.0] + * make compilable with OpenJDK8 + * add async functionality + * add GitHub API + * split on two maven modules (+repackaging) + +[2.3] + + * add state parameter in LinkedInAPI 2.0 + * update FB Graph API to version 2.0 + * add tut.by OAuth API + * add default parameter grant_type for Google, LinkedIn and Mail.ru + * update host for requests in VkontakteExample + * add Yinxiang Biji endpoint in EvernoteApi + * switch Flickr and Twitter to https + * update domain for LiveAPI + * add support for the Authorization parameter 'realm' + * add TumblrExample + * update TwitterExample to v1.1 + * merge Request class in OAuthRequest. No need in separate Request class. + No planned usages of 'clean' http requests. + * add required OAuthService parameter in constructor for OAuthRequest, + so it can use OAuthConfig always (Default timeouts for all OAuthRequests + per OAuthService instance are now possible 'from-the-box'). + * remove messy RequestTuner. Use OAuthConfig instead of it. + +[2.1] + + * add OpenID id_token parsing from response to GoogleAPI 2.0 + * add optional OAuth 'state' request parameter + * Add hh api support + * fix Mailru API + +[2.0] + + * New release. First release. Formalizations of new project.