diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..8987649 --- /dev/null +++ b/.classpath @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2b9eaa5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target/ +/.settings/ +.classpath +.settings \ No newline at end of file diff --git a/.project b/.project new file mode 100644 index 0000000..19ba215 --- /dev/null +++ b/.project @@ -0,0 +1,23 @@ + + + blackbird + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..4c28b1a --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..8626026 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..14b697b --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..e397e1d --- /dev/null +++ b/pom.xml @@ -0,0 +1,65 @@ + + 4.0.0 + + com.github.langsdorf + blackbird + 0.0.1-SNAPSHOT + jar + A simple Twitter API for Java + BlackBird + https://github.com/Langsdorf/BlackBird + + + UTF-8 + 1.6 + 1.6 + + + + + MIT + https://github.com/Langsdorf/BlackBird/LICENCE + + + + + + + Langsdorf + Thiago Langsdorf + langsdorf@outlook.com.br + https://github.com/Langsdorf/ + + owner + developer + + -3 + + + + + + org.projectlombok + lombok + 1.16.22 + provided + + + com.github.scribejava + scribejava-apis + 5.4.0 + + + org.apache.httpcomponents + httpclient + 4.5.5 + + + com.googlecode.json-simple + json-simple + 1.1.1 + + + diff --git a/src/examples/java/com/github/langsdorf/blackbird/DirectMessageExample.java b/src/examples/java/com/github/langsdorf/blackbird/DirectMessageExample.java new file mode 100644 index 0000000..4976507 --- /dev/null +++ b/src/examples/java/com/github/langsdorf/blackbird/DirectMessageExample.java @@ -0,0 +1,29 @@ +package com.github.langsdorf.blackbird; + +import com.github.langsdorf.blackbird.api.DirectMessageAPI; +import com.github.langsdorf.blackbird.api.UserAPI; +import com.github.langsdorf.blackbird.directmessage.DirectMessage; +import com.github.langsdorf.blackbird.exception.TwitterException; + +public class DirectMessageExample { + + public static void main(String[] args) throws TwitterException, InterruptedException { + BlackBird blackBird = new BlackBird(args[0], args[1], args[2], args[3]); + sendDM(blackBird, "thlangsdorf", "Using BlackBird! :D"); // sending a dm to "thlangsdorf" + } + + public static void sendDM(BlackBird session, String username, String text) throws TwitterException { + DirectMessageAPI directmessage_api = session.getDirectMessageAPI(); + UserAPI user_api = session.getUserAPI(); + + long userID = user_api.getUser(username).getUserId(); // Get user id by username + DirectMessage dm_sent = directmessage_api.sendDirectMessage(userID, text); + + System.out.println("DM ID: " + dm_sent.getId()); + System.out.println("DM Sender: " + dm_sent.getSenderId()); + System.out.println("DM Target: " + dm_sent.getRecipientId()); + System.out.println("DM Date: " + dm_sent.getCreatedAt().toString()); + System.out.println("DM Text: " + dm_sent.getMessage()); + } + +} diff --git a/src/examples/java/com/github/langsdorf/blackbird/TweetExample.java b/src/examples/java/com/github/langsdorf/blackbird/TweetExample.java new file mode 100644 index 0000000..1bf78cf --- /dev/null +++ b/src/examples/java/com/github/langsdorf/blackbird/TweetExample.java @@ -0,0 +1,32 @@ +package com.github.langsdorf.blackbird; + +import com.github.langsdorf.blackbird.api.TweetAPI; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.tweet.Tweet; + +public class TweetExample { + + public static void main(String[] args) throws TwitterException { + BlackBird blackBird = new BlackBird(args[0], args[1], args[2], args[3]); + long tw_id = createTweet(blackBird, "Check out my github profile: https://github.com/Langsdorf"); + deleteTweet(blackBird, tw_id); + } + + public static long createTweet(BlackBird session, String text) throws TwitterException { + TweetAPI tweet_api = session.getTweetAPI(); + Tweet tweet = tweet_api.createTweet(text); + System.out.println("Tweet text: " + tweet.getText()); + System.out.println("Tweet created at: " + tweet.getCreatedAt()); + System.out.println("Tweet ID: " + tweet.getTweetId()); + return tweet.getTweetId(); + } + + public static void deleteTweet(BlackBird session, long id) throws TwitterException { + TweetAPI tweet_api = session.getTweetAPI(); + Tweet tweet = tweet_api.deleteTweet(id); + System.out.println("Deleted tweet text: " + tweet.getText()); + System.out.println("Deleted tweet created at: " + tweet.getCreatedAt()); + System.out.println("Deleted tweet ID: " + tweet.getTweetId()); + } + +} diff --git a/src/examples/java/com/github/langsdorf/blackbird/UserExample.java b/src/examples/java/com/github/langsdorf/blackbird/UserExample.java new file mode 100644 index 0000000..a738bbb --- /dev/null +++ b/src/examples/java/com/github/langsdorf/blackbird/UserExample.java @@ -0,0 +1,67 @@ +package com.github.langsdorf.blackbird; + +import com.github.langsdorf.blackbird.api.UserAPI; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.user.User; + +public class UserExample { + + public static void main(String[] args) throws TwitterException { + BlackBird blackBird = new BlackBird(args[0], args[1], args[2], args[3]); + + blockUser(blackBird, "finkd"); //blocking the user called "finkd" + unblockUser(blackBird, "finkd"); //unblocking the user called "finkd" + muteUser(blackBird, "finkd"); //muting the user called "finkd" + unmuteUser(blackBird, "finkd"); //unmuting the user called "finkd" + followUser(blackBird, "finkd"); //follow the user called "finkd" + unfollowUser(blackBird, "finkd"); //unfollow the user called "finkd" + getFollowersName(blackBird, "thlangsdorf"); //get thlangsdorf's followers name + } + + public static void blockUser(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + User user = user_api.blockUser(target_name); + System.out.println("Blocked user name: " + user.getName()); + } + + public static void unblockUser(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + User user = user_api.unblockUser(target_name); + System.out.println("Unblocked user name: " + user.getName()); + } + + public static void muteUser(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + User user = user_api.muteUser(target_name); + System.out.println("Muting user: " + user.getName()); + } + + public static void unmuteUser(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + User user = user_api.unmuteUser(target_name); + System.out.println("Unmuting user: " + user.getName()); + } + + + public static void followUser(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + User user = user_api.followUser(target_name); + System.out.println("Following " + user.getName()); + } + + public static void unfollowUser(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + User user = user_api.unfollowUser(target_name); + System.out.println("Unfollowing " + user.getName()); + } + + public static void getFollowersName(BlackBird session, String target_name) throws TwitterException { + UserAPI user_api = session.getUserAPI(); + System.out.println(target_name + "'s followers:"); + for (User user : user_api.getFollowersList(target_name, -1, "")) { + String name = user.getName(); + System.out.println(name); + } + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/BlackBird.java b/src/main/java/com/github/langsdorf/blackbird/BlackBird.java new file mode 100644 index 0000000..25b1f72 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/BlackBird.java @@ -0,0 +1,107 @@ +package com.github.langsdorf.blackbird; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import com.github.langsdorf.blackbird.api.DirectMessageAPI; +import com.github.langsdorf.blackbird.api.TweetAPI; +import com.github.langsdorf.blackbird.api.UserAPI; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.factory.DirectMessageFactory; +import com.github.langsdorf.blackbird.factory.TweetFactory; +import com.github.langsdorf.blackbird.factory.UserFactory; +import com.github.langsdorf.blackbird.http.URLList; +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth10aService; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Setter(AccessLevel.PACKAGE) +@Getter +public class BlackBird implements URLList { + + private String consumerKey; + private String consumerSecret; + + private String accessToken; + private String accessTokenSecret; + + private OAuth10aService oauthService; + private OAuth1AccessToken oauthAccessToken; + private OAuth1RequestToken oauthRequestToken; + + private DirectMessageFactory directMessageFactory; + private DirectMessageAPI directMessageAPI; + + private UserFactory userFactory; + private UserAPI userAPI; + + private TweetFactory tweetFactory; + private TweetAPI tweetAPI; + + public BlackBird(String consumerKey, String consumerSecret) { + setConsumerKey(consumerKey); + setConsumerSecret(consumerSecret); + } + + public BlackBird(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) { + setConsumerKey(consumerKey); + setConsumerSecret(consumerSecret); + setAccessToken(accessToken); + setAccessTokenSecret(accessTokenSecret); + auth(); + } + + @SneakyThrows(Exception.class) + private void auth() { + OAuth10aService service = new ServiceBuilder(getConsumerKey()).apiSecret(getConsumerSecret()) + .build(TwitterApi.instance()); + OAuth1RequestToken requestToken = service.getRequestToken(); + OAuth1AccessToken oauthAccessToken = new OAuth1AccessToken(getAccessToken(), getAccessTokenSecret()); + + setOauthAccessToken(oauthAccessToken); + setOauthService(service); + setOauthRequestToken(requestToken); + checkCredentials(); + } + + @SneakyThrows(Exception.class) + public void checkCredentials() { + String URL = PROTECTED_RESOURCE_URL; + OAuthRequest request = new OAuthRequest(Verb.GET, URL); + getOauthService().signRequest(getOauthAccessToken(), request); + Response response = getOauthService().execute(request); + if (response.getCode() >= 200 && response.getCode() < 300) { + init(); + } else { + throw new TwitterException("Missing or incorrect authentication credentials."); + } + } + + public BlackBird pinAuth(String pin) throws IOException, InterruptedException, ExecutionException { + OAuth1AccessToken accessToken = oauthService.getAccessToken(oauthRequestToken, pin); + setOauthAccessToken(accessToken); + checkCredentials(); + return this; + } + + void init() { + setDirectMessageFactory(new DirectMessageFactory(this)); + setUserFactory(new UserFactory(this)); + setTweetFactory(new TweetFactory(this)); + + setDirectMessageAPI(new DirectMessageAPI(this)); + setUserAPI(new UserAPI(this)); + setTweetAPI(new TweetAPI(this)); + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/URLBasedOAuth.java b/src/main/java/com/github/langsdorf/blackbird/URLBasedOAuth.java new file mode 100644 index 0000000..99341b3 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/URLBasedOAuth.java @@ -0,0 +1,46 @@ +package com.github.langsdorf.blackbird; + +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.oauth.OAuth10aService; + +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Getter +@Setter + +public class URLBasedOAuth { + + private String consumerKey; + private String consumerSecret; + private BlackBird session; + + public URLBasedOAuth(String consumerKey, String consumerSecret) { + setConsumerKey(consumerKey); + setConsumerSecret(consumerSecret); + setSession(new BlackBird(consumerKey, consumerSecret)); + prepare(); + } + + public String getAuthorizationUrl() { + return getSession().getOauthService().getAuthorizationUrl(getSession().getOauthRequestToken()); + } + + @SneakyThrows(Exception.class) + public void prepare() { + OAuth10aService service = new ServiceBuilder(getConsumerKey()) + .apiSecret(getConsumerSecret()) + .build(TwitterApi.instance()); + OAuth1RequestToken requestToken = service.getRequestToken(); + getSession().setOauthService(service); + getSession().setOauthRequestToken(requestToken); + } + + @SneakyThrows(Exception.class) + public BlackBird authenticate(String pin) { + return session.pinAuth(pin); + } +} diff --git a/src/main/java/com/github/langsdorf/blackbird/api/DirectMessageAPI.java b/src/main/java/com/github/langsdorf/blackbird/api/DirectMessageAPI.java new file mode 100644 index 0000000..b850410 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/api/DirectMessageAPI.java @@ -0,0 +1,47 @@ +package com.github.langsdorf.blackbird.api; + +import java.util.List; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.directmessage.DirectMessage; +import com.github.langsdorf.blackbird.directmessage.DirectMessageI; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.factory.DirectMessageFactory; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class DirectMessageAPI implements DirectMessageI { + + private BlackBird session; + + public DirectMessage showDirectMessage(long id) throws TwitterException { + return getFactory().showDirectMessage(id); + } + + public List getDirectMessages() throws TwitterException { + return getFactory().getDirectMessages(); + } + + public List getDirectMessages(int max) throws TwitterException { + return getFactory().getDirectMessages(max); + } + + public DirectMessage sendDirectMessage(long recipientId, String text) { + return getFactory().sendDirectMessage(recipientId, text); + } + + public void destroyDirectMessage(long id) throws TwitterException { + getFactory().destroyDirectMessage(id); + } + + public DirectMessageFactory getFactory() { + return getSession().getDirectMessageFactory(); + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/api/TweetAPI.java b/src/main/java/com/github/langsdorf/blackbird/api/TweetAPI.java new file mode 100644 index 0000000..e594909 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/api/TweetAPI.java @@ -0,0 +1,76 @@ +package com.github.langsdorf.blackbird.api; + +import java.util.List; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.factory.TweetFactory; +import com.github.langsdorf.blackbird.tweet.Tweet; +import com.github.langsdorf.blackbird.tweet.TweetI; +import com.github.langsdorf.blackbird.user.list.BirdList; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class TweetAPI implements TweetI { + + private BlackBird session; + + public Tweet createTweet(String status) throws TwitterException { + return getFactory().createTweet(status); + } + + public Tweet deleteTweet(long tweetId) throws TwitterException { + return getFactory().deleteTweet(tweetId); + } + + public Tweet showTweet(long tweetId) throws TwitterException { + return getFactory().showTweet(tweetId); + } + + public List tweetLookup(long... tweetsId) throws TwitterException { + return getFactory().tweetLookup(tweetsId); + } + + public Tweet retweet(long tweetId) throws TwitterException { + return getFactory().retweet(tweetId); + } + + public Tweet unretweet(long tweetId) throws TwitterException { + return getFactory().unretweet(tweetId); + } + + public List getRetweets(long tweetId, int count) throws TwitterException { + return getFactory().getRetweets(tweetId, count); + } + + public BirdList getRetweetersId(long tweetId, int count, String cursor) throws TwitterException { + return getFactory().getRetweetersId(tweetId, count, cursor); + } + + public Tweet like(long tweetId) throws TwitterException { + return getFactory().like(tweetId); + } + + public Tweet unlike(long tweetId) throws TwitterException { + return getFactory().unlike(tweetId); + } + + public List getLikedTweets(String screenName, int count) throws TwitterException { + return getFactory().getLikedTweets(screenName, count); + } + + public List getLikedTweets(long userId, int count) throws TwitterException { + return getFactory().getLikedTweets(userId, count); + } + + public TweetFactory getFactory() { + return getSession().getTweetFactory(); + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/api/UserAPI.java b/src/main/java/com/github/langsdorf/blackbird/api/UserAPI.java new file mode 100644 index 0000000..9ef406c --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/api/UserAPI.java @@ -0,0 +1,222 @@ +package com.github.langsdorf.blackbird.api; + +import java.util.List; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.factory.UserFactory; +import com.github.langsdorf.blackbird.user.User; +import com.github.langsdorf.blackbird.user.UserI; +import com.github.langsdorf.blackbird.user.list.BirdList; +import com.github.langsdorf.blackbird.user.misc.AccountSettings; +import com.github.langsdorf.blackbird.user.misc.Banner; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class UserAPI implements UserI { + + private BlackBird session; + + public AccountSettings getAccountSettings() throws TwitterException { + return getFactory().getAccountSettings(); + } + + public List getProfileBanner(String screenName) throws TwitterException { + return getFactory().getProfileBanner(screenName); + } + + public List getProfileBanner(long userId) throws TwitterException { + return getFactory().getProfileBanner(userId); + } + + public void removeProfileBanner() throws TwitterException { + getFactory().removeProfileBanner(); + } + + public AccountSettings updateAccountSettings(boolean sleep_time_enabled, int start_sleep_time, int end_sleep_time, + String time_zone, int trend_location_woeid, String lang) throws TwitterException { + return getFactory().updateAccountSettings(sleep_time_enabled, start_sleep_time, end_sleep_time, time_zone, + trend_location_woeid, lang); + } + + public User updateProfile(String name, String url, String location, String description, String profile_link_color) + throws TwitterException { + return getFactory().updateProfile(name, url, location, description, profile_link_color); + } + + public void updateProfileBanner(String image) throws TwitterException { + getFactory().updateProfileBanner(image); + } + + public void updateProfileBanner(String image, int width, int height, int offset_left, int offset_top) + throws TwitterException { + getFactory().updateProfileBanner(image, width, height, offset_left, offset_top); + } + + public void updateProfileImage(String image) throws TwitterException { + getFactory().updateProfileImage(image); + } + + public BirdList getBlockIDList(String cursor) throws TwitterException { + return getFactory().getBlockIDList(cursor); + } + + public BirdList getBlockIDList() throws TwitterException { + return getFactory().getBlockIDList(); + } + + public BirdList getBlockUserList(String cursor) throws TwitterException { + return getFactory().getBlockUserList(cursor); + } + + public BirdList getBlockUserList() throws TwitterException { + return getFactory().getBlockUserList(); + } + + public BirdList getMutesIDList(String cursor) throws TwitterException { + return getFactory().getMutesIDList(cursor); + } + + public BirdList getMutesUserList(String cursor) throws TwitterException { + return getFactory().getMutesUserList(cursor); + } + + public BirdList getMutesIDList() throws TwitterException { + return getFactory().getMutesIDList(); + } + + public BirdList getMutesUserList() throws TwitterException { + return getFactory().getMutesUserList(); + } + + public User blockUser(String screenName) throws TwitterException { + return getFactory().blockUser(screenName); + } + + public User blockUser(long userId) throws TwitterException { + return getFactory().blockUser(userId); + } + + public User unblockUser(String screenName) throws TwitterException { + return getFactory().unblockUser(screenName); + } + + public User unblockUser(long userId) throws TwitterException { + return getFactory().unblockUser(userId); + } + + public User muteUser(String screenName) throws TwitterException { + return getFactory().muteUser(screenName); + } + + public User muteUser(long userId) throws TwitterException { + return getFactory().muteUser(userId); + } + + public User unmuteUser(String screenName) throws TwitterException { + return getFactory().unmuteUser(screenName); + } + + public User unmuteUser(long userId) throws TwitterException { + return getFactory().unmuteUser(userId); + } + + public User reportSpam(String screenName, boolean block) throws TwitterException { + return getFactory().reportSpam(screenName, block); + } + + public User reportSpam(long userId, boolean block) throws TwitterException { + return getFactory().reportSpam(userId, block); + } + + public BirdList getFollowersIDList(String screenName, int count, String cursor) throws TwitterException { + return getFactory().getFollowersIDList(screenName, count, cursor); + } + + public BirdList getFollowersIDList(long userId, int count, String cursor) throws TwitterException { + return getFactory().getFollowersIDList(userId, count, cursor); + } + + public BirdList getFollowersList(String screenName, int count, String cursor) throws TwitterException { + return getFactory().getFollowersList(screenName, count, cursor); + } + + public BirdList getFollowersList(long userId, int count, String cursor) throws TwitterException { + return getFactory().getFollowersList(userId, count, cursor); + } + + public BirdList getFollowingIDList(String screenName, int count, String cursor) throws TwitterException { + return getFactory().getFollowingIDList(screenName, count, cursor); + } + + public BirdList getFollowingIDList(long userId, int count, String cursor) throws TwitterException { + return getFactory().getFollowingIDList(userId, count, cursor); + } + + public BirdList getFollowingList(String screenName, int count, String cursor) throws TwitterException { + return getFactory().getFollowingList(screenName, count, cursor); + } + + public BirdList getFollowingList(long userId, int count, String cursor) throws TwitterException { + return getFactory().getFollowingList(userId, count, cursor); + } + + public BirdList getIncomingRequests(String cursor) throws TwitterException { + return getFactory().getIncomingRequests(cursor); + } + + public List relationsLookup(String... screen_names) throws TwitterException { + return getFactory().relationsLookup(screen_names); + } + + public List relationsLookup(long... usersId) throws TwitterException { + return getFactory().relationsLookup(usersId); + } + + public BirdList getOutcomingRequests(String cursor) throws TwitterException { + return getFactory().getOutcomingRequests(cursor); + } + + public BirdList userLookup(String... screenNames) throws TwitterException { + return getFactory().userLookup(screenNames); + } + + public BirdList userLookup(long... usersId) throws TwitterException { + return getFactory().userLookup(usersId); + } + + public User getUser(String screenName) throws TwitterException { + return getFactory().getUser(screenName); + } + + public User getUser(long userId) throws TwitterException { + return getFactory().getUser(userId); + } + + public User followUser(String screenName) throws TwitterException { + return getFactory().followUser(screenName); + } + + public User followUser(long userId) throws TwitterException { + return getFactory().followUser(userId); + } + + public User unfollowUser(String screenName) throws TwitterException { + return getFactory().unfollowUser(screenName); + } + + public User unfollowUser(long userId) throws TwitterException { + return getFactory().unfollowUser(userId); + } + + public UserFactory getFactory() { + return getSession().getUserFactory(); + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/directmessage/DirectMessage.java b/src/main/java/com/github/langsdorf/blackbird/directmessage/DirectMessage.java new file mode 100644 index 0000000..7540889 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/directmessage/DirectMessage.java @@ -0,0 +1,25 @@ +package com.github.langsdorf.blackbird.directmessage; + +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@AllArgsConstructor +@NoArgsConstructor +public class DirectMessage { + + private long id; + private long senderId; + private long recipientId; + private String message; + private String nextCursor; + private Date createdAt; + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/directmessage/DirectMessageI.java b/src/main/java/com/github/langsdorf/blackbird/directmessage/DirectMessageI.java new file mode 100644 index 0000000..8abbd0b --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/directmessage/DirectMessageI.java @@ -0,0 +1,86 @@ +package com.github.langsdorf.blackbird.directmessage; + +import java.util.List; + +import com.github.langsdorf.blackbird.exception.TwitterException; + +public interface DirectMessageI { + + /** + * Returns a single Direct Message event by the given id. + *
+ *
Retorna uma mensagem direta especificada pelo id. + *
+ *
https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-event + *
+ *
https://api.twitter.com/1.1/direct_messages/events/show.json + * + * @param id DirectMessage id. + * @return DirectMessage + * @throws TwitterException + * */ + DirectMessage showDirectMessage(long id) throws TwitterException; + + /** + * Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order. + *
+ *
Retorna todas as mensagens diretas (enviadas e recebidas) dentro dos últimos 30 dias. Organizadas em ordem cronológica reversa. + *
+ *
https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/list-events + *
+ *
https://api.twitter.com/1.1/direct_messages/events/list.json + * . + * @return List of DirectMessages + * @throws TwitterException + * */ + List getDirectMessages() throws TwitterException; + + /** + * Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order. + *
+ *
Retorna todas as mensagens diretas (enviadas e recebidas) dentro dos últimos 30 dias. Organizadas em ordem cronológica reversa. + *
+ *
https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/list-events + *
+ *
https://api.twitter.com/1.1/direct_messages/events/list.json + * . + * @return List of DirectMessages + * @param max Max number of events to be returned. 20 default. 50 max. + * @param max Quantidade máxima de mensagens que devem retornar. 20 padrão, 50 máximo. + * @throws TwitterException + * */ + List getDirectMessages(int max) throws TwitterException; + + /** + * Sends a new Direct Message to the specified user from the authenticating user + *
+ *
Envia uma nova mensagem direta para um determinado usuário utilizando o usuário autenticado. + *
+ *
https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message + *
+ *
https://api.twitter.com/1.1/direct_messages/events/new.json + * . + * @return DirectMessage + * @param recipientId The ID of the user who should receive the direct message. + * @param text The text of your Direct Message. + * @param recipientId O id do usuário que irá receber a mensagem. + * @param text A mensagem a ser enviada. + * */ + DirectMessage sendDirectMessage(long recipientId, String text); + + /** + * Deletes the direct message specified in the required ID parameter. + *
+ *
Deleta a mensagem direta especificada pelo Id. + *
+ *
https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message-event + *
+ *
https://api.twitter.com/1.1/direct_messages/events/destroy.json + * + * @param id DirectMessage id. + * @throws TwitterException + * */ + void destroyDirectMessage(long id) throws TwitterException; + + +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/exception/TwitterException.java b/src/main/java/com/github/langsdorf/blackbird/exception/TwitterException.java new file mode 100644 index 0000000..da6e157 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/exception/TwitterException.java @@ -0,0 +1,124 @@ +package com.github.langsdorf.blackbird.exception; + +import java.io.IOException; +import java.util.StringJoiner; + +import com.github.langsdorf.blackbird.http.HTTPStatusCode; +import com.github.langsdorf.blackbird.json.JSONException; +import com.github.langsdorf.blackbird.json.JSONObject; +import com.github.scribejava.core.model.Response; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Getter +@Setter(AccessLevel.PROTECTED) +public class TwitterException extends Exception implements HTTPStatusCode { + + private static final long serialVersionUID = -8049135171139755980L; + private Response response; + private int statusCode; + private int errorCode; + private String message; + private String errorMessage; + + public TwitterException(String message, Response res) throws IOException { + this(res.getBody()); + setResponse(res); + setStatusCode(res.getCode()); + } + + public TwitterException(String message, Throwable throwable) { + super(message, throwable); + setStatusCode(-1); + setErrorCode(-1); + setMessage(message); + read(message); + } + + public TwitterException(String message) { + this(message, (Throwable) null); + } + + @SneakyThrows(JSONException.class) + private void read(String message) { + if (message != null && message.startsWith("{") && message.endsWith("}")) { + JSONObject jsonObject = new JSONObject(message); + if (jsonObject != null && !jsonObject.isNull("errors")) { + JSONObject error = jsonObject.getJSONArray("errors").getJSONObject(0); + setErrorMessage(error.getString("message")); + setErrorCode(error.getInt("code")); + } + } + } + + public String getLocalizedMessage() { + StringJoiner stringJoiner = new StringJoiner(System.lineSeparator(), System.lineSeparator(), System.lineSeparator()); + if (getStatusCode() != -1) { + stringJoiner.add(getMessageByStatusCode()); + } + if (getErrorCode() != -1 && getErrorMessage() != null) { + stringJoiner.add("Message: " + getErrorMessage()); + stringJoiner.add("Error code: " + getErrorCode()); + } + if (!getMessage().equals("")) { + stringJoiner.add(getMessage()); + } + return stringJoiner.toString(); + } + + /** + * @author Twitter4j. All credits to them for this. + */ + private String getMessageByStatusCode() { + String cause = null; + switch (getStatusCode()) { + case 304: + cause = "There was no new data to return."; + break; + case 400: + cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting (https://developer.twitter.com/en/docs/basics/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response."; + break; + case 401: + cause = "Authentication credentials (https://developer.twitter.com/en/docs/basics/authentication/overview/oauth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync."; + break; + case 403: + cause = "The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following)."; + break; + case 404: + cause = "The URI requested is invalid or the resource requested, such as a user, does not exists. Also returned when the requested format is not supported by the requested method."; + break; + case 406: + cause = "Returned by the Search API when an invalid format is specified in the request.\nReturned by the Streaming API when one or more of the parameters are not suitable for the resource. The track parameter, for example, would throw this error if:\n The track keyword is too long or too short.\n The bounding box specified is invalid.\n No predicates defined for filtered resource, for example, neither track nor follow parameter defined.\n Follow userid cannot be read."; + break; + case 420: + cause = "Returned by the Search and Trends API when you are being rate limited (https://developer.twitter.com/en/docs/basics/rate-limiting).\nReturned by the Streaming API:\n Too many login attempts in a short period of time.\n Running too many copies of the same application authenticating with the same account name."; + break; + case 422: + cause = "Returned when an image uploaded to POST account/update_profile_banner(https://developer.twitter.com/en/docs/accounts-and-users/user-profile-images-and-banners) is unable to be processed."; + break; + case 429: + cause = "Returned in API v1.1 when a request cannot be served due to the application's rate limit having been exhausted for the resource. See Rate Limiting in API v1.1.(https://developer.twitter.com/en/docs/basics/rate-limiting)"; + break; + case 500: + cause = "Something is broken. Please post to the forum (https://twittercommunity.com/) so the Twitter team can investigate."; + break; + case 502: + cause = "Twitter is down or being upgraded."; + break; + case 503: + cause = "The Twitter servers are up, but overloaded with requests. Try again later."; + break; + case 504: + cause = "The Twitter servers are up, but the request couldn't be serviced due to some failure within our stack. Try again later."; + break; + default: + cause = ""; + break; + } + return String.valueOf(getStatusCode()) + ":" + cause; + } + +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/factory/DirectMessageFactory.java b/src/main/java/com/github/langsdorf/blackbird/factory/DirectMessageFactory.java new file mode 100644 index 0000000..6151a58 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/factory/DirectMessageFactory.java @@ -0,0 +1,158 @@ +package com.github.langsdorf.blackbird.factory; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.directmessage.DirectMessage; +import com.github.langsdorf.blackbird.directmessage.DirectMessageI; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.http.BasicRequest; +import com.github.langsdorf.blackbird.http.CustomRequest; +import com.github.langsdorf.blackbird.http.URLList; +import com.github.langsdorf.blackbird.json.JSONArray; +import com.github.langsdorf.blackbird.json.JSONException; +import com.github.langsdorf.blackbird.json.JSONObject; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class DirectMessageFactory implements DirectMessageI, URLList { + + private BlackBird session; + + @SneakyThrows(value = { NumberFormatException.class, JSONException.class, IOException.class }) + public DirectMessage showDirectMessage(long id) throws TwitterException { + String URL = DIRECT_MESSAGE_SHOW.replace("VALUE1", Long.toString(id)); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300 && response.getBody().contains("\"events\"")) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + JSONObject message = jsonObject.getJSONObject("event"); + + Long m_id = Long.parseLong(message.getString("id")); + Long timestamp = Long.parseLong(message.getString("created_timestamp")); + + JSONObject data_list = message.getJSONObject("message_create"); + Long sender_id = Long.parseLong(data_list.getString("sender_id")); + + JSONObject target = data_list.getJSONObject("target"); + Long target_id = Long.parseLong(target.getString("recipient_id")); + + JSONObject message_data = data_list.getJSONObject("message_data"); + String text = message_data.getString("text"); + + DirectMessage dm = new DirectMessage(); + dm.setId(m_id); + dm.setCreatedAt(new Date(timestamp * 1000)); + dm.setMessage(text); + dm.setRecipientId(target_id); + dm.setSenderId(sender_id); + return dm; + } + + throw new TwitterException("", response); + } + + public List getDirectMessages() throws TwitterException { + return getDirectMessages(20); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List getDirectMessages(int max) throws TwitterException { + List dm_list = new ArrayList(); + String URL = DIRECT_MESSAGE_LIST.replace("$?count=VALUE1$", "?count=" + max); + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + if (response.getCode() >= 200 && response.getCode() < 300 && response.getBody().contains("\"events\"")) { + String body = response.getBody(); + System.out.println(body); + JSONObject jsonObject = new JSONObject(body); + + JSONArray messages_list = jsonObject.getJSONArray("events"); + String next_cursor = ""; + if (!jsonObject.isNull("next_cursor")) { + next_cursor = jsonObject.getString("next_cursor"); + } + + for (int i = 0; i < messages_list.length(); ++i) { + JSONObject message = new JSONObject(messages_list.getString(i)); + Long id = Long.parseLong(message.getString("id")); + Long timestamp = Long.parseLong(message.getString("created_timestamp")); + + JSONObject data_list = message.getJSONObject("message_create"); + Long sender_id = Long.parseLong(data_list.getString("sender_id")); + + JSONObject target = data_list.getJSONObject("target"); + Long target_id = Long.parseLong(target.getString("recipient_id")); + + JSONObject message_data = data_list.getJSONObject("message_data"); + String text = message_data.getString("text"); + DirectMessage dm = new DirectMessage(); + dm.setId(id); + dm.setCreatedAt(new Date(timestamp * 1000)); + dm.setMessage(text); + dm.setRecipientId(target_id); + dm.setSenderId(sender_id); + dm.setNextCursor(next_cursor); + dm_list.add(dm); + } + } + + return dm_list; + } + + @SneakyThrows(JSONException.class) + public DirectMessage sendDirectMessage(long recipientId, String text) { + String URL = DIRECT_MESSAGE_NEW; + String pattern = MESSAGE_CREATE_PATTERN.replace("$ID$", Long.toString(recipientId)).replace("$TEXT$", text); + String response = new CustomRequest(getSession()).request(URL, pattern.getBytes(StandardCharsets.UTF_8)); + JSONObject jsonObject = new JSONObject(response); + + JSONObject message = jsonObject.getJSONObject("event"); + Long m_id = Long.parseLong(message.getString("id")); + Long timestamp = Long.parseLong(message.getString("created_timestamp")); + + JSONObject data_list = message.getJSONObject("message_create"); + Long sender_id = Long.parseLong(data_list.getString("sender_id")); + + JSONObject target = data_list.getJSONObject("target"); + Long target_id = Long.parseLong(target.getString("recipient_id")); + + JSONObject message_data = data_list.getJSONObject("message_data"); + String text_m = message_data.getString("text"); + + DirectMessage dm = new DirectMessage(); + dm.setId(m_id); + dm.setCreatedAt(new Date(timestamp * 1000)); + dm.setMessage(text_m); + dm.setRecipientId(target_id); + dm.setSenderId(sender_id); + return dm; + } + + @SneakyThrows(IOException.class) + public void destroyDirectMessage(long id) throws TwitterException { + String URL = DIRECT_MESSAGE_DESTROY.replace("VALUE1", Long.toString(id)); + Response response = new BasicRequest(getSession()).request(Verb.DELETE, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + return; + } + + throw new TwitterException("", response); + } + +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/factory/TweetFactory.java b/src/main/java/com/github/langsdorf/blackbird/factory/TweetFactory.java new file mode 100644 index 0000000..343c93d --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/factory/TweetFactory.java @@ -0,0 +1,260 @@ +package com.github.langsdorf.blackbird.factory; + +import java.io.IOException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; +import java.util.StringJoiner; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.http.BasicRequest; +import com.github.langsdorf.blackbird.http.URLList; +import com.github.langsdorf.blackbird.json.JSONArray; +import com.github.langsdorf.blackbird.json.JSONException; +import com.github.langsdorf.blackbird.json.JSONObject; +import com.github.langsdorf.blackbird.tweet.Tweet; +import com.github.langsdorf.blackbird.tweet.TweetI; +import com.github.langsdorf.blackbird.user.User; +import com.github.langsdorf.blackbird.user.list.BirdList; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class TweetFactory implements TweetI, URLList { + + private BlackBird session; + + @SuppressWarnings("deprecation") + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet createTweet(String status) throws TwitterException { + String URL = STATUSES_CREATE.replace("$PARAM$", "status=" + URLEncoder.encode(status)); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet deleteTweet(long tweetId) throws TwitterException { + String URL = STATUSES_DESTROY.replace("$ID$", Long.toString(tweetId)); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet showTweet(long tweetId) throws TwitterException { + String URL = STATUSES_SHOW.replace("$PARAM$", "id=" + tweetId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List tweetLookup(long... tweetsId) throws TwitterException { + String URL = STATUSES_LOOKUP; + + if (tweetsId.length > 100) + throw new TwitterException("Max 100 users per request"); + if (tweetsId.length == 1) { + URL = URL.replace("$PARAM$", "id=" + tweetsId[0]); + } else { + StringJoiner sj = new StringJoiner(","); + for (long names : tweetsId) { + sj.add(Long.toString(names)); + } + URL = URL.replace("$PARAM$", "id=" + sj.toString()); + } + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return tweetListCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet retweet(long tweetId) throws TwitterException { + String URL = STATUSES_RETWEET.replace("$ID$", Long.toString(tweetId)); + + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet unretweet(long tweetId) throws TwitterException { + String URL = STATUSES_UNRETWEET.replace("$ID$", Long.toString(tweetId)); + + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List getRetweets(long tweetId, int count) throws TwitterException { + String URL = STATUSES_RETWEETS.replace("$ID$", Long.toString(tweetId)); + if (count != -1) + URL = URL + "?count=" + count; + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return tweetListCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getRetweetersId(long tweetId, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("id=" + tweetId); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = STATUSES_RETWEETERS_IDS + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getSession().getUserFactory().getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet like(long tweetId) throws TwitterException { + String URL = FAVORITES_CREATE.replace("$PARAM$", "id=" + tweetId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public Tweet unlike(long tweetId) throws TwitterException { + String URL = FAVORITES_DESTROY.replace("$PARAM$", "id=" + tweetId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getTweetCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List getLikedTweets(String screenName, int count) throws TwitterException { + String URL = FAVORITES_LIST.replace("$PARAM$", "screen_name=" + screenName); + if (count != -1) + URL = URL + "&count=" + count; + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return tweetListCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List getLikedTweets(long userId, int count) throws TwitterException { + String URL = FAVORITES_LIST.replace("$PARAM$", "user_id=" + userId); + if (count != -1) + URL = URL + "&count=" + count; + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return tweetListCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(JSONException.class) + public Tweet getTweetCompact(JSONObject jsonObject) { + String createdAt = jsonObject.isNull("created_at") ? "" : jsonObject.getString("created_at"); + long tweetId = jsonObject.isNull("id") ? 0 : jsonObject.getLong("id"); + String text = jsonObject.isNull("text") ? "" : jsonObject.getString("text"); + int retweetCount = jsonObject.isNull("retweet_count") ? -1 : jsonObject.getInt("retweet_count"); + int favoriteCount = jsonObject.isNull("favorite_count") ? -1 : jsonObject.getInt("favorite_count"); + + JSONObject jsonUser = jsonObject.getJSONObject("user"); + User user = getSession().getUserFactory().getUserCompact(jsonUser); + + return new Tweet(tweetId, text, createdAt, retweetCount, favoriteCount, user); + } + + @SneakyThrows(JSONException.class) + public List tweetListCompact(JSONArray jsonArray) { + List tweet_list = new ArrayList(); + + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonTweet = jsonArray.getJSONObject(i); + tweet_list.add(getTweetCompact(jsonTweet)); + } + + return tweet_list; + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/factory/UserFactory.java b/src/main/java/com/github/langsdorf/blackbird/factory/UserFactory.java new file mode 100644 index 0000000..8fb08bc --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/factory/UserFactory.java @@ -0,0 +1,986 @@ +package com.github.langsdorf.blackbird.factory; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.http.BasicRequest; +import com.github.langsdorf.blackbird.http.URLList; +import com.github.langsdorf.blackbird.json.JSONArray; +import com.github.langsdorf.blackbird.json.JSONException; +import com.github.langsdorf.blackbird.json.JSONObject; +import com.github.langsdorf.blackbird.user.User; +import com.github.langsdorf.blackbird.user.UserI; +import com.github.langsdorf.blackbird.user.list.BirdList; +import com.github.langsdorf.blackbird.user.list.BirdListImp; +import com.github.langsdorf.blackbird.user.misc.AccountSettings; +import com.github.langsdorf.blackbird.user.misc.Banner; +import com.github.langsdorf.blackbird.user.misc.BannerSizes; +import com.github.langsdorf.blackbird.user.misc.Relationships; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class UserFactory implements UserI, URLList { + + private BlackBird session; + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public AccountSettings getAccountSettings() throws TwitterException { + String URL = ACCOUNT_SETTINGS; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getAccountSettingsCompact(jsonObject); + } + throw new TwitterException("", response); + } + + public List getProfileBanner(String screenName) throws TwitterException { + return getProfileBannerCompact(screenName, 0); + } + + public List getProfileBanner(long userId) throws TwitterException { + return getProfileBannerCompact("", userId); + } + + @SneakyThrows(value = { IOException.class }) + public void removeProfileBanner() throws TwitterException { + String URL = ACCOUNT_REMOVE_PROFILE_BANNER; + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + if (!(response.getCode() >= 200 && response.getCode() < 300)) { + throw new TwitterException("", response); + } + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public AccountSettings updateAccountSettings(boolean sleep_time_enabled, int start_sleep_time, int end_sleep_time, + String time_zone, int trend_location_woeid, String lang) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("sleep_time_enabled=" + sleep_time_enabled); + if (start_sleep_time != -1) + sj.add("start_sleep_time=" + start_sleep_time); + if (end_sleep_time != -1) + sj.add("end_sleep_time=" + end_sleep_time); + if (end_sleep_time != -1) + sj.add("end_sleep_time=" + end_sleep_time); + if (!time_zone.equals("")) + sj.add("time_zone=" + time_zone); + if (trend_location_woeid != -1) + sj.add("trend_location_woeid=" + trend_location_woeid); + if (!lang.equals("")) + sj.add("lang=" + lang); + + String URL = ACCOUNT_SETTINGS.replace("$PARAM$", sj.toString()); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getAccountSettingsCompact(jsonObject); + } + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User updateProfile(String name, String url, String location, String description, String profile_link_color) + throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + if (!name.equals("")) + sj.add("name=" + name); + if (!url.equals("")) + sj.add("url=" + name); + if (!location.equals("")) + sj.add("location=" + location); + if (!description.equals("")) + sj.add("description=" + description); + if (!profile_link_color.equals("")) + sj.add("profile_link_color=" + profile_link_color); + + String URL = ACCOUNT_UPDATE_PROFILE.replace("$PARAM$", sj.toString()); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + throw new TwitterException("", response); + } + + public void updateProfileBanner(String image) throws TwitterException { + updateProfileBanner(image, -1, -1, -1, -1); + } + + @SneakyThrows(value = { IOException.class }) + public void updateProfileBanner(String image, int width, int height, int offset_left, int offset_top) + throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("banner=" + image); + if (width != -1) + sj.add("width=" + width); + if (height != -1) + sj.add("height=" + height); + if (offset_left != -1) + sj.add("offset_left=" + offset_left); + if (offset_top != -1) + sj.add("offset_top=" + offset_top); + + String URL = ACCOUNT_UPDATE_PROFILE_BANNER.replace("$PARAM$", sj.toString()); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + if (!(response.getCode() >= 200 && response.getCode() < 300)) { + throw new TwitterException("", response); + } + } + + @SneakyThrows(value = { IOException.class }) + public void updateProfileImage(String image) throws TwitterException { + String URL = ACCOUNT_UPDATE_PROFILE_IMAGE.replace("$PARAM$", "image=" + image); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + if (!(response.getCode() >= 200 && response.getCode() < 300)) { + throw new TwitterException("", response); + } + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getBlockIDList(String cursor) throws TwitterException { + String URL = BLOCKS_ID_LIST + "?cursor=" + cursor; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getBlockIDList() throws TwitterException { + String URL = BLOCKS_ID_LIST; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getBlockUserList() throws TwitterException { + String URL = BLOCKS_USERS_LIST; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getBlockUserList(String cursor) throws TwitterException { + String URL = BLOCKS_USERS_LIST + "?cursor=" + cursor; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getMutesIDList() throws TwitterException { + String URL = MUTES_ID_LIST; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getMutesUserList() throws TwitterException { + String URL = MUTES_USER_LIST; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getMutesIDList(String cursor) throws TwitterException { + String URL = MUTES_ID_LIST + "?cursor=" + cursor; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getMutesUserList(String cursor) throws TwitterException { + String URL = MUTES_USER_LIST + "?cursor=" + cursor; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User blockUser(String screenName) throws TwitterException { + String URL = BLOCKS_CREATE.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User blockUser(long userId) throws TwitterException { + String URL = BLOCKS_CREATE.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User unblockUser(String screenName) throws TwitterException { + String URL = BLOCKS_DESTROY.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User unblockUser(long userId) throws TwitterException { + String URL = BLOCKS_DESTROY.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User muteUser(String screenName) throws TwitterException { + String URL = MUTES_CREATE.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User muteUser(long userId) throws TwitterException { + String URL = MUTES_CREATE.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User unmuteUser(String screenName) throws TwitterException { + String URL = MUTES_DESTROY.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User unmuteUser(long userId) throws TwitterException { + String URL = MUTES_DESTROY.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User reportSpam(String screenName, boolean block) throws TwitterException { + String URL = USERS_REPORT_SPAM.replace("$PARAM$", "screen_name=" + screenName).replace("$PARAM2$", + "perform_block=" + block); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User reportSpam(long userId, boolean block) throws TwitterException { + String URL = USERS_REPORT_SPAM.replace("$PARAM$", "user_id=" + userId).replace("$PARAM2$", + "perform_block=" + block); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowersIDList(String screenName, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("screen_name=" + screenName); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_ID_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowersIDList(long userId, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("user_id=" + userId); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_ID_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowersList(String screenName, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("screen_name=" + screenName); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_USER_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowersList(long userId, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("user_id=" + userId); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_USER_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowingIDList(String screenName, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("screen_name=" + screenName); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_ID_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowingIDList(long userId, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("user_id=" + userId); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_ID_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowingList(String screenName, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("screen_name=" + screenName); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_USER_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getFollowingList(long userId, int count, String cursor) throws TwitterException { + StringJoiner sj = new StringJoiner("&"); + sj.add("user_id=" + userId); + if (count != -1) + sj.add("count=" + count); + if (!cursor.equals("")) + sj.add("cursor=" + cursor); + + String URL = FOLLOWERS_USER_LIST + sj.toString(); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getIncomingRequests(String cursor) throws TwitterException { + String URL = FRIENDSHIPS_INCOMING; + if (!cursor.equals("")) + URL = URL + "?cursor=" + cursor; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List relationsLookup(String... screen_names) throws TwitterException { + String URL = FRIENDSHIPS_LOOKUP; + + if (screen_names.length > 100) + throw new TwitterException("Max 100 users per request"); + if (screen_names.length == 1) { + URL = URL.replace("$PARAM$", "screen_name=" + screen_names[0]); + } else { + StringJoiner sj = new StringJoiner(","); + for (String names : screen_names) { + sj.add(names); + } + URL = URL.replace("$PARAM$", "screen_name=" + sj.toString()); + } + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return lookupCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List relationsLookup(long... usersId) throws TwitterException { + String URL = FRIENDSHIPS_LOOKUP; + + if (usersId.length > 100) + throw new TwitterException("Max 100 users per request"); + if (usersId.length == 1) { + URL = URL.replace("$PARAM$", "user_id=" + usersId[0]); + } else { + StringJoiner sj = new StringJoiner(","); + for (long ids : usersId) { + sj.add(Long.toString(ids)); + } + URL = URL.replace("$PARAM$", "user_id=" + sj.toString()); + } + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return lookupCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList getOutcomingRequests(String cursor) throws TwitterException { + String URL = FRIENDSHIPS_OUTGOING; + if (!cursor.equals("")) + URL = URL + "?cursor=" + cursor; + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getIDListCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList userLookup(String... screenNames) throws TwitterException { + String URL = USERS_LOOKUP; + + if (screenNames.length > 100) + throw new TwitterException("Max 100 users per request"); + if (screenNames.length == 1) { + URL = URL.replace("$PARAM$", "screen_name=" + screenNames[0]); + } else { + StringJoiner sj = new StringJoiner(","); + for (String names : screenNames) { + sj.add(names); + } + URL = URL.replace("$PARAM$", "screen_name=" + sj.toString()); + } + + Verb verb; + if (screenNames.length >= 50) { + verb = Verb.POST; + } else { + verb = Verb.GET; + } + + Response response = new BasicRequest(getSession()).request(verb, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return lookupUsersCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public BirdList userLookup(long... usersId) throws TwitterException { + String URL = USERS_LOOKUP; + + if (usersId.length > 100) + throw new TwitterException("Max 100 users per request"); + if (usersId.length == 1) { + URL = URL.replace("$PARAM$", "user_id=" + usersId[0]); + } else { + StringJoiner sj = new StringJoiner(","); + for (Long ids : usersId) { + sj.add(Long.toString(ids)); + } + URL = URL.replace("$PARAM$", "user_id=" + sj.toString()); + } + + Verb verb; + if (usersId.length >= 50) { + verb = Verb.POST; + } else { + verb = Verb.GET; + } + + Response response = new BasicRequest(getSession()).request(verb, URL); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONArray jsonArray = new JSONArray(body); + return lookupUsersCompact(jsonArray); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User getUser(String screenName) throws TwitterException { + String URL = USERS_SHOW.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User getUser(long userId) throws TwitterException { + String URL = USERS_SHOW.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User followUser(String screenName) throws TwitterException { + String URL = FRIENDSHIPS_CREATE.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User followUser(long userId) throws TwitterException { + String URL = FRIENDSHIPS_CREATE.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User unfollowUser(String screenName) throws TwitterException { + String URL = FRIENDSHIPS_DESTROY.replace("$PARAM$", "screen_name=" + screenName); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public User unfollowUser(long userId) throws TwitterException { + String URL = FRIENDSHIPS_DESTROY.replace("$PARAM$", "user_id=" + userId); + Response response = new BasicRequest(getSession()).request(Verb.POST, URL); + + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + return getUserCompact(jsonObject); + } + + throw new TwitterException("", response); + } + + public boolean checkNull(JSONObject json, String s) { + return json.isNull(s); + } + + @SneakyThrows(value = { IOException.class, JSONException.class }) + public List getProfileBannerCompact(String screenName, long userId) throws TwitterException { + String URL = USERS_PROFILE_BANNER; + + if (!screenName.equals("")) { + URL = URL.replace("$PARAM$", "screen_name=" + screenName); + } else { + URL = URL.replace("$PARAM$", "user_id=" + userId); + } + + Response response = new BasicRequest(getSession()).request(Verb.GET, URL); + List banner_list = new ArrayList(); + if (response.getCode() >= 200 && response.getCode() < 300) { + String body = response.getBody(); + JSONObject jsonObject = new JSONObject(body); + JSONObject sizes = jsonObject.getJSONObject("sizes"); + + for (BannerSizes bs : BannerSizes.values()) { + String sizeName = bs.name().toLowerCase(); + if (sizeName.startsWith("s")) { + sizeName = sizeName.replace("s_", ""); + } + JSONObject bannerJson = sizes.getJSONObject(sizeName); + String url = bannerJson.getString("url"); + + Banner banner = new Banner(); + + banner.setSize(bs); + banner.setURL(url); + banner.setUserScreenName(screenName); + + banner_list.add(banner); + } + } + return banner_list; + } + + @SneakyThrows(value = { JSONException.class }) + public AccountSettings getAccountSettingsCompact(JSONObject jsonObject) { + JSONObject sleeptimeJson = jsonObject.getJSONObject("sleep_time"); + + JSONObject timezoneJson = jsonObject.getJSONObject("time_zone"); + + JSONArray trendJson = jsonObject.getJSONArray("trend_location"); + JSONObject trend = trendJson.getJSONObject(0); + + String language = jsonObject.isNull("language") ? "" : jsonObject.getString("language"); + + boolean protectedUser = jsonObject.isNull("protected") ? false : jsonObject.getBoolean("protected"); + + String screen_name = jsonObject.isNull("screen_name") ? "" : jsonObject.getString("screen_name"); + + boolean sleep_time_enabled = sleeptimeJson.isNull("enabled") ? false : sleeptimeJson.getBoolean("enabled"); + int sleep_time_start = sleeptimeJson.isNull("start_time") ? -1 : sleeptimeJson.getInt("start_time"); + int sleep_time_end = sleeptimeJson.isNull("end_time") ? -1 : sleeptimeJson.getInt("end_time"); + + String timezone = timezoneJson.isNull("name") ? "" : timezoneJson.getString("name"); + String timezoneinfo = timezoneJson.isNull("tzinfo_name") ? "" : timezoneJson.getString("tzinfo_name"); + + String country = trend.isNull("country") ? "" : trend.getString("country"); + String countryCode = trend.isNull("countryCode") ? "" : trend.getString("countryCode"); + String location_name = trend.isNull("name") ? "" : trend.getString("name"); + + return new AccountSettings(language, protectedUser, screen_name, sleep_time_enabled, sleep_time_end, + sleep_time_start, timezone, timezoneinfo, country, countryCode, location_name); + } + + @SneakyThrows(value = { JSONException.class }) + public User getUserCompact(JSONObject jsonObject) { + long userId = jsonObject.isNull("id") ? 0 : jsonObject.getLong("id"); + String name = jsonObject.isNull("name") ? "" : jsonObject.getString("name"); + String screenName = jsonObject.isNull("screen_name") ? "" : jsonObject.getString("screen_name"); + String location = jsonObject.isNull("location") ? "" : jsonObject.getString("location"); + String description = jsonObject.isNull("description") ? "" : jsonObject.getString("description"); + String profileWebsite = jsonObject.isNull("url") ? "" : jsonObject.getString("url"); + boolean protectedProfile = jsonObject.isNull("protected") ? false : jsonObject.getBoolean("protected"); + int followers = jsonObject.isNull("followers_count") ? -1 : jsonObject.getInt("followers_count"); + int following = jsonObject.isNull("friends_count") ? -1 : jsonObject.getInt("friends_count"); + String createdAt = jsonObject.isNull("created_at") ? "" : jsonObject.getString("created_at"); + int favouritesCount = jsonObject.isNull("favourites_count") ? -1 : jsonObject.getInt("favourites_count"); + String timeZone = jsonObject.isNull("time_zone") ? "" : jsonObject.getString("time_zone"); + boolean verified = jsonObject.isNull("verified") ? false : jsonObject.getBoolean("verified"); + int tweetsCount = jsonObject.isNull("statuses_count") ? -1 : jsonObject.getInt("statuses_count"); + String language = jsonObject.isNull("lang") ? "" : jsonObject.getString("lang"); + String profileColor = jsonObject.isNull("profile_background_color") ? "" + : jsonObject.getString("profile_background_color"); + String profileBannerUrl = jsonObject.isNull("profile_banner_url") ? "" + : jsonObject.getString("profile_banner_url"); + String profileImageUrl = jsonObject.isNull("profile_image_url") ? "" + : jsonObject.getString("profile_image_url"); + + return new User(userId, name, screenName, location, description, profileWebsite, protectedProfile, followers, + following, createdAt, favouritesCount, timeZone, verified, tweetsCount, language, profileColor, + profileBannerUrl, profileImageUrl, null, null, null, null, null); + } + + @SneakyThrows(value = { JSONException.class }) + public BirdList getIDListCompact(JSONObject jsonObject) { + BirdList id_list = new BirdListImp(); + JSONArray jsonArray = jsonObject.getJSONArray("ids"); + for (int i = 0; i < jsonArray.length(); i++) { + Long id = jsonArray.getLong(i); + id_list.add(id); + } + + String next_cursor = jsonObject.isNull("next_cursor_str") ? "" : jsonObject.getString("next_cursor_str"); + String previous_cursor = jsonObject.isNull("previous_cursor_str") ? "" + : jsonObject.getString("previous_cursor_str"); + id_list.setNextCursor(next_cursor); + id_list.setPreviousCursor(previous_cursor); + + return id_list; + } + + @SneakyThrows(value = { JSONException.class }) + public BirdList getUserListCompact(JSONObject jsonObject) { + BirdList user_list = new BirdListImp(); + JSONArray jsonArray = jsonObject.getJSONArray("users"); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonUser = jsonArray.getJSONObject(i); + User user = getUserCompact(jsonUser); + user_list.add(user); + } + + String next_cursor = jsonObject.isNull("next_cursor_str") ? "" : jsonObject.getString("next_cursor_str"); + String previous_cursor = jsonObject.isNull("previous_cursor_str") ? "" + : jsonObject.getString("previous_cursor_str"); + user_list.setNextCursor(next_cursor); + user_list.setPreviousCursor(previous_cursor); + + return user_list; + } + + @SneakyThrows(value = { JSONException.class }) + public List lookupCompact(JSONArray jsonArray) { + List list_user = new ArrayList(); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + Map> relMap = new HashMap>(); + + User user = getUserCompact(jsonObject); + + JSONArray connections = jsonObject.getJSONArray("connections"); + List relList = new ArrayList(); + for (int i2 = 0; i2 < connections.length(); i2++) { + Relationships rel = Relationships.valueOf(connections.getString(i2).toUpperCase()); + relList.add(rel); + } + + relMap.put(user, relList); + user.setRelationships(relMap); + list_user.add(user); + } + return list_user; + } + + @SneakyThrows(value = { JSONException.class }) + public BirdList lookupUsersCompact(JSONArray jsonArray) { + BirdList user_list = new BirdListImp(); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonUser = jsonArray.getJSONObject(i); + User user = getUserCompact(jsonUser); + user_list.add(user); + } + return user_list; + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/http/BasicRequest.java b/src/main/java/com/github/langsdorf/blackbird/http/BasicRequest.java new file mode 100644 index 0000000..afb9326 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/http/BasicRequest.java @@ -0,0 +1,36 @@ +package com.github.langsdorf.blackbird.http; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth10aService; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class BasicRequest { + + private BlackBird session; + + @SneakyThrows(value = { InterruptedException.class, ExecutionException.class, IOException.class }) + public Response request(Verb verb, String url) throws TwitterException { + OAuth10aService service = getSession().getOauthService(); + OAuth1AccessToken access_token = getSession().getOauthAccessToken(); + OAuthRequest request = new OAuthRequest(verb, url); + service.signRequest(access_token, request); + return service.execute(request); + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/http/CustomRequest.java b/src/main/java/com/github/langsdorf/blackbird/http/CustomRequest.java new file mode 100644 index 0000000..c54df18 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/http/CustomRequest.java @@ -0,0 +1,65 @@ +package com.github.langsdorf.blackbird.http; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth10aService; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter(AccessLevel.PROTECTED) +@AllArgsConstructor +public class CustomRequest { + + private BlackBird session; + + public String request(String u, byte[] out) { + try { + URL url = new URL(u); + URLConnection con = url.openConnection(); + HttpURLConnection http = (HttpURLConnection) con; + http.setRequestMethod("POST"); + http.setDoOutput(true); + + int length = out.length; + http.setFixedLengthStreamingMode(length); + + OAuth10aService service = getSession().getOauthService(); + OAuth1AccessToken accessToken = getSession().getOauthAccessToken(); + OAuthRequest request = new OAuthRequest(Verb.POST, u); + service.signRequest(accessToken, request); + + for (String key : request.getHeaders().keySet()) { + http.setRequestProperty(key, request.getHeaders().get(key)); + } + http.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); + http.connect(); + + OutputStream os = http.getOutputStream(); + os.write(out); + BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream())); + if (http.getResponseCode() >= 200 && http.getResponseCode() < 300) { + return reader.readLine(); + } + + throw new TwitterException(reader.readLine()); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/http/HTTPStatusCode.java b/src/main/java/com/github/langsdorf/blackbird/http/HTTPStatusCode.java new file mode 100644 index 0000000..1797a7b --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/http/HTTPStatusCode.java @@ -0,0 +1,25 @@ +package com.github.langsdorf.blackbird.http; + +/** + * @author Twitter4j. All credits to them for this. + */ +public interface HTTPStatusCode { + + int OK = 200; + int MULTIPLE_CHOICES = 300; + int FOUND = 302; + int NOT_MODIFIED = 304; + int BAD_REQUEST = 400; + int UNAUTHORIZED = 401; + int FORBIDDEN = 403; + int NOT_FOUND = 404; + int NOT_ACCEPTABLE = 406; + int ENHANCE_YOUR_CLAIM = 420; + int UNPROCESSABLE_ENTITY = 422; + int TOO_MANY_REQUESTS = 429; + int INTERNAL_SERVER_ERROR = 500; + int BAD_GATEWAY = 502; + int SERVICE_UNAVAILABLE = 503; + int GATEWAY_TIMEOUT = 504; + +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/http/URLList.java b/src/main/java/com/github/langsdorf/blackbird/http/URLList.java new file mode 100644 index 0000000..db1e418 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/http/URLList.java @@ -0,0 +1,71 @@ +package com.github.langsdorf.blackbird.http; + +public interface URLList { + + String BASE_URL = "https://api.twitter.com/1.1/"; + + String DIRECT_MESSAGE = "direct_messages/events/"; + String DIRECT_MESSAGE_SHOW = BASE_URL + DIRECT_MESSAGE + "show.json?id=VALUE1"; + String DIRECT_MESSAGE_LIST = BASE_URL + DIRECT_MESSAGE + "list.json$?count=VALUE1$"; + String DIRECT_MESSAGE_NEW = BASE_URL + DIRECT_MESSAGE + "new.json"; + String DIRECT_MESSAGE_DESTROY = BASE_URL + DIRECT_MESSAGE + "destroy.json?id=VALUE1"; + + String ACCOUNT = "account/"; + String PROTECTED_RESOURCE_URL = BASE_URL + ACCOUNT + "verify_credentials.json"; + String ACCOUNT_REMOVE_PROFILE_BANNER = BASE_URL + ACCOUNT + "remove_profile_banner.json"; + String ACCOUNT_UPDATE_PROFILE_BANNER = BASE_URL + ACCOUNT + "update_profile_banner.json?$PARAM$"; + String ACCOUNT_UPDATE_PROFILE_IMAGE = BASE_URL + ACCOUNT + "update_profile_image.json?$PARAM$"; + String ACCOUNT_SETTINGS = BASE_URL + ACCOUNT + "settings.json?$PARAM$"; + String ACCOUNT_UPDATE_PROFILE = BASE_URL + ACCOUNT + "update_profile.json?$PARAM$"; + String MESSAGE_CREATE_PATTERN = "{\"event\":{\"type\":\"message_create\",\"message_create\":{\"target\":{\"recipient_id\":\"$ID$\"},\"message_data\":{\"text\":\"$TEXT$\"}}}}"; + + String USERS = "users/"; + String USERS_SHOW = BASE_URL + USERS + "show.json?$PARAM$"; + String USERS_REPORT_SPAM = BASE_URL + USERS + "report_spam.json?$PARAM$&$PARAM2$"; + String USERS_PROFILE_BANNER = BASE_URL + USERS + "profile_banner.json?$PARAM$"; + String USERS_LOOKUP = BASE_URL + USERS + "lookup.json?$PARAM$"; + + String BLOCKS = "blocks/"; + String BLOCKS_CREATE = BASE_URL + BLOCKS + "create.json?$PARAM$"; + String BLOCKS_DESTROY = BASE_URL + BLOCKS + "destroy.json?$PARAM$"; + String BLOCKS_ID_LIST = BASE_URL + BLOCKS + "ids.json"; + String BLOCKS_USERS_LIST = BASE_URL + BLOCKS + "list.json"; + + String MUTES = "mutes/users/"; + String MUTES_CREATE = BASE_URL + MUTES + "create.json?$PARAM$"; + String MUTES_DESTROY = BASE_URL + MUTES + "destroy.json?$PARAM$"; + String MUTES_ID_LIST = BASE_URL + MUTES + "ids.json"; + String MUTES_USER_LIST = BASE_URL + MUTES + "list.json"; + + String FRIENDSHIPS = "friendships/"; + String FRIENDSHIPS_CREATE = BASE_URL + FRIENDSHIPS + "create.json?$PARAM$"; + String FRIENDSHIPS_DESTROY = BASE_URL + FRIENDSHIPS + "destroy.json?$PARAM$"; + String FRIENDSHIPS_SHOW = BASE_URL + FRIENDSHIPS + "show.json?$PARAM$"; + String FRIENDSHIPS_INCOMING = BASE_URL + FRIENDSHIPS + "incoming.json"; + String FRIENDSHIPS_LOOKUP = BASE_URL + FRIENDSHIPS + "lookup.json?$PARAM$"; + String FRIENDSHIPS_OUTGOING = BASE_URL + FRIENDSHIPS + "outgoing.json?$PARAM$"; + + String FOLLOWERS = "followers/"; + String FOLLOWERS_ID_LIST = BASE_URL + FOLLOWERS + "ids.json?"; + String FOLLOWERS_USER_LIST = BASE_URL + FOLLOWERS + "list.json?"; + + String FOLLOWING = "friends/"; + String FOLLOWING_ID_LIST = BASE_URL + FOLLOWING + "ids.json?"; + String FOLLOWING_USER_LIST = BASE_URL + FOLLOWING + "list.json?"; + + String STATUSES = "statuses/"; + String STATUSES_CREATE = BASE_URL + STATUSES + "update.json?$PARAM$"; + String STATUSES_DESTROY = BASE_URL + STATUSES + "destroy/$ID$.json"; + String STATUSES_SHOW = BASE_URL + STATUSES + "show.json?$PARAM$"; + String STATUSES_RETWEET = BASE_URL + STATUSES + "retweet/$ID$.json"; + String STATUSES_UNRETWEET = BASE_URL + STATUSES + "unretweet/$ID$.json"; + String STATUSES_LOOKUP = BASE_URL + STATUSES + "lookup.json?$PARAM$"; + String STATUSES_RETWEETS = BASE_URL + STATUSES + "retweets/$ID$.json"; + String STATUSES_RETWEETERS_IDS = BASE_URL + STATUSES + "retweeters/ids.json?"; + + String FAVORITES = "favorites/"; + String FAVORITES_CREATE = BASE_URL + FAVORITES + "create.json?$PARAM$"; + String FAVORITES_DESTROY = BASE_URL + FAVORITES + "destroy.json?$PARAM$"; + String FAVORITES_LIST = BASE_URL + FAVORITES + "list.json?$PARAM$"; + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/json/JSONArray.java b/src/main/java/com/github/langsdorf/blackbird/json/JSONArray.java new file mode 100644 index 0000000..68c5145 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/json/JSONArray.java @@ -0,0 +1,712 @@ +package com.github.langsdorf.blackbird.json; + +/* +Copyright (c) 2002 JSON.org + +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 shall be used for Good, not Evil. + +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. +*/ + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; + +/** + * A JSONArray is an ordered sequence of values. Its external text form is a + * string wrapped in square brackets with commas separating the values. The + * internal form is an object having {@code}get{/code} and {@code}opt{/code} + * methods for accessing the values by index, and {@code}put{/code} methods for + * adding or replacing values. The values can be any of these types: + * {@code}Boolean{/code}, {@code}JSONArray{/code}, {@code}JSONObject{/code}, + * {@code}Number{/code}, {@code}String{/code}, or the + * {@code}JSONObject.NULL object{/code}. + *

+ * The constructor can convert a JSON text into a Java object. The + * {@code}toString{/code} method converts to JSON text. + *

+ * A {@code}get{/code} method returns a value if one can be found, and throws an + * exception if one cannot be found. An {@code}opt{/code} method returns a + * default value instead of throwing an exception, and so is useful for + * obtaining optional values. + *

+ * The generic {@code}get(){/code} and {@code}opt(){/code} methods return an + * object which you can cast or query for type. There are also typed + * {@code}get{/code} and {@code}opt{/code} methods that do type checking and type + * coercion for you. + *

+ * The texts produced by the {@code}toString{/code} methods strictly conform to + * JSON syntax rules. The constructors are more forgiving in the texts they will + * accept: + *

    + *
  • An extra {@code},{/code} (comma) may appear just + * before the closing bracket.
  • + *
  • The {@code}null{/code} value will be inserted when there + * is {@code},{/code} (comma) elision.
  • + *
  • Strings may be quoted with {@code}'{/code} (single + * quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, + * and if they do not contain any of these characters: + * {@code}{ } [ ] / \ : , = ; #{/code} and if they do not look like numbers + * and if they are not the reserved words {@code}true{/code}, + * {@code}false{/code}, or {@code}null{/code}.
  • + *
  • Values can be separated by {@code};{/code} (semicolon) as + * well as by {@code},{/code} (comma).
  • + *
  • Numbers may have the + * {@code}0x-{/code} (hex) prefix.
  • + *
+ * + * @author JSON.org + * @version 2010-12-28 + */ +@SuppressWarnings(value = { "rawtypes", "unchecked", "deprecation" }) +public class JSONArray { + + + /** + * The arrayList where the JSONArray's properties are kept. + */ + private final ArrayList myArrayList; + + + /** + * Construct an empty JSONArray. + */ + public JSONArray() { + this.myArrayList = new ArrayList(); + } + + /** + * Construct a JSONArray from a JSONTokener. + * + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + public JSONArray(JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']') { + x.back(); + for (; ; ) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } + + + /** + * Construct a JSONArray from a source JSON text. + * + * @param source A string that begins with + * {@code}[{/code} (left bracket) + * and ends with {@code}]{/code} (right bracket). + * @throws JSONException If there is a syntax error. + */ + public JSONArray(String source) throws JSONException { + this(new JSONTokener(source)); + } + + + /** + * Construct a JSONArray from a Collection. + * + * @param collection A Collection. + */ + public JSONArray(Collection collection) { + this.myArrayList = new ArrayList(); + if (collection != null) { + for (Object aCollection : collection) { + this.myArrayList.add(JSONObject.wrap(aCollection)); + } + } + } + + + /** + * Construct a JSONArray from an array + * + * @param array array + * @throws JSONException If not an array. + */ + public JSONArray(Object array) throws JSONException { + this(); + if (array.getClass().isArray()) { + int length = Array.getLength(array); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException( + "JSONArray initial value should be a string or collection or array."); + } + } + + + /** + * Get the object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return An object value. + * @throws JSONException If there is no value for the index. + */ + public Object get(int index) throws JSONException { + Object object = opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + + /** + * Get the boolean value associated with an index. + * The string values "true" and "false" are converted to boolean. + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + * @throws JSONException If there is no value for the index or if the + * value is not convertible to boolean. + */ + public boolean getBoolean(int index) throws JSONException { + Object object = get(index); + if (object.equals(Boolean.FALSE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a boolean."); + } + + + /** + * Get the double value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + */ + public double getDouble(int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the int value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value is not a number. + */ + public int getInt(int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the JSONArray associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + * @throws JSONException If there is no value for the index. or if the + * value is not a JSONArray + */ + public JSONArray getJSONArray(int index) throws JSONException { + Object object = get(index); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw new JSONException("JSONArray[" + index + + "] is not a JSONArray."); + } + + + /** + * Get the JSONObject associated with an index. + * + * @param index subscript + * @return A JSONObject value. + * @throws JSONException If there is no value for the index or if the + * value is not a JSONObject + */ + public JSONObject getJSONObject(int index) throws JSONException { + Object object = get(index); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONArray[" + index + + "] is not a JSONObject."); + } + + + /** + * Get the long value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + */ + public long getLong(int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the string associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return A string value. + * @throws JSONException If there is no value for the index. + */ + public String getString(int index) throws JSONException { + Object object = get(index); + return object == JSONObject.NULL ? null : object.toString(); + } + + + /** + * Determine if the value is null. + * + * @param index The index must be between 0 and length() - 1. + * @return true if the value at the index is null, or if there is no value. + */ + public boolean isNull(int index) { + return JSONObject.NULL.equals(opt(index)); + } + + + /** + * Make a string from the contents of this JSONArray. The + * {@code}separator{/code} string is inserted between each element. + * Warning: This method assumes that the data structure is acyclical. + * + * @param separator A string that will be inserted between the elements. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join(String separator) throws JSONException { + int len = length(); + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length() { + return this.myArrayList.size(); + } + + + /** + * Get the optional object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return An object value, or null if there is no + * object at that index. + */ + public Object opt(int index) { + return (index < 0 || index >= length()) ? + null : this.myArrayList.get(index); + } + + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public JSONArray put(boolean value) { + put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * + * @param value A Collection value. + * @return this. + */ + public JSONArray put(Collection value) { + put(new JSONArray(value)); + return this; + } + + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public JSONArray put(int value) { + put(new Integer(value)); + return this; + } + + + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public JSONArray put(long value) { + put(new Long(value)); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject which is produced from a Map. + * + * @param value A Map value. + * @return this. + */ + public JSONArray put(Map value) { + put(new JSONObject(value)); + return this; + } + + + /** + * Append an object value. This increases the array's length by one. + * + * @param value An object value. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + */ + public JSONArray put(Object value) { + this.myArrayList.add(value); + return this; + } + + + /** + * Put or replace a boolean value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * + * @param index The subscript. + * @param value A boolean value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, boolean value) throws JSONException { + put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * + * @param index The subscript. + * @param value A Collection value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public JSONArray put(int index, Collection value) throws JSONException { + put(index, new JSONArray(value)); + return this; + } + + + /** + * Put or replace a double value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * + * @param index The subscript. + * @param value A double value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public JSONArray put(int index, double value) throws JSONException { + put(index, new Double(value)); + return this; + } + + + /** + * Put or replace an int value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, int value) throws JSONException { + put(index, new Integer(value)); + return this; + } + + + /** + * Put or replace a long value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * + * @param index The subscript. + * @param value A long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, long value) throws JSONException { + put(index, new Long(value)); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject which is produced from a Map. + * + * @param index The subscript. + * @param value The Map value. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public JSONArray put(int index, Map value) throws JSONException { + put(index, new JSONObject(value)); + return this; + } + + + /** + * Put or replace an object value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * + * @param index The subscript. + * @param value The value to put into the array. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public JSONArray put(int index, Object value) throws JSONException { + JSONObject.testValidity(value); + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < length()) { + this.myArrayList.set(index, value); + } else { + while (index != length()) { + put(JSONObject.NULL); + } + put(value); + } + return this; + } + + /** + * Make a JSON text of this JSONArray. For compactness, no + * unnecessary whitespace is added. If it is not possible to produce a + * syntactically correct JSON text then null will be returned instead. This + * could occur if the array contains an invalid number. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable + * representation of the array. + */ + public String toString() { + try { + return '[' + join(",") + ']'; + } catch (Exception e) { + return null; + } + } + + + /** + * Make a prettyprinted JSON text of this JSONArray. + * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with {@code}[{/code} (left bracket) and ending + * with {@code}]{/code} (right bracket). + * @throws JSONException when failed to stringify + */ + public String toString(int indentFactor) throws JSONException { + return toString(indentFactor, 0); + } + + + /** + * Make a prettyprinted JSON text of this JSONArray. + * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indention of the top level. + * @return a printable, displayable, transmittable + * representation of the array. + * @throws JSONException when failed to stringify + */ + String toString(int indentFactor, int indent) throws JSONException { + int len = length(); + if (len == 0) { + return "[]"; + } + int i; + StringBuilder sb = new StringBuilder("["); + if (len == 1) { + sb.append(JSONObject.valueToString(this.myArrayList.get(0), + indentFactor, indent)); + } else { + int newindent = indent + indentFactor; + sb.append('\n'); + for (i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(",\n"); + } + for (int j = 0; j < newindent; j += 1) { + sb.append(' '); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i), + indentFactor, newindent)); + } + sb.append('\n'); + for (i = 0; i < indent; i += 1) { + sb.append(' '); + } + } + sb.append(']'); + return sb.toString(); + } + + + /** + * Write the contents of the JSONArray as JSON text to a writer. + * For compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param writer writer + * @return The writer. + * @throws JSONException when failed to write the content + */ + public Writer write(Writer writer) throws JSONException { + try { + boolean b = false; + int len = length(); + + writer.write('['); + + for (int i = 0; i < len; i += 1) { + if (b) { + writer.write(','); + } + Object v = this.myArrayList.get(i); + if (v instanceof JSONObject) { + ((JSONObject) v).write(writer); + } else if (v instanceof JSONArray) { + ((JSONArray) v).write(writer); + } else { + writer.write(JSONObject.valueToString(v)); + } + b = true; + } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/json/JSONException.java b/src/main/java/com/github/langsdorf/blackbird/json/JSONException.java new file mode 100644 index 0000000..766561c --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/json/JSONException.java @@ -0,0 +1,31 @@ +package com.github.langsdorf.blackbird.json; + +/** + * The JSONException is thrown by the JSON.org classes when things are amiss. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class JSONException extends Exception { + private static final long serialVersionUID = -4144585377907783745L; + private Throwable cause; + + /** + * Constructs a JSONException with an explanatory message. + * + * @param message Detail about the reason for the exception. + */ + public JSONException(String message) { + super(message); + } + + public JSONException(Throwable cause) { + super(cause.getMessage()); + this.cause = cause; + } + + @Override + public Throwable getCause() { + return this.cause; + } +} diff --git a/src/main/java/com/github/langsdorf/blackbird/json/JSONObject.java b/src/main/java/com/github/langsdorf/blackbird/json/JSONObject.java new file mode 100644 index 0000000..a71c5e2 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/json/JSONObject.java @@ -0,0 +1,1245 @@ +package com.github.langsdorf.blackbird.json; + +/* +Copyright (c) 2002 JSON.org + +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 shall be used for Good, not Evil. + +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. +*/ + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * A JSONObject is an unordered collection of name/value pairs. Its + * external form is a string wrapped in curly braces with colons between the + * names and values, and commas between the values and names. The internal form + * is an object having {@code}get{/code} and {@code}opt{/code} methods for + * accessing the values by name, and {@code}put{/code} methods for adding or + * replacing values by name. The values can be any of these types: + * {@code}Boolean{/code}, {@code}JSONArray{/code}, {@code}JSONObject{/code}, + * {@code}Number{/code}, {@code}String{/code}, or the {@code}JSONObject.NULL{/code} + * object. A JSONObject constructor can be used to convert an external form + * JSON text into an internal form whose values can be retrieved with the + * {@code}get{/code} and {@code}opt{/code} methods, or to convert values into a + * JSON text using the {@code}put{/code} and {@code}toString{/code} methods. + * A {@code}get{/code} method returns a value if one can be found, and throws an + * exception if one cannot be found. An {@code}opt{/code} method returns a + * default value instead of throwing an exception, and so is useful for + * obtaining optional values. + *

+ * The generic {@code}get(){/code} and {@code}opt(){/code} methods return an + * object, which you can cast or query for type. There are also typed + * {@code}get{/code} and {@code}opt{/code} methods that do type checking and type + * coercion for you. The opt methods differ from the get methods in that they + * do not throw. Instead, they return a specified value, such as null. + *

+ * The {@code}put{/code} methods add or replace values in an object. For example, + *

myString = new JSONObject().put("JSON", "Hello, World!").toString();
+ * produces the string {@code}{"JSON": "Hello, World"}{/code}. + *

+ * The texts produced by the {@code}toString{/code} methods strictly conform to + * the JSON syntax rules. + * The constructors are more forgiving in the texts they will accept: + *

    + *
  • An extra {@code},{/code} (comma) may appear just + * before the closing brace.
  • + *
  • Strings may be quoted with {@code}'{/code} (single + * quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, + * and if they do not contain any of these characters: + * {@code}{ } [ ] / \ : , = ; #{/code} and if they do not look like numbers + * and if they are not the reserved words {@code}true{/code}, + * {@code}false{/code}, or {@code}null{/code}.
  • + *
  • Keys can be followed by {@code}={/code} or {@code}=>{/code} as well as + * by {@code}:{/code}.
  • + *
  • Values can be followed by {@code};{/code} (semicolon) as + * well as by {@code},{/code} (comma).
  • + *
  • Numbers may have the {@code}0x-{/code} (hex) prefix.
  • + *
+ * + * @author JSON.org + * @version 2010-12-28 + */ +@SuppressWarnings(value = { "rawtypes", "unchecked", "deprecation" }) +public class JSONObject { + + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined. + */ + private static final class Null { + + /** + * There is only intended to be a single instance of the NULL object, + * so the clone method returns itself. + * + * @return NULL. + */ + @Override + protected final Object clone() { + return this; + } + + /** + * A Null object is equal to the null value and to itself. + * + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object + * or null. + */ + public boolean equals(Object object) { + return object == null || object == this; + } + + /** + * Get the "null" string value. + * + * @return The string "null". + */ + public String toString() { + return "null"; + } + } + + + /** + * The map where the JSONObject's properties are kept. + */ + private final Map map; + + + /** + * It is sometimes more convenient and less ambiguous to have a + * {@code}NULL{/code} object than to use Java's {@code}null{/code} value. + * {@code}JSONObject.NULL.equals(null){/code} returns {@code}true{/code}. + * {@code}JSONObject.NULL.toString(){/code} returns {@code}"null"{/code}. + */ + public static final Object NULL = new Null(); + + + /** + * Construct an empty JSONObject. + */ + public JSONObject() { + this.map = new HashMap(); + } + + + /** + * Construct a JSONObject from a subset of another JSONObject. + * An array of strings is used to identify the keys that should be copied. + * Missing keys are ignored. + * + * @param jo A JSONObject. + * @param names An array of strings. + */ + public JSONObject(JSONObject jo, String[] names) { + this(); + for (String name : names) { + try { + putOnce(name, jo.opt(name)); + } catch (Exception ignore) { + } + } + } + + + /** + * Construct a JSONObject from a JSONTokener. + * + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string + * or a duplicated key. + */ + public JSONObject(JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{' found:" + x.nextClean()); + } + for (; ; ) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + +// The key is followed by ':'. We will also tolerate '=' or '=>'. + + c = x.nextClean(); + if (c == '=') { + if (x.next() != '>') { + x.back(); + } + } else if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + putOnce(key, x.nextValue()); + +// Pairs are separated by ','. We will also tolerate ';'. + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of + * the JSONObject. + */ + public JSONObject(Map map) { + this.map = new HashMap(); + if (map != null) { + for (Object o : map.entrySet()) { + Map.Entry e = (Map.Entry) o; + Object value = e.getValue(); + if (value != null) { + this.map.put(e.getKey(), wrap(value)); + } + } + } + } + + + /** + * Construct a JSONObject from an Object using bean getters. + * It reflects on all of the public methods of the object. + * For each of the methods with no parameters and a name starting + * with {@code}"get"{/code} or {@code}"is"{/code} followed by an uppercase letter, + * the method is invoked, and a key and the value returned from the getter method + * are put into the new JSONObject. + *

+ * The key is formed by removing the {@code}"get"{/code} or {@code}"is"{/code} prefix. + * If the second remaining character is not upper case, then the first + * character is converted to lower case. + *

+ * For example, if an object has a method named {@code}"getName"{/code}, and + * if the result of calling {@code}object.getName(){/code} is {@code}"Larry Fine"{/code}, + * then the JSONObject will contain {@code}"name": "Larry Fine"{/code}. + * + * @param bean An object that has getter methods that should be used + * to make a JSONObject. + */ + public JSONObject(Object bean) { + this(); + populateMap(bean); + } + + + /** + * Construct a JSONObject from an Object, using reflection to find the + * public members. The resulting JSONObject's keys will be the strings + * from the names array, and the values will be the field values associated + * with those keys in the object. If a key is not found or not visible, + * then it will not be copied into the new JSONObject. + * + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. + */ + public JSONObject(Object object, String names[]) { + this(); + Class c = object.getClass(); + for (String name : names) { + try { + putOpt(name, c.getField(name).get(object)); + } catch (Exception ignore) { + } + } + } + + + /** + * Construct a JSONObject from a source JSON text string. + * This is the most commonly used JSONObject constructor. + * + * @param source A string beginning + * with {@code}{{/code} (left brace) and ending + * with {@code}}{/code} (right brace). + * @throws JSONException If there is a syntax error in the source + * string or a duplicated key. + */ + public JSONObject(String source) throws JSONException { + this(new JSONTokener(source)); + } + + + /** + * Construct a JSONObject from a ResourceBundle. + * + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. + */ + public JSONObject(String baseName, Locale locale) throws JSONException { + this(); + ResourceBundle r = ResourceBundle.getBundle(baseName, locale, + Thread.currentThread().getContextClassLoader()); + +// Iterate through the keys in the bundle. + + Enumeration keys = r.getKeys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (key instanceof String) { + +// Go through the path, ensuring that there is a nested JSONObject for each +// segment except the last. Add the value using the last segment's name into +// the deepest nested JSONObject. + + String[] path = ((String) key).split("\\."); + int last = path.length - 1; + JSONObject target = this; + for (int i = 0; i < last; i += 1) { + String segment = path[i]; + Object object = target.opt(segment); + JSONObject nextTarget = object instanceof JSONObject ? (JSONObject) object : null; + if (nextTarget == null) { + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], r.getString((String) key)); + } + } + } + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already + * associated with a JSONArray, then the value parameter is appended to it. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the key is null or if the current value + * associated with the key is not a JSONArray. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + Object object = opt(key); + if (object == null) { + put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + put(key, ((JSONArray) object).put(value)); + } else { + throw new JSONException("JSONObject[" + key + + "] is not a JSONArray."); + } + return this; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + + "] not found."); + } + return object; + } + + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or "false". + */ + public boolean getBoolean(String key) throws JSONException { + Object object = get(key); + if (object.equals(Boolean.FALSE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a Boolean."); + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to an integer. + */ + public int getInt(String key) throws JSONException { + Object object = get(key); + try { + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not an int."); + } + } + + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object object = get(key); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a JSONArray."); + } + + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object object = get(key); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a JSONObject."); + } + + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to a long. + */ + public long getLong(String key) throws JSONException { + Object object = get(key); + try { + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not a long."); + } + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if the key is not found. + */ + public String getString(String key) throws JSONException { + Object object = get(key); + return object == NULL ? null : object.toString(); + } + + + /** + * Determine if the JSONObject contains a specific key. + * + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key) { + return this.map.containsKey(key); + } + + /** + * Determine if the value associated with the key is null or if there is + * no value. + * + * @param key A key string. + * @return true if there is no value associated with the key or if + * the value is the JSONObject.NULL object. + */ + public boolean isNull(String key) { + return JSONObject.NULL.equals(opt(key)); + } + + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys() { + return this.map.keySet().iterator(); + } + + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + + /** + * Produce a JSONArray containing the names of the elements of this + * JSONObject. + * + * @return A JSONArray containing the key strings, or null if the JSONObject + * is empty. + */ + public JSONArray names() { + JSONArray ja = new JSONArray(); + Iterator keys = keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * Produce a string from a Number. + * + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + public static String numberToString(Number number) + throws JSONException { + if (number == null) { + throw new JSONException("Null pointer"); + } + testValidity(number); + +// Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + + /** + * Get an optional value associated with a key. + * + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key) { + return key == null ? null : this.map.get(key); + } + + + private void populateMap(Object bean) { + Class klass = bean.getClass(); + +// If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = (includeSuperClass) ? + klass.getMethods() : klass.getDeclaredMethods(); + for (Method method1 : methods) { + try { + if (Modifier.isPublic(method1.getModifiers())) { + String name = method1.getName(); + String key = ""; + if (name.startsWith("get")) { + if (name.equals("getClass") || + name.equals("getDeclaringClass")) { + key = ""; + } else { + key = name.substring(3); + } + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && + Character.isUpperCase(key.charAt(0)) && + method1.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + + key.substring(1); + } + + Object result = method1.invoke(bean, (Object[]) null); + if (result != null) { + map.put(key, wrap(result)); + } + } + } + } catch (Exception ignore) { + } + } + } + + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException { + put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + public JSONObject put(String key, Collection value) throws JSONException { + put(key, new JSONArray(value)); + return this; + } + + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the key is null or if the number is invalid. + */ + public JSONObject put(String key, double value) throws JSONException { + put(key, new Double(value)); + return this; + } + + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException { + put(key, new Integer(value)); + return this; + } + + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException { + put(key, new Long(value)); + return this; + } + + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONObject which is produced from a Map. + * + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException when failed to put value + */ + public JSONObject put(String key, Map value) throws JSONException { + put(key, new JSONObject(value)); + return this; + } + + + /** + * Put a key/value pair in the JSONObject. If the value is null, + * then the key will be removed from the JSONObject if it is present. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number + * or if the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + remove(key); + } + return this; + } + + + /** + * Put a key/value pair in the JSONObject, but only if the key and the + * value are both non-null, and only if there is not already a member + * with that name. + * + * @param key key to be put + * @param value value to be put + * @return his. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException { + if (key != null && value != null) { + if (opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + put(key, value); + } + return this; + } + + + /** + * Put a key/value pair in the JSONObject, but only if the + * key and the value are both non-null. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException { + if (key != null && value != null) { + put(key, value); + } + return this; + } + + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within </, producing <\/, + * allowing JSON text to be delivered in HTML. In JSON text, a string + * cannot contain a control character or an unescaped quote or backslash. + * + * @param string A String + * @return A String correctly formatted for insertion in a JSON text. + */ + public static String quote(String string) { + if (string == null || string.length() == 0) { + return "\"\""; + } + + char b; + char c = 0; + String hhhh; + int i; + int len = string.length(); + StringBuilder sb = new StringBuilder(len + 4); + + sb.append('"'); + for (i = 0; i < len; i += 1) { + b = c; + c = string.charAt(i); + switch (c) { + case '\\': + case '"': + sb.append('\\'); + sb.append(c); + break; + case '/': + if (b == '<') { + sb.append('\\'); + } + sb.append(c); + break; + case '\b': + sb.append("\\b"); + break; + case '\t': + sb.append("\\t"); + break; + case '\n': + sb.append("\\n"); + break; + case '\f': + sb.append("\\f"); + break; + case '\r': + sb.append("\\r"); + break; + default: + if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || + (c >= '\u2000' && c < '\u2100')) { + hhhh = "000" + Integer.toHexString(c); + sb.append("\\u").append(hhhh.substring(hhhh.length() - 4)); + } else { + sb.append(c); + } + } + } + sb.append('"'); + return sb.toString(); + } + + /** + * Remove a name and its value, if present. + * + * @param key The name to be removed. + * @return The value that was associated with the name, + * or null if there was no value. + */ + public Object remove(String key) { + return this.map.remove(key); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * The keys will be sorted alphabetically. + * + * @return An iterator of the keys. + */ + public Iterator sortedKeys() { + return new TreeSet(this.map.keySet()).iterator(); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. + * We support the non-standard 0x- convention. + * If a number cannot be produced, then the value will just + * be a string. Note that the 0x-, plus, and implied string + * conventions are non-standard. A JSON parser may accept + * non-JSON forms as long as it accepts all correct JSON forms. + */ + + char b = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + if (b == '0' && string.length() > 2 && + (string.charAt(1) == 'x' || string.charAt(1) == 'X')) { + try { + return Integer.parseInt(string.substring(2), 16); + } catch (Exception ignore) { + } + } + try { + if (string.indexOf('.') > -1 || + string.indexOf('e') > -1 || string.indexOf('E') > -1) { + return Double.valueOf(string); + } else { + Long myLong = new Long(string); + if (myLong == myLong.intValue()) { + return myLong.intValue(); + } else { + return myLong; + } + } + } catch (Exception ignore) { + } + } + return string; + } + + + /** + * Throw an exception if the object is a NaN or infinite number. + * + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + public static void testValidity(Object o) throws JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { + throw new JSONException( + "JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float) { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { + throw new JSONException( + "JSON does not allow non-finite numbers."); + } + } + } + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace + * is added. If this would not result in a syntactically correct JSON text, + * then null will be returned instead. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with {@code}{{/code} (left brace) and ending + * with {@code}}{/code} (right brace). + */ + public String toString() { + try { + Iterator keys = keys(); + StringBuilder sb = new StringBuilder("{"); + + while (keys.hasNext()) { + if (sb.length() > 1) { + sb.append(','); + } + Object o = keys.next(); + sb.append(quote(o.toString())); + sb.append(':'); + sb.append(valueToString(this.map.get(o))); + } + sb.append('}'); + return sb.toString(); + } catch (Exception e) { + return null; + } + } + + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with {@code}{{/code} (left brace) and ending + * with {@code}}{/code} (right brace). + * @throws JSONException If the object contains an invalid number. + */ + public String toString(int indentFactor) throws JSONException { + return toString(indentFactor, 0); + } + + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with {@code}{{/code} (left brace) and ending + * with {@code}}{/code} (right brace). + * @throws JSONException If the object contains an invalid number. + */ + String toString(int indentFactor, int indent) throws JSONException { + int i; + int length = this.length(); + if (length == 0) { + return "{}"; + } + Iterator keys = sortedKeys(); + int newindent = indent + indentFactor; + Object object; + StringBuilder sb = new StringBuilder("{"); + if (length == 1) { + object = keys.next(); + sb.append(quote(object.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(object), indentFactor, + indent)); + } else { + while (keys.hasNext()) { + object = keys.next(); + if (sb.length() > 1) { + sb.append(",\n"); + } else { + sb.append('\n'); + } + for (i = 0; i < newindent; i += 1) { + sb.append(' '); + } + sb.append(quote(object.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(object), indentFactor, + newindent)); + } + if (sb.length() > 1) { + sb.append('\n'); + for (i = 0; i < indent; i += 1) { + sb.append(' '); + } + } + } + sb.append('}'); + return sb.toString(); + } + + + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce + * the JSON text. The method is required to produce a strictly + * conforming text. If the object does not contain a toJSONString + * method (which is the most common case), then a text will be + * produced by other means. If the value is an array or Collection, + * then a JSONArray will be made from it and its toJSONString method + * will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the + * value's toString method will be called, and the result will be quoted. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with {@code}{{/code} (left brace) and ending + * with {@code}}{/code} (right brace). + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean || value instanceof JSONObject || + value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + return new JSONObject((Map) value).toString(); + } + if (value instanceof Collection) { + return new JSONArray((Collection) value).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + + /** + * Make a prettyprinted JSON text of an object value. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with {@code}{{/code} (left brace) and ending + * with {@code}}{/code} (right brace). + * @throws JSONException If the object contains an invalid number. + */ + static String valueToString(Object value, int indentFactor, int indent) + throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean) { + return value.toString(); + } + if (value instanceof JSONObject) { + return ((JSONObject) value).toString(indentFactor, indent); + } + if (value instanceof JSONArray) { + return ((JSONArray) value).toString(indentFactor, indent); + } + if (value instanceof Map) { + return new JSONObject((Map) value).toString(indentFactor, indent); + } + if (value instanceof Collection) { + return new JSONArray((Collection) value).toString(indentFactor, indent); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(indentFactor, indent); + } + return quote(value.toString()); + } + + + /** + * Wrap an object, if necessary. If the object is null, return the NULL + * object. If it is an array or collection, wrap it in a JSONArray. If + * it is a map, wrap it in a JSONObject. If it is a standard property + * (Double, String, et al) then it is already wrapped. Otherwise, if it + * comes from one of the java packages, turn it into a string. And if + * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, + * then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + public static Object wrap(Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || + NULL.equals(object) || + object instanceof Byte || object instanceof Character || + object instanceof Short || object instanceof Integer || + object instanceof Long || object instanceof Boolean || + object instanceof Float || object instanceof Double || + object instanceof String) { + return object; + } + + if (object instanceof Collection) { + return new JSONArray((Collection) object); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + return new JSONObject((Map) object); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = (objectPackage != null ? objectPackage.getName() : ""); + if (objectPackageName.startsWith("java.") || + objectPackageName.startsWith("javax.") || + object.getClass().getClassLoader() == null) { + return object.toString(); + } + return new JSONObject(object); + } catch (Exception exception) { + return null; + } + } + + + public Writer write(Writer writer) throws JSONException { + try { + boolean commanate = false; + Iterator keys = keys(); + writer.write('{'); + + while (keys.hasNext()) { + if (commanate) { + writer.write(','); + } + Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + Object value = this.map.get(key); + if (value instanceof JSONObject) { + ((JSONObject) value).write(writer); + } else if (value instanceof JSONArray) { + ((JSONArray) value).write(writer); + } else { + writer.write(valueToString(value)); + } + commanate = true; + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/json/JSONTokener.java b/src/main/java/com/github/langsdorf/blackbird/json/JSONTokener.java new file mode 100644 index 0000000..58f134c --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/json/JSONTokener.java @@ -0,0 +1,352 @@ +package com.github.langsdorf.blackbird.json; + +import java.io.*; + +/* +Copyright (c) 2002 JSON.org + +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 shall be used for Good, not Evil. + +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. +*/ + +/** + * A JSONTokener takes a source string and extracts characters and tokens from + * it. It is used by the JSONObject and JSONArray constructors to parse + * JSON source strings. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class JSONTokener { + + private int character; + private boolean eof; + private int index; + private int line; + private char previous; + private final Reader reader; + private boolean usePrevious; + + + /** + * Construct a JSONTokener from a Reader. + * + * @param reader A reader. + */ + public JSONTokener(Reader reader) { + this.reader = reader.markSupported() ? + reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + + /** + * Construct a JSONTokener from an InputStream. + * @param inputStream input stream + * @throws JSONException when failed to construct + */ + public JSONTokener(InputStream inputStream) throws JSONException { + this(new InputStreamReader(inputStream)); + } + + + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener(String s) { + this(new StringReader(s)); + } + + + /** + * Back up one character. This provides a sort of lookahead capability, + * so that you can test for a digit or letter before attempting to parse + * the next number or identifier. + * @throws JSONException when tried to back two steps + */ + public void back() throws JSONException { + if (usePrevious || index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + + public boolean end() { + return eof && !usePrevious; + } + + + /** + * Determine if the source string still contains characters that next() + * can consume. + * + * @return true if not yet at the end of the source. + * @throws JSONException when failed to determine + */ + public boolean more() throws JSONException { + next(); + if (end()) { + return false; + } + back(); + return true; + } + + + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + * @throws JSONException when failed to read the next character from the reader + */ + public char next() throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (IOException exception) { + throw new JSONException(exception); + } + + if (c <= 0) { // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r') { + this.line += 1; + this.character = c == '\n' ? 0 : 1; + } else if (c == '\n') { + this.line += 1; + this.character = 0; + } else { + this.character += 1; + } + this.previous = (char) c; + return this.previous; + } + + + /** + * Consume the next character, and check that it matches a specified + * character. + * + * @param c The character to match. + * @return The character. + * @throws JSONException if the character does not match. + */ + public char next(char c) throws JSONException { + char n = next(); + if (n != c) { + throw syntaxError("Expected '" + c + "' and instead saw '" + + n + "'"); + } + return n; + } + + + /** + * Get the next n characters. + * + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not + * n characters remaining in the source string. + */ + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } + + char[] chars = new char[n]; + int pos = 0; + + while (pos < n) { + chars[pos] = next(); + if (end()) { + throw syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + + /** + * Get the next char in the string, skipping whitespace. + * + * @return A character, or 0 if there are no more characters. + * @throws JSONException when failed to read the content from the reader + */ + public char nextClean() throws JSONException { + for (; ; ) { + char c = next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + + + /** + * Return the characters up to the next close quote character. + * Backslash processing is done. The formal JSON format does not + * allow strings in single quotes, but an implementation is allowed to + * accept them. + * + * @param quote The quoting character, either + * {@code "} (double quote) or + * {@code '} (single quote). + * @return A String. + * @throws JSONException Unterminated string. + */ + public String nextString(char quote) throws JSONException { + char c; + StringBuilder sb = new StringBuilder(); + for (; ; ) { + c = next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw syntaxError("Unterminated string"); + case '\\': + c = next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char) Integer.parseInt(next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + + /** + * Get the next value. The value can be a Boolean, Double, Integer, + * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. + * + * @return An object. + * @throws JSONException If syntax error. + */ + public Object nextValue() throws JSONException { + char c = nextClean(); + String string; + + switch (c) { + case '"': + case '\'': + return nextString(c); + case '{': + back(); + return new JSONObject(this); + case '[': + back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or + * null, or it can be a number. An implementation (such as this one) + * is allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a + * formatting character. + */ + + StringBuilder sb = new StringBuilder(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = next(); + } + back(); + + string = sb.toString().trim(); + if (string.equals("")) { + throw syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message) { + return new JSONException(message + toString()); + } + + + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + public String toString() { + return " at " + index + " [character " + this.character + " line " + + this.line + "]"; + } +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/tweet/Tweet.java b/src/main/java/com/github/langsdorf/blackbird/tweet/Tweet.java new file mode 100644 index 0000000..bd8a5cd --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/tweet/Tweet.java @@ -0,0 +1,23 @@ +package com.github.langsdorf.blackbird.tweet; + +import com.github.langsdorf.blackbird.user.User; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class Tweet { + + private long tweetId; + private String text; + private String createdAt; + private int retweetCount; + private int favoriteCount; + private User user; + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/tweet/TweetI.java b/src/main/java/com/github/langsdorf/blackbird/tweet/TweetI.java new file mode 100644 index 0000000..b5d0fe3 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/tweet/TweetI.java @@ -0,0 +1,190 @@ +package com.github.langsdorf.blackbird.tweet; + +import java.util.List; + +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.user.list.BirdList; + +public interface TweetI { + + /** + * Updates the authenticating user’s current status, also known as Tweeting.
+ *
+ * Publica um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update + *
+ *
+ * https://api.twitter.com/1.1/statuses/update.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet createTweet(String status) throws TwitterException; + + /** + * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.
+ *
+ * Deleta um tweet. O autor do tweet deve ser o usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id + *
+ *
+ * https://api.twitter.com/1.1/statuses/destroy/:id.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet deleteTweet(long tweetId) throws TwitterException; + + /** + * Returns a single Tweet, specified by the id parameter.
+ *
+ * Retorna um tweet específico.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id + *
+ *
+ * https://api.twitter.com/1.1/statuses/show.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet showTweet(long tweetId) throws TwitterException; + + /** + * Returns fully-hydrated Tweet objects for up to 100 Tweets per request, as specified by comma-separated values passed to the id parameter.
+ *
+ * Retorna todos os tweets específicados (Máximo 100 tweets por request).
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-lookup + *
+ *
+ * https://api.twitter.com/1.1/statuses/lookup.json + * + * @return List + * @throws TwitterException + */ + List tweetLookup(long... tweetsId) throws TwitterException; + + /** + * Retweets a tweet. Returns the original Tweet with Retweet details embedded.
+ *
+ * Retweeta um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id + *
+ *
+ * https://api.twitter.com/1.1/statuses/retweet/:id.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet retweet(long tweetId) throws TwitterException; + + /** + * Untweets a retweeted status. Returns the original Tweet with Retweet details embedded.
+ *
+ * Remove o retweet de um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-unretweet-id + *
+ *
+ * https://api.twitter.com/1.1/statuses/unretweet/:id.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet unretweet(long tweetId) throws TwitterException; + + /** + * Returns a collection of the 100 most recent retweets of the Tweet specified by the id parameter.
+ *
+ * Retorna os 100 retweets mais recentes de um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweets-id + *
+ *
+ * https://api.twitter.com/1.1/statuses/retweets/:id.json + * + * @return List + * @throws TwitterException + */ + List getRetweets(long tweetId, int count) throws TwitterException; + + /** + * Returns a collection of up to 100 user IDs belonging to users who have retweeted the Tweet specified by the id parameter.
+ *
+ * Retorna 100 ids de usuários que tenham dado retweet em um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweeters-ids + *
+ *
+ * https://api.twitter.com/1.1/statuses/retweeters/ids.json + * + * @return BirdList + * @throws TwitterException + */ + BirdList getRetweetersId(long tweetId, int count, String cursor) throws TwitterException; + + /** + * Favorites (likes) the Tweet specified in the ID parameter as the authenticating user. Returns the favorite Tweet when successful.
+ *
+ * Favorita (like) um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-favorites-create + *
+ *
+ * https://api.twitter.com/1.1/favorites/create.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet like(long tweetId) throws TwitterException; + + /** + * Unfavorites (un-likes) the Tweet specified in the ID parameter as the authenticating user. Returns the un-liked Tweet when successful.
+ *
+ * Desfavorita (un-like) um tweet.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-favorites-destroy + *
+ *
+ * https://api.twitter.com/1.1/favorites/destroy.json + * + * @return Tweet + * @throws TwitterException + */ + Tweet unlike(long tweetId) throws TwitterException; + + /** + * Returns the 20 most recent Tweets liked by the authenticating or specified user.
+ *
+ * Retorna os 20 mais recentes tweets que um usuário curtiu.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list + *
+ *
+ * https://api.twitter.com/1.1/favorites/list.json + * + * @return List + * @throws TwitterException + */ + List getLikedTweets(String screenName, int count) throws TwitterException; + + /** + * Returns the 20 most recent Tweets liked by the authenticating or specified user.
+ *
+ * Retorna os 20 mais recentes tweets que um usuário curtiu.
+ *
+ * https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list + *
+ *
+ * https://api.twitter.com/1.1/favorites/list.json + * + * @return List + * @throws TwitterException + */ + List getLikedTweets(long userId, int count) throws TwitterException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/user/User.java b/src/main/java/com/github/langsdorf/blackbird/user/User.java new file mode 100644 index 0000000..29b45b2 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/User.java @@ -0,0 +1,51 @@ +package com.github.langsdorf.blackbird.user; + +import java.util.List; +import java.util.Map; + +import com.github.langsdorf.blackbird.user.misc.Relationships; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class User { + + private long userId; + private String name; + private String screenName; + private String location; + private String description; + private String profileWebsite; + private boolean protectedProfile; + private int followers; + private int following; + private String createdAt; + private int favouritesCount; + private String timeZone; + private boolean verified; + private int tweetsCount; + private String language; + private String profileColor; + private String profileBannerUrl; + private String profileImageUrl; + private List followersList; + private List followingList; + private List blockList; + private List muteList; + private Map> relationships; + + public User(String screenName) { + setScreenName(screenName); + } + + public User(long userId) { + setUserId(userId); + } + +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/user/UserI.java b/src/main/java/com/github/langsdorf/blackbird/user/UserI.java new file mode 100644 index 0000000..29d4ec2 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/UserI.java @@ -0,0 +1,699 @@ +package com.github.langsdorf.blackbird.user; + +import java.util.List; + +import com.github.langsdorf.blackbird.exception.TwitterException; +import com.github.langsdorf.blackbird.user.list.BirdList; +import com.github.langsdorf.blackbird.user.misc.AccountSettings; +import com.github.langsdorf.blackbird.user.misc.Banner; + +public interface UserI { + + /** + * Returns settings (including current trend, geo and sleep time information) + * for the authenticating user.
+ *
+ * Retorna as configurações (incluindo trend, geo e sleep time) do usuário + * autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-settings + *
+ *
+ * https://api.twitter.com/1.1/account/settings.json + * + * @return AccountSettings + * @throws TwitterException + */ + AccountSettings getAccountSettings() throws TwitterException; + + /** + * Returns a map of the available size variations of the specified user’s + * profile banner. If the user has not uploaded a profile banner, a HTTP 404 + * will be served instead.
+ *
+ * Retorna um mapa das variações de tamanho disponíveis do banner de perfil do + * usuário especificado. Se o usuário não tiver um banner de perfil, um código + * HTTP 404 será exibido.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials + *
+ *
+ * https://api.twitter.com/1.1/account/verify_credentials.json + * + * @return User + * @throws TwitterException + */ + List getProfileBanner(String screenName) throws TwitterException; + + /** + * Returns a map of the available size variations of the specified user’s + * profile banner. If the user has not uploaded a profile banner, a HTTP 404 + * will be served instead.
+ *
+ * Retorna um mapa das variações de tamanho disponíveis do banner de perfil do + * usuário especificado. Se o usuário não tiver um banner de perfil, um código + * HTTP 404 será exibido.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials + *
+ *
+ * https://api.twitter.com/1.1/account/verify_credentials.json + * + * @return User + * @throws TwitterException + */ + List getProfileBanner(long userId) throws TwitterException; + + /** + * Removes the uploaded profile banner for the authenticating user. Returns HTTP + * 200 upon success.
+ *
+ * Remove o banner de perfil do usuário autenticado. Retorna um código HTTP 200 + * se tiver sucesso.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials + *
+ *
+ * https://api.twitter.com/1.1/account/verify_credentials.json + * + * @throws TwitterException + */ + void removeProfileBanner() throws TwitterException; + + /** + * Updates the authenticating user’s settings. Only the parameters specified + * will be updated.
+ *
+ * Atualiza as configurações do usuário autenticado. Somente parâmetros + * especificados serão atualizados.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings + *
+ *
+ * https://api.twitter.com/1.1/account/settings.json + * + * @return AccountSettings + * @param time_zone http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html + * @param lang https://developer.twitter.com/en/docs/developer-utilities/supported-languages/api-reference/get-help-languages + * @throws TwitterException + */ + AccountSettings updateAccountSettings(boolean sleep_time_enabled, int start_sleep_time, int end_sleep_time, + String time_zone, int trend_location_woeid, String lang) throws TwitterException; + + /** + * Updates the authenticating user’s profile. Only the parameters specified will + * be updated.
+ *
+ * Atualiza o perfil do usuário autenticado. Somente parâmetros especificados + * serão atualizados.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile + *
+ *
+ * https://api.twitter.com/1.1/account/update_profile.json + * + * @return AccountSettings + * @throws TwitterException + */ + User updateProfile(String name, String url, String location, String description, String profile_link_color) throws TwitterException; + + /** + * Uploads a profile banner on behalf of the authenticating user.
+ *
+ * Atualiza o banner de perfil do usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_banner + *
+ *
+ * https://api.twitter.com/1.1/account/update_profile_banner.json + * + * @throws TwitterException + */ + void updateProfileBanner(String image) throws TwitterException; + + /** + * Uploads a profile banner on behalf of the authenticating user.
+ *
+ * Atualiza o banner de perfil do usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_banner + *
+ *
+ * https://api.twitter.com/1.1/account/update_profile_banner.json + * + * @throws TwitterException + */ + void updateProfileBanner(String image, int width, int height, int offset_left, int offset_top) throws TwitterException; + + /** + * Updates the authenticating user’s profile image. Note that this method expects raw multipart data, not a URL to an image.
+ *
+ * Atualiza a imagem de perfil do usuário autenticado. Note que esse método espera raw multipart data, não uma URL de alguma imagem.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image + *
+ *
+ * https://api.twitter.com/1.1/account/update_profile_image.json + * + * @throws TwitterException + */ + void updateProfileImage(String image) throws TwitterException; + + /** + * Returns an array of numeric user ids the authenticating user is blocking.
+ *
+ * Retorna uma lista de ids das pessoas bloqueadas pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-ids + *
+ *
+ * https://api.twitter.com/1.1/blocks/ids.json + * + * @throws TwitterException + */ + BirdList getBlockIDList(String cursor) throws TwitterException; + + /** + * Returns an array of numeric user ids the authenticating user is blocking.
+ *
+ * Retorna uma lista de ids das pessoas bloqueadas pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-ids + *
+ *
+ * https://api.twitter.com/1.1/blocks/ids.json + * + * @throws TwitterException + */ + BirdList getBlockIDList() throws TwitterException; + + /** + * Returns a collection of user objects that the authenticating user is blocking.
+ *
+ * Retorna uma lista de usuários bloqueados pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list + *
+ *
+ * https://api.twitter.com/1.1/blocks/list.json + * + * @throws TwitterException + */ + BirdList getBlockUserList(String cursor) throws TwitterException; + + /** + * Returns a collection of user objects that the authenticating user is blocking.
+ *
+ * Retorna uma lista de usuários bloqueados pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list + *
+ *
+ * https://api.twitter.com/1.1/blocks/list.json + * + * @throws TwitterException + */ + BirdList getBlockUserList() throws TwitterException; + + /** + * Returns an array of numeric user ids the authenticating user has muted.
+ *
+ * Retorna uma lista de ids das pessoas mutadas pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-ids + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/ids.json + * + * @throws TwitterException + */ + BirdList getMutesIDList(String cursor) throws TwitterException; + + /** + * Returns an array of user objects the authenticating user has muted.
+ *
+ * Retorna uma lista de usuários mutados pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-list + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/list.json + * + * @throws TwitterException + */ + BirdList getMutesUserList(String cursor) throws TwitterException; + + /** + * Returns an array of numeric user ids the authenticating user has muted.
+ *
+ * Retorna uma lista de ids das pessoas mutadas pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-ids + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/ids.json + * + * @throws TwitterException + */ + BirdList getMutesIDList() throws TwitterException; + + /** + * Returns an array of user objects the authenticating user has muted.
+ *
+ * Retorna uma lista de usuários mutados pelo usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-list + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/list.json + * + * @throws TwitterException + */ + BirdList getMutesUserList() throws TwitterException; + + /** + * Blocks the specified user from following the authenticating user.
+ *
+ * Bloqueia um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-create + *
+ *
+ * https://api.twitter.com/1.1/blocks/create.json + * + * @throws TwitterException + */ + User blockUser(String screenName) throws TwitterException; + + /** + * Blocks the specified user from following the authenticating user.
+ *
+ * Bloqueia um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-create + *
+ *
+ * https://api.twitter.com/1.1/blocks/create.json + * + * @throws TwitterException + */ + User blockUser(long userId) throws TwitterException; + + /** + * Un-blocks the user specified in the ID parameter for the authenticating user.
+ *
+ * Desbloqueia um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-destroy + *
+ *
+ * https://api.twitter.com/1.1/blocks/destroy.json + * + * @throws TwitterException + */ + User unblockUser(String screenName) throws TwitterException; + + /** + * Un-blocks the user specified in the ID parameter for the authenticating user.
+ *
+ * Desbloqueia um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-destroy + *
+ *
+ * https://api.twitter.com/1.1/blocks/destroy.json + * + * @throws TwitterException + */ + User unblockUser(long userId) throws TwitterException; + + // + + /** + * Mutes the user specified in the ID parameter for the authenticating user.
+ *
+ * Muta um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-create + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/create.json + * + * @throws TwitterException + */ + User muteUser(String screenName) throws TwitterException; + + /** + * Mutes the user specified in the ID parameter for the authenticating user.
+ *
+ * Muta um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-create + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/create.json + * + * @throws TwitterException + */ + User muteUser(long userId) throws TwitterException; + + /** + * Un-mutes the user specified in the ID parameter for the authenticating user.
+ *
+ * Desmuta um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-destroy + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/destroy.json + * + * @throws TwitterException + */ + User unmuteUser(String screenName) throws TwitterException; + + /** + * Un-mutes the user specified in the ID parameter for the authenticating user.
+ *
+ * Desmuta um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-destroy + *
+ *
+ * https://api.twitter.com/1.1/mutes/users/destroy.json + * + * @throws TwitterException + */ + User unmuteUser(long userId) throws TwitterException; + + /** + * Report the specified user as a spam account to Twitter.
+ *
+ * Reporta um usuário como spam.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-users-report_spam + *
+ *
+ * https://api.twitter.com/1.1/users/report_spam.json + * + * @throws TwitterException + */ + User reportSpam(String screenName, boolean block) throws TwitterException; + + /** + * Report the specified user as a spam account to Twitter.
+ *
+ * Reporta um usuário como spam.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-users-report_spam + *
+ *
+ * https://api.twitter.com/1.1/users/report_spam.json + * + * @throws TwitterException + */ + User reportSpam(long userId, boolean block) throws TwitterException; + + /** + * Returns a cursored collection of user IDs for every user following the specified user.
+ *
+ * Retorna uma lista de id de todos os seguidores de um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids + *
+ *
+ * https://api.twitter.com/1.1/followers/ids.json + * + * @throws TwitterException + */ + BirdList getFollowersIDList(String screenName, int count, String cursor) throws TwitterException; + + /** + * Returns a cursored collection of user IDs for every user following the specified user.
+ *
+ * Retorna uma lista de id de todos os seguidores de um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids + *
+ *
+ * https://api.twitter.com/1.1/followers/ids.json + * + * @throws TwitterException + */ + BirdList getFollowersIDList(long userId, int count, String cursor) throws TwitterException; + + /** + * Returns a cursored collection of user objects for users following the specified user.
+ *
+ * Retorna uma lista de usuários de todos os seguidores de um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-list + *
+ *
+ * https://api.twitter.com/1.1/followers/list.json + * + * @throws TwitterException + */ + BirdList getFollowersList(String screenName, int count, String cursor) throws TwitterException; + + /** + * Returns a cursored collection of user objects for users following the specified user.
+ *
+ * Retorna uma lista de usuários de todos os seguidores de um usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-list + *
+ *
+ * https://api.twitter.com/1.1/followers/list.json + * + * @throws TwitterException + */ + BirdList getFollowersList(long userId, int count, String cursor) throws TwitterException; + + // + + /** + * Returns a cursored collection of user IDs for every user the specified user is following (otherwise known as their “friends”).
+ *
+ * Retorna uma lista de id de todas as pessoas que o usuário segue.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids + *
+ *
+ * https://api.twitter.com/1.1/friends/ids.json + * + * @throws TwitterException + */ + BirdList getFollowingIDList(String screenName, int count, String cursor) throws TwitterException; + + /** + * Returns a cursored collection of user IDs for every user the specified user is following (otherwise known as their “friends”).
+ *
+ * Retorna uma lista de id de todas as pessoas que o usuário segue.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids + *
+ *
+ * https://api.twitter.com/1.1/friends/ids.json + * + * @throws TwitterException + */ + BirdList getFollowingIDList(long userId, int count, String cursor) throws TwitterException; + + /** + * Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their “friends”).
+ *
+ * Retorna uma lista de usuários de todos as pessoas que o usuário segue.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list + *
+ *
+ * https://api.twitter.com/1.1/friends/list.json + * + * @throws TwitterException + */ + BirdList getFollowingList(String screenName, int count, String cursor) throws TwitterException; + + /** + * Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their “friends”).
+ *
+ * Retorna uma lista de usuários de todos as pessoas que o usuário segue.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list + *
+ *
+ * https://api.twitter.com/1.1/friends/list.json + * + * @throws TwitterException + */ + BirdList getFollowingList(long userId, int count, String cursor) throws TwitterException; + + /** + * Returns a collection of numeric IDs for every user who has a pending request to follow the authenticating user.
+ *
+ * Retorna uma lista de id de todos os usuários que possuem um pedido de follow para o usuário autenticado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming + *
+ *
+ * https://api.twitter.com/1.1/friendships/incoming.json + * + * @throws TwitterException + */ + BirdList getIncomingRequests(String cursor) throws TwitterException; + + /** + * Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided
+ *
+ * Retorna as relações entre o usuário autenticado e o(s) usuário(s) (Máximo 100 usuários por request).
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-lookup + *
+ *
+ * https://api.twitter.com/1.1/friendships/lookup.json + * + * @throws TwitterException + */ + List relationsLookup(String... screen_names) throws TwitterException; + + /** + * Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided
+ *
+ * Retorna as relações entre o usuário autenticado e o(s) usuário(s) (Máximo 100 usuários por request).
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-lookup + *
+ *
+ * https://api.twitter.com/1.1/friendships/lookup.json + * + * @throws TwitterException + */ + List relationsLookup(long... usersId) throws TwitterException; + + /** + * Returns a collection of numeric IDs for every protected user for whom the authenticating user has a pending follow request.
+ *
+ * Retorna uma lista de id de todos os usuários que o usuário autenticado pediu para seguir.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-outgoing + *
+ *
+ * https://api.twitter.com/1.1/friendships/outgoing.json + * + * @throws TwitterException + */ + BirdList getOutcomingRequests(String cursor) throws TwitterException; + + /** + * Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
+ *
+ * Retorna uma lista de usuários (Máximo 100 usuários por request).
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup + *
+ *
+ * https://api.twitter.com/1.1/users/lookup.json + * + * @throws TwitterException + */ + BirdList userLookup(String... screenNames) throws TwitterException; + + /** + * Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
+ *
+ * Retorna uma lista de usuários (Máximo 100 usuários por request).
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup + *
+ *
+ * https://api.twitter.com/1.1/users/lookup.json + * + * @throws TwitterException + */ + BirdList userLookup(long... usersId) throws TwitterException; + + /** + * Returns a variety of information about the user specified by the required user_id or screen_name parameter.
+ *
+ * Retorna um usuário especificado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show + *
+ *
+ * https://api.twitter.com/1.1/users/show.json + * + * @throws TwitterException + */ + User getUser(String screenName) throws TwitterException; + + /** + * Returns a variety of information about the user specified by the required user_id or screen_name parameter.
+ *
+ * Retorna um usuário especificado.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show + *
+ *
+ * https://api.twitter.com/1.1/users/show.json + * + * @throws TwitterException + */ + User getUser(long userId) throws TwitterException; + + /** + * Allows the authenticating user to follow (friend) the user specified in the ID parameter.
+ *
+ * Faz o usuário autenticado seguir outro usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create + *
+ *
+ * https://api.twitter.com/1.1/friendships/create.json + * + * @throws TwitterException + */ + User followUser(String screenName) throws TwitterException; + + /** + * Allows the authenticating user to follow (friend) the user specified in the ID parameter.
+ *
+ * Faz o usuário autenticado seguir outro usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create + *
+ *
+ * https://api.twitter.com/1.1/friendships/create.json + * + * @throws TwitterException + */ + User followUser(long userId) throws TwitterException; + + /** + * Allows the authenticating user to unfollow the user specified in the ID parameter.
+ *
+ * Faz o usuário autenticado parar de seguir outro usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy + *
+ *
+ * https://api.twitter.com/1.1/friendships/destroy.json + * + * @throws TwitterException + */ + User unfollowUser(String screenName) throws TwitterException; + + /** + * Allows the authenticating user to unfollow the user specified in the ID parameter.
+ *
+ * Faz o usuário autenticado parar de seguir outro usuário.
+ *
+ * https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy + *
+ *
+ * https://api.twitter.com/1.1/friendships/destroy.json + * + * @throws TwitterException + */ + User unfollowUser(long userId) throws TwitterException; + + //wip +} \ No newline at end of file diff --git a/src/main/java/com/github/langsdorf/blackbird/user/list/BirdList.java b/src/main/java/com/github/langsdorf/blackbird/user/list/BirdList.java new file mode 100644 index 0000000..d902dfe --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/list/BirdList.java @@ -0,0 +1,13 @@ +package com.github.langsdorf.blackbird.user.list; + +import java.util.List; + +public interface BirdList extends List { + + String getNextCursor(); + String getPreviousCursor(); + void setNextCursor(String next_cursor); + void setPreviousCursor(String previous_cursor); + + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/user/list/BirdListImp.java b/src/main/java/com/github/langsdorf/blackbird/user/list/BirdListImp.java new file mode 100644 index 0000000..5dc869f --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/list/BirdListImp.java @@ -0,0 +1,20 @@ +package com.github.langsdorf.blackbird.user.list; + +import java.util.ArrayList; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Setter +@Getter +public class BirdListImp extends ArrayList implements BirdList { + + private static final long serialVersionUID = -604790975019671108L; + + private String nextCursor; + private String previousCursor; +} diff --git a/src/main/java/com/github/langsdorf/blackbird/user/misc/AccountSettings.java b/src/main/java/com/github/langsdorf/blackbird/user/misc/AccountSettings.java new file mode 100644 index 0000000..247856b --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/misc/AccountSettings.java @@ -0,0 +1,26 @@ +package com.github.langsdorf.blackbird.user.misc; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class AccountSettings { + + private String language; + private boolean protectedUser; + private String screenName; + private boolean sleepTimeEnabled; + private int sleepTimeEnd; + private int sleepTimeStart; + private String timezone; + private String tzinfoName; + private String country; + private String countryCode; + private String locationName; + + + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/user/misc/Banner.java b/src/main/java/com/github/langsdorf/blackbird/user/misc/Banner.java new file mode 100644 index 0000000..befaf4e --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/misc/Banner.java @@ -0,0 +1,17 @@ +package com.github.langsdorf.blackbird.user.misc; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +public class Banner { + + private String URL; + private BannerSizes size; + private long userId; + private String userScreenName; + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/user/misc/BannerSizes.java b/src/main/java/com/github/langsdorf/blackbird/user/misc/BannerSizes.java new file mode 100644 index 0000000..dc4e394 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/misc/BannerSizes.java @@ -0,0 +1,7 @@ +package com.github.langsdorf.blackbird.user.misc; + +public enum BannerSizes { + + IPAD, IPAD_RETINA, WEB, WEB_RETINA, MOBILE, MOBILE_RETINA, S_300x100, S_600x200, S_1500x500; + +} diff --git a/src/main/java/com/github/langsdorf/blackbird/user/misc/Relationships.java b/src/main/java/com/github/langsdorf/blackbird/user/misc/Relationships.java new file mode 100644 index 0000000..a481947 --- /dev/null +++ b/src/main/java/com/github/langsdorf/blackbird/user/misc/Relationships.java @@ -0,0 +1,7 @@ +package com.github.langsdorf.blackbird.user.misc; + +public enum Relationships { + + FOLLOWING, FOLLOWING_REQUESTED, FOLLOWED_BY, BLOCKING, MUTING, NONE; + +} diff --git a/src/test/java/com/github/langsdorf/blackbird/AuthTest.java b/src/test/java/com/github/langsdorf/blackbird/AuthTest.java new file mode 100644 index 0000000..929c359 --- /dev/null +++ b/src/test/java/com/github/langsdorf/blackbird/AuthTest.java @@ -0,0 +1,43 @@ +package com.github.langsdorf.blackbird; + +import java.util.Scanner; +import java.util.concurrent.ThreadLocalRandom; + +import com.github.langsdorf.blackbird.BlackBird; +import com.github.langsdorf.blackbird.URLBasedOAuth; +import com.github.langsdorf.blackbird.api.TweetAPI; +import com.github.langsdorf.blackbird.exception.TwitterException; + +public class AuthTest { + + public static void main(String[] args) throws TwitterException { + String consumerKey = ""; + String consumerSecret = ""; + String accessToken = ""; + String accessTokenSecret = ""; + testAuth1(consumerKey, consumerSecret); + testAuth2(consumerKey, consumerSecret, accessToken, accessTokenSecret); + } + + public static void testAuth1(String consumerKey, String consumerSecret) throws TwitterException { + URLBasedOAuth oauthURL = new URLBasedOAuth(consumerKey, consumerSecret); + Scanner in = new Scanner(System.in); + System.out.println(oauthURL.getAuthorizationUrl()); + + String pin = in.nextLine(); + + BlackBird blackBird = oauthURL.authenticate(pin); + TweetAPI tweet_api = blackBird.getTweetAPI(); + tweet_api.createTweet("Working! " + ThreadLocalRandom.current().nextInt(0, 100)); + + in.close(); + } + + public static void testAuth2(String consumerKey, String consumerSecret, String accessToken, + String accessTokenSecret) throws TwitterException { + BlackBird bb = new BlackBird(consumerKey, consumerSecret, accessToken, accessTokenSecret); + TweetAPI tweet_api = bb.getTweetAPI(); + tweet_api.createTweet("Working! " + ThreadLocalRandom.current().nextInt(0, 100)); + } + +}