├── settings.gradle ├── .travis.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── main │ └── java │ │ └── twijava │ │ ├── exception │ │ └── TwiJavaException.java │ │ ├── encode │ │ └── ParamEncoder.java │ │ ├── json │ │ ├── objects │ │ │ └── TwitterJsonObjects.java │ │ └── util │ │ │ └── JsonDecoder.java │ │ ├── FriendList.java │ │ ├── FollowerList.java │ │ ├── UserProfile.java │ │ ├── DeleteTweet.java │ │ ├── SearchTweet.java │ │ ├── Tweet.java │ │ ├── HomeTimeLine.java │ │ ├── UserTimeLine.java │ │ ├── oauth │ │ ├── OAuthSupportParamFactory.java │ │ ├── OAuthBasicCodeFactory.java │ │ ├── OAuthParamFactory.java │ │ ├── OAuthSignatureFactory.java │ │ ├── OAuthMapFactory.java │ │ └── OAuthHeaderFactory.java │ │ ├── url │ │ └── TwitterApiURLs.java │ │ ├── APIKeyFactory.java │ │ ├── TwiJava.java │ │ ├── http │ │ ├── HttpResponseHandler.java │ │ └── core │ │ │ └── HttpRequest.java │ │ └── TwitterRequests.java └── test │ └── java │ ├── TokenbuilderTest.java │ └── TestHttpRequest.java ├── LICENCE ├── gradlew.bat ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'TwiJava' 2 | 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk8 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rf0321/twi-Java/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | target/ 3 | build/ 4 | .gradle/ 5 | #Package Files 6 | *.jar 7 | !gradle-wrapper.jar 8 | Main.java 9 | /.idea 10 | /out 11 | # VScode ignore extension 12 | /.vscode -------------------------------------------------------------------------------- /src/main/java/twijava/exception/TwiJavaException.java: -------------------------------------------------------------------------------- 1 | package twijava.exception; 2 | 3 | public class TwiJavaException extends Exception { 4 | public TwiJavaException(String str) { 5 | super(str); 6 | } 7 | } 8 | 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Jul 11 19:37:18 JST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip 7 | -------------------------------------------------------------------------------- /src/test/java/TokenbuilderTest.java: -------------------------------------------------------------------------------- 1 | public class TokenbuilderTest { 2 | public static String somekey; 3 | 4 | public void printKey() throws Exception{ 5 | if(somekey == null){ 6 | throw new Exception("key not found"); 7 | } 8 | else{ 9 | System.out.println(somekey); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/twijava/encode/ParamEncoder.java: -------------------------------------------------------------------------------- 1 | package twijava.encode; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.net.URLEncoder; 5 | 6 | public class ParamEncoder { 7 | 8 | public static String encode(String params){ 9 | try{ 10 | return URLEncoder.encode(params,"UTF-8").replace("+","%20"); 11 | } 12 | catch (UnsupportedEncodingException e){ 13 | return e.toString(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/twijava/json/objects/TwitterJsonObjects.java: -------------------------------------------------------------------------------- 1 | package twijava.json.objects; 2 | 3 | public class TwitterJsonObjects { //Twitter json objects need to parsing json. 4 | /** 5 | * @param created_at tweet made by twitter user 6 | * @param id_str id string 7 | * @param text tweet content(text) 8 | * @param id id integer 9 | */ 10 | public final String created_at="created_at"; 11 | public final String text="text"; 12 | public final String user="user"; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/twijava/FriendList.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.http.core.HttpRequest; 4 | import twijava.url.TwitterApiURLs; 5 | 6 | import java.util.TreeMap; 7 | 8 | public class FriendList { 9 | 10 | public String getFriendRequest(){ 11 | 12 | TreeMap param = new TreeMap<>(); 13 | param.put("cursor","-1"); 14 | 15 | HttpRequest httpRequest = new HttpRequest(); 16 | 17 | return httpRequest.get(TwitterApiURLs.FRIENDS_URL,param); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/twijava/FollowerList.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.http.core.HttpRequest; 4 | import twijava.url.TwitterApiURLs; 5 | 6 | import java.util.TreeMap; 7 | 8 | public class FollowerList { 9 | 10 | public String getFollowerRequest(){ 11 | 12 | TreeMap param = new TreeMap<>(); 13 | param.put("cursor","-1"); 14 | 15 | HttpRequest httpRequest = new HttpRequest(); 16 | 17 | return httpRequest.get(TwitterApiURLs.FOLLOWERS_URL,param); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/twijava/UserProfile.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.url.TwitterApiURLs; 4 | import twijava.http.core.HttpRequest; 5 | 6 | import java.util.TreeMap; 7 | 8 | public class UserProfile { 9 | 10 | public String getProfileRequest(String screenName){ 11 | 12 | TreeMapparam = new TreeMap<>(); 13 | param.put("screen_name",screenName); 14 | 15 | HttpRequest httpRequest = new HttpRequest(); 16 | 17 | return httpRequest.get(TwitterApiURLs.PROFILE_URL,param); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/twijava/DeleteTweet.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.url.TwitterApiURLs; 4 | import twijava.http.core.HttpRequest; 5 | 6 | import java.util.TreeMap; 7 | 8 | public class DeleteTweet { 9 | 10 | public void deleteRequest(String idStr){ 11 | 12 | TreeMap param = new TreeMap<>(); 13 | param.put("id",idStr); 14 | 15 | HttpRequest httpRequest = new HttpRequest(); 16 | 17 | String requestUri = TwitterApiURLs.USER_DESTROY_URL+idStr+".json"; 18 | 19 | httpRequest.post(requestUri, param); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/twijava/SearchTweet.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.url.TwitterApiURLs; 4 | import twijava.encode.ParamEncoder; 5 | import twijava.http.core.HttpRequest; 6 | 7 | import java.util.TreeMap; 8 | 9 | public class SearchTweet { 10 | 11 | public String searchRequest(String query){ 12 | 13 | TreeMap param = new TreeMap<>(); 14 | param.put("q", ParamEncoder.encode(query)); 15 | 16 | HttpRequest httpRequest = new HttpRequest(); 17 | 18 | return httpRequest.get(TwitterApiURLs.SEACH_URL,param); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/twijava/Tweet.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.url.TwitterApiURLs; 4 | import twijava.encode.ParamEncoder; 5 | import twijava.http.core.HttpRequest; 6 | 7 | import java.util.TreeMap; 8 | 9 | public class Tweet { 10 | 11 | public void tweetRequest(String text){ 12 | 13 | TreeMap param = new TreeMap<>(); 14 | param.put("status", ParamEncoder.encode(text)); 15 | param.put("trim_user","1"); 16 | 17 | HttpRequest httpRequest = new HttpRequest(); 18 | 19 | httpRequest.post(TwitterApiURLs.USER_UPDATESTATUS_URL,param); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/twijava/HomeTimeLine.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.url.TwitterApiURLs; 4 | import twijava.http.core.HttpRequest; 5 | 6 | import java.util.TreeMap; 7 | 8 | public class HomeTimeLine { 9 | 10 | public String getTimeLineRequest(int count){ 11 | 12 | String sendCount = String.valueOf(count); 13 | 14 | TreeMap param = new TreeMap<>(); 15 | param.put("count", sendCount); 16 | param.put("trim_user", "1"); 17 | 18 | HttpRequest httpRequest = new HttpRequest(); 19 | 20 | return httpRequest.get(TwitterApiURLs.HOME_TIMELINE_URL,param); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/twijava/UserTimeLine.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import twijava.url.TwitterApiURLs; 4 | import twijava.http.core.HttpRequest; 5 | 6 | import java.util.TreeMap; 7 | 8 | public class UserTimeLine { 9 | 10 | public String getTimeLineRequest(int count){ 11 | 12 | String sendCount = String.valueOf(count); 13 | 14 | TreeMap param = new TreeMap<>(); 15 | param.put("count", sendCount); 16 | param.put("trim_user", "1"); 17 | 18 | HttpRequest httpRequest = new HttpRequest(); 19 | 20 | return httpRequest.get(TwitterApiURLs.USER_TIMELINE_URL,param); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/twijava/oauth/OAuthSupportParamFactory.java: -------------------------------------------------------------------------------- 1 | package twijava.oauth; 2 | 3 | import java.util.Random; 4 | import java.util.TreeMap; 5 | import java.util.stream.Collectors; 6 | 7 | public class OAuthSupportParamFactory { 8 | 9 | public static String generateNonce() { 10 | 11 | Random rnd = new Random(); 12 | 13 | return String.valueOf(123400 + rnd.nextInt(9999999 - 123400)); 14 | } 15 | 16 | public static String oAuthParamAppending(TreeMap param) { 17 | return param.entrySet().stream() 18 | .map(e -> e.getKey() + "=" + e.getValue()) 19 | .collect(Collectors.joining("&")); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/twijava/oauth/OAuthBasicCodeFactory.java: -------------------------------------------------------------------------------- 1 | package twijava.oauth; 2 | 3 | import javax.crypto.Mac; 4 | import javax.crypto.SecretKey; 5 | import javax.crypto.spec.SecretKeySpec; 6 | import java.nio.charset.StandardCharsets; 7 | import java.util.Base64; 8 | 9 | public class OAuthBasicCodeFactory { 10 | 11 | public static String makeBasicCode(String base,String key) throws Exception{ 12 | 13 | SecretKey secretKey; 14 | byte[]keyByte = key.getBytes(); 15 | secretKey = new SecretKeySpec(keyByte,"HmacSHA1"); 16 | 17 | Mac mac = Mac.getInstance("HmacSHA1"); 18 | mac.init(secretKey); 19 | byte[]text=base.getBytes(StandardCharsets.US_ASCII); 20 | 21 | return Base64.getEncoder().encodeToString(mac.doFinal(text)).trim(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/twijava/oauth/OAuthParamFactory.java: -------------------------------------------------------------------------------- 1 | package twijava.oauth; 2 | import java.util.*; 3 | 4 | public class OAuthParamFactory { 5 | 6 | public static String makeURLwithParam(String url,TreeMapparamMap){ 7 | 8 | StringBuffer strBuffer=new StringBuffer(url); 9 | TreeMaptreeMap=new TreeMap<>(); 10 | treeMap.putAll(paramMap); 11 | 12 | for (Map.Entry paramEntry : treeMap.entrySet()) { 13 | if (paramEntry.equals(treeMap.firstEntry())) { 14 | strBuffer.append("?"); 15 | } else { 16 | strBuffer.append("&"); 17 | } 18 | strBuffer.append(paramEntry.getKey() + "=" + paramEntry.getValue()); 19 | } 20 | 21 | return strBuffer.toString(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/twijava/oauth/OAuthSignatureFactory.java: -------------------------------------------------------------------------------- 1 | package twijava.oauth; 2 | 3 | import twijava.encode.ParamEncoder; 4 | 5 | import java.util.TreeMap; 6 | 7 | public class OAuthSignatureFactory { 8 | 9 | public static String makeSignature(String method, String url, 10 | TreeMap urlParam, TreeMapoauthParam){ 11 | TreeMaptreeMap= new TreeMap<>(); 12 | 13 | treeMap.putAll(urlParam); 14 | treeMap.putAll(oauthParam); 15 | 16 | String paramStr= OAuthSupportParamFactory.oAuthParamAppending(treeMap); 17 | 18 | String temp="%s&%s&%s"; 19 | 20 | return String.format(temp, 21 | ParamEncoder.encode(method), 22 | ParamEncoder.encode(url), 23 | ParamEncoder.encode(paramStr)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/twijava/oauth/OAuthMapFactory.java: -------------------------------------------------------------------------------- 1 | package twijava.oauth; 2 | 3 | import java.util.Calendar; 4 | import java.util.TimeZone; 5 | import java.util.TreeMap; 6 | 7 | 8 | public class OAuthMapFactory { 9 | 10 | public static TreeMap getOAuthMap(String ck, String ac) { 11 | 12 | //Components of need to authorization 13 | TreeMap data = new TreeMap<>(); 14 | data.put("oauth_consumer_key", ck); 15 | data.put("oauth_signature_method", "HMAC-SHA1"); 16 | data.put("oauth_timestamp", String.valueOf(Calendar 17 | .getInstance(TimeZone.getTimeZone("UTC")).getTime().getTime() / 1000)); 18 | data.put("oauth_nonce", OAuthSupportParamFactory.generateNonce()); 19 | data.put("oauth_token", ac); 20 | data.put("oauth_version", "1.0"); 21 | 22 | return data; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2017] [ItinoseSan] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/java/twijava/url/TwitterApiURLs.java: -------------------------------------------------------------------------------- 1 | package twijava.url; 2 | 3 | /** 4 | * Request url of TwitterAPI 5 | *

These url is not all, for this Wrapper

6 | */ 7 | public class TwitterApiURLs { 8 | 9 | public static final String END_POINT_URL = ("https://api.twitter.com/1.1/"); 10 | 11 | public static final String HOME_TIMELINE_URL = ("statuses/home_timeline.json"); 12 | 13 | public static final String USER_TIMELINE_URL = ("statuses/user_timeline.json"); 14 | 15 | public static final String USER_UPDATESTATUS_URL = ("statuses/update.json"); 16 | 17 | public static final String USER_DESTROY_URL = ("statuses/destroy/"); 18 | 19 | public static final String SEACH_URL = ("search/tweets.json"); 20 | 21 | public static final String PROFILE_URL = ("users/show.json"); 22 | 23 | public static final String FOLLOWERS_URL = ("followers/list.json"); 24 | 25 | public static final String FRIENDS_URL = ("friends/list.json"); 26 | 27 | public static final String USER_CREATEMESSAGE_URL= ("direct_messages/events/new.json"); 28 | 29 | /* 30 | private static final String FOLLOWERS_URL="followers/list.json"; 31 | private static final String FOLLOW_URL="friends/list.json"; 32 | */ 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/twijava/APIKeyFactory.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | import java.util.TreeMap; 4 | 5 | public class APIKeyFactory { 6 | 7 | /** 8 | * @param OAuth Consumer Key 9 | */ 10 | private static String consumerKey; 11 | 12 | /** 13 | * @param OAuth Consumer Secret Key 14 | */ 15 | private static String consumerSecretKey; 16 | 17 | /** 18 | * @param OAuth Access Token 19 | */ 20 | private static String accessToken; 21 | 22 | /** 23 | * @param OAuth Access Token Secret 24 | */ 25 | private static String accessTokenSecret; 26 | 27 | public void buildKey(String consumerKey,String consumerSecretKey, 28 | String accessToken,String accessTokenSecret){ 29 | this.consumerKey = consumerKey; 30 | this.consumerSecretKey = consumerSecretKey; 31 | this.accessToken = accessToken; 32 | this.accessTokenSecret = accessTokenSecret; 33 | } 34 | 35 | public static TreeMapapiKeyMap(){ 36 | 37 | TreeMap keys = new TreeMap<>(); 38 | keys.put("ck",consumerKey); 39 | keys.put("cks",consumerSecretKey); 40 | keys.put("ac",accessToken); 41 | keys.put("ats",accessTokenSecret); 42 | 43 | return keys; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/twijava/TwiJava.java: -------------------------------------------------------------------------------- 1 | /** 2 | * TwiJava class 3 | *

This is client class

4 | */ 5 | package twijava; 6 | 7 | public class TwiJava{ 8 | 9 | private TwitterRequests requests = new TwitterRequests(); 10 | 11 | private APIKeyFactory keyFactory = new APIKeyFactory(); 12 | 13 | public void authorize(String ck,String cks,String ac,String ats){ 14 | keyFactory.buildKey(ck, cks, ac, ats); 15 | } 16 | 17 | public void tweet(String text){ 18 | requests.tweet(text); 19 | } 20 | 21 | public void deleteTweet(String idStr){ 22 | requests.deleteTweet(idStr); 23 | } 24 | 25 | public String searchTweet(String query){ 26 | return requests.searchTweet(query); 27 | } 28 | 29 | public String getUserProfile(String screen_name){ 30 | return requests.getUserProfile(screen_name); 31 | } 32 | 33 | public String getFollowerList(){ 34 | return requests.getFollowerList(); 35 | } 36 | 37 | public String getFriendList(){ 38 | return requests.getFriendList(); 39 | } 40 | 41 | public String getHomeTimeLine(int count){ 42 | return requests.getHomeTimeLine(count); 43 | } 44 | 45 | public String getUserTimeLine(int count){ 46 | return requests.getUserTimeLine(count); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/twijava/oauth/OAuthHeaderFactory.java: -------------------------------------------------------------------------------- 1 | package twijava.oauth; 2 | 3 | import twijava.encode.ParamEncoder; 4 | 5 | import java.util.TreeMap; 6 | 7 | public class OAuthHeaderFactory { 8 | 9 | public static String makeOAuthHeader(String signature,TreeMap oAuthParam, 10 | String cks,String ats) throws Exception{ 11 | 12 | String compoKey = ParamEncoder.encode(cks)+"&"+ ParamEncoder.encode(ats); 13 | 14 | String oauthSignature = OAuthBasicCodeFactory.makeBasicCode(signature,compoKey); 15 | 16 | String encodedSignature = ParamEncoder.encode(oauthSignature); 17 | 18 | //esape data strings 19 | String authHeaderTemp="OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", " + 20 | "oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\""; 21 | 22 | return String.format(authHeaderTemp, 23 | oAuthParam.get("oauth_consumer_key"), 24 | oAuthParam.get("oauth_nonce"), 25 | encodedSignature, 26 | oAuthParam.get("oauth_signature_method"), 27 | oAuthParam.get("oauth_timestamp"), 28 | oAuthParam.get("oauth_token"), 29 | oAuthParam.get("oauth_version")); 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/twijava/http/HttpResponseHandler.java: -------------------------------------------------------------------------------- 1 | package twijava.http; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.net.HttpURLConnection; 6 | 7 | public class HttpResponseHandler { 8 | 9 | public static String receiveResponse(HttpURLConnection connection) throws Exception { 10 | 11 | InputStreamReader isr = connection.getResponseCode() == HttpURLConnection.HTTP_OK ? 12 | new InputStreamReader(connection.getInputStream()) 13 | : new InputStreamReader(connection.getErrorStream()); 14 | 15 | BufferedReader reader = new BufferedReader(isr); 16 | StringBuilder responseJson = new StringBuilder(); 17 | 18 | return handleResponse(connection,reader, responseJson); 19 | } 20 | 21 | private static String handleResponse(HttpURLConnection connection, BufferedReader reader, 22 | StringBuilder json) throws Exception{ 23 | String line; 24 | 25 | int code = connection.getResponseCode(); 26 | while ((line = reader.readLine()) != null) { 27 | if(code == HttpURLConnection.HTTP_OK) { 28 | System.out.println("HttpRequest accepted"); 29 | } 30 | System.out.println("Response json"); 31 | System.out.println(json.append(line)+"\n"); 32 | } 33 | reader.close(); 34 | 35 | return json.toString(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/TestHttpRequest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import java.io.*; 4 | import java.net.HttpURLConnection; 5 | import java.net.URL; 6 | import java.nio.charset.StandardCharsets; 7 | 8 | public class TestHttpRequest 9 | { 10 | public String post(String authheader,String url)throws IOException{ 11 | URL urls=new URL(url); 12 | HttpURLConnection connection=(HttpURLConnection)urls.openConnection(); 13 | 14 | connection.setRequestMethod("POST"); 15 | connection.setRequestProperty("Authorization",authheader); 16 | connection.connect(); 17 | BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)); 18 | writer.write(authheader); 19 | writer.flush(); 20 | 21 | InputStreamReader isr = connection.getResponseCode() == HttpURLConnection.HTTP_OK ? new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8) : new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8); 22 | BufferedReader reader = new BufferedReader(isr); 23 | String line; 24 | String resultLine = ""; 25 | System.out.println("----- Body -----"); 26 | while((line = reader.readLine()) != null) { 27 | System.out.println(line); 28 | resultLine = resultLine + line; 29 | } 30 | writer.close(); 31 | reader.close(); 32 | 33 | return resultLine; 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/twijava/TwitterRequests.java: -------------------------------------------------------------------------------- 1 | package twijava; 2 | 3 | 4 | public class TwitterRequests { 5 | /** 6 | * @param request instances 7 | */ 8 | private Tweet tweet = new Tweet(); 9 | 10 | private DeleteTweet deleteTweet = new DeleteTweet(); 11 | 12 | private HomeTimeLine home = new HomeTimeLine(); 13 | 14 | private UserTimeLine user = new UserTimeLine(); 15 | 16 | private UserProfile profile = new UserProfile(); 17 | 18 | private FollowerList follower = new FollowerList(); 19 | 20 | private FriendList friend = new FriendList(); 21 | 22 | private SearchTweet search = new SearchTweet(); 23 | 24 | public void tweet(String text){ 25 | tweet.tweetRequest(text); 26 | } 27 | 28 | public void deleteTweet(String idStr){ 29 | deleteTweet.deleteRequest(idStr); 30 | } 31 | 32 | public String getUserProfile(String screen_name) { 33 | return profile.getProfileRequest(screen_name); 34 | } 35 | 36 | public String getFollowerList(){ 37 | return follower.getFollowerRequest(); 38 | } 39 | 40 | public String getFriendList(){ 41 | return friend.getFriendRequest(); 42 | } 43 | 44 | public String searchTweet(String query){ 45 | return search.searchRequest(query); 46 | } 47 | 48 | public String getHomeTimeLine(int count){ 49 | return home.getTimeLineRequest(count); 50 | } 51 | 52 | public String getUserTimeLine(int count){ 53 | return user.getTimeLineRequest(count); 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/twijava/json/util/JsonDecoder.java: -------------------------------------------------------------------------------- 1 | package twijava.json.util; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONException; 5 | 6 | import org.json.JSONObject; 7 | import twijava.json.objects.TwitterJsonObjects; 8 | 9 | import java.util.stream.IntStream; 10 | 11 | 12 | 13 | public class JsonDecoder { 14 | 15 | public static void decodeTimeLine(String responejson) { 16 | TwitterJsonObjects objects=new TwitterJsonObjects(); 17 | try{ 18 | JSONArray jsonArray=new JSONArray(responejson); 19 | IntStream.range(0, jsonArray.length()) 20 | .mapToObj(i -> jsonArray.getJSONObject(i)) 21 | .forEach(i -> System.out.println( 22 | "Posted:"+i.getString(objects.created_at)+"\n"+ 23 | "User_id:"+ i.getJSONObject(objects.user).getInt("id")+"\n"+ 24 | "Tweet:"+i.getString(objects.text)+"\n")); 25 | } 26 | catch (JSONException e){ 27 | sayError(); 28 | } 29 | } 30 | 31 | private static void sayError(){ 32 | 33 | System.out.println("ParseError:You might be wrong decode method"); 34 | } 35 | } 36 | /*for(int i=0; idata){ 16 | return makeSendParam("GET",uri,data); 17 | } 18 | 19 | public String post(String uri,TreeMapdata){ 20 | return makeSendParam("POST",uri,data); 21 | } 22 | 23 | private String makeSendParam(String method, String uri, TreeMapdata) { 24 | 25 | try { 26 | TreeMapkeyMap = APIKeyFactory.apiKeyMap(); 27 | 28 | StringBuilder urlBuilder = new StringBuilder(); 29 | 30 | String url = urlBuilder 31 | .append(TwitterApiURLs.END_POINT_URL) 32 | .append(uri).toString(); 33 | 34 | System.out.println("Request Url:"+url); 35 | 36 | TreeMap oauthMap = OAuthMapFactory.getOAuthMap(keyMap.get("ck"),keyMap.get("ac")); 37 | 38 | String signature = OAuthSignatureFactory.makeSignature(method, url, data, oauthMap); 39 | String oAuthHeader = OAuthHeaderFactory.makeOAuthHeader(signature, oauthMap,keyMap.get("cks"),keyMap.get("ats")); 40 | String urlWithParam = OAuthParamFactory.makeURLwithParam(url, data); 41 | 42 | URL sendUrl = new URL(urlWithParam); 43 | return sendRequest(sendUrl,oAuthHeader,method); 44 | 45 | } catch (Exception e) { 46 | return e.toString(); 47 | } 48 | } 49 | 50 | private String sendRequest(URL sendUrl,String oAuthHeader,String method) { 51 | 52 | try { 53 | 54 | HttpURLConnection urlConnection = (HttpURLConnection) sendUrl.openConnection(); 55 | 56 | urlConnection.setRequestProperty("Authorization", oAuthHeader); 57 | urlConnection.setRequestMethod(method); 58 | urlConnection.connect(); 59 | 60 | return HttpResponseHandler.receiveResponse(urlConnection); 61 | 62 | } catch (Exception e) { 63 | return e.toString(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Twi-Java 2 | [![LICENCE](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/ItinoseSan/Twi-Java/blob/0109/LICENCE) 3 | [![Maintainability](https://api.codeclimate.com/v1/badges/3c5aba0c8532ff256c50/maintainability)](https://codeclimate.com/github/ItinoseSan/twi-Java/maintainability) 4 | [![Build Status](https://travis-ci.org/ItinoseSan/twi-Java.svg?branch=0109)](https://travis-ci.org/ItinoseSan/twi-Java) 5 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) 6 | 7 | Twitter API wrapper for Java 8 | 9 | Main API wrapping is implemented by standard library. 10 | 11 | Json Decoding is implmented by org.json. 12 | 13 | # Java Version 14 | This wrapper's current java version is java8 15 | # Installation 16 | ### 1.Download Twi-Java.jar 17 | ### 2.Add as Library the jar 18 | # Usage 19 | About detail of params that send to api, please check [API Reference](https://developer.twitter.com) 20 | ## Get Instance 21 | ```java 22 | TwiJava twitter = new TwiJava(); 23 | ``` 24 | ## Authentication in API keys(Required method) 25 | ```java 26 | twitter.authorize("consumerKey","consumerSecretKey","accessToken","accessTokenSecret"); 27 | ``` 28 | ## Tweet 29 | ```java 30 | twitter.tweet("Hello World"); 31 | ``` 32 | ## Delete Tweet 33 | ```java 34 | twitter.deleteTweet("your tweet id_str"); 35 | ``` 36 | ## Search Tweet 37 | ```java 38 | twitter.searchTweet("Hello"); 39 | ``` 40 | ## Custom Search Tweet 41 | If you use optional param 42 | ```java 43 | TreeMap customSearch = new TreeMap<>(); 44 | customSearch.put("q",ParamEncoder.encode("Hello")); 45 | // Below is optional params 46 | customSearch.put("count","25"); 47 | customSearch.put("locale","ja"); 48 | customSearch.put("result_type","popular"); 49 | 50 | HttpRequest httpRequest = new HttpRequest(); 51 | httpRequest.get(TwitterApiURLs.SEACH_URL,customSearch); 52 | ``` 53 | ## Get User Timeline 54 | ```java 55 | twitter.getUserTimeLine(100); 56 | ``` 57 | ## Get Home Timeline 58 | ```java 59 | twitter.getHomeTimeLine(100); 60 | ``` 61 | ## Get User Profile 62 | ```java 63 | twitter.getUserProfile("screen_name"); 64 | ``` 65 | ## Get Follower List 66 | ```java 67 | twitter.getFollowerList(); 68 | ``` 69 | ## Custom Get Follower List 70 | ```java 71 | TreeMap param = new TreeMap<>(); 72 | param.put("cursor","-1"); 73 | // Below is optional params 74 | param.put("screen_name","twitter's @id"); 75 | param.put("count","30"); 76 | 77 | HttpRequest httpRequest = new HttpRequest(); 78 | httpRequest.get(TwitterApiURLs.FOLLOWERS_URL,param); 79 | ``` 80 | ## Get Friend(Follow user) List 81 | ```java 82 | twitter.getFriendList(); 83 | ``` 84 | ## Custom Get Friend List 85 | ```java 86 | TreeMap param = new TreeMap<>(); 87 | param.put("cursor","-1"); 88 | // Below is optional params 89 | param.put("screen_name","twitter's @id"); 90 | param.put("count","30"); 91 | 92 | HttpRequest httpRequest = new HttpRequest(); 93 | httpRequest.get(TwitterApiURLs.FRIENDS_URL,param); 94 | ``` 95 | ## Twitter time line Json decode(this is optional mini function) 96 | ```java 97 | String json = twitter.getHomeTimeLine(50); 98 | JsonDecoder.decodeTimeLine(json); 99 | ``` 100 | # Implemented urls 101 | 102 | ```` 103 | POST /1.1/statuses/update.json 104 | POST /1.1/statuses/destroy/:id.json 105 | GET /1.1/statuses/user_timeline.json 106 | GET /1.1/statuses/home_timeline.json 107 | GET /1.1/search/tweets.json 108 | GET /1.1/users/show.json 109 | GET /1.1/followers/list.json 110 | GET /1.1/friend/list.json 111 | ```` 112 | # Contributing 113 | I welcome it. But if you pullrequest to this repository,you should write description of pullrequest content in English. 114 | # LICENCE 115 | ``` 116 | MIT License 117 | 118 | Copyright (c) [2017] ItinoseSan 119 | 120 | Permission is hereby granted, free of charge, to any person obtaining a copy 121 | of this software and associated documentation files (the "Software"), to deal 122 | in the Software without restriction, including without limitation the rights 123 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 124 | copies of the Software, and to permit persons to whom the Software is 125 | furnished to do so, subject to the following conditions: 126 | 127 | The above copyright notice and this permission notice shall be included in all 128 | copies or substantial portions of the Software. 129 | 130 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 131 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 132 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 133 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 134 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 135 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 136 | SOFTWARE. 137 | ``` 138 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | --------------------------------------------------------------------------------