List of usage examples for twitter4j TwitterFactory getSingleton
public static Twitter getSingleton()
From source file:br.unisal.twitter.bean.TwitterBean.java
public void postingToTwitter() { try {/*from w ww. ja va2 s . c o m*/ TwitterFactory TwitterFactory = new TwitterFactory(); Twitter twitter = TwitterFactory.getSingleton(); String message = getTwitt(); Status status = twitter.updateStatus(message); /*String s = "status.toString() = " + status.toString() + "status.getInReplyToScreenName() = " + status.getInReplyToScreenName() + "status.getSource() = " + status.getSource() + "status.getText() = " + status.getText() + "status.getContributors() = " + Arrays.toString(status.getContributors()) + "status.getCreatedAt() = " + status.getCreatedAt() + "status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId() + "status.getGeoLocation() = " + status.getGeoLocation() + "status.getId() = " + status.getId() + "status.getInReplyToStatusId() = " + status.getInReplyToStatusId() + "status.getInReplyToUserId() = " + status.getInReplyToUserId() + "status.getPlace() = " + status.getPlace() + "status.getRetweetCount() = " + status.getRetweetCount() + "status.getRetweetedStatus() = " + status.getRetweetedStatus() + "status.getUser() = " + status.getUser() + "status.getAccessLevel() = " + status.getAccessLevel() + "status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()) + "status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()) + "status.getURLEntities() = " + Arrays.toString(status.getURLEntities()) + "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities());*/ String s = "status.getId() = " + status.getId() + "\nstatus.getUser() = " + status.getUser().getName() + " - " + status.getUser().getScreenName() + "\nstatus.getGeoLocation() = " + status.getGeoLocation() + "\nstatus.getText() = " + status.getText(); setTwittsResult(s); this.getUiMsg().setSubmittedValue(""); this.getUiResultMsg().setSubmittedValue(getTwittsResult()); } catch (TwitterException ex) { LOG.error("Erro no postingToTwitter() - " + ex.toString()); } }
From source file:br.unisal.twitter.bean.TwitterBean.java
public void consultarTweets() { TwitterFactory TwitterFactory = new TwitterFactory(); Twitter twitter = TwitterFactory.getSingleton(); List<Status> tweets = new ArrayList<>(); Query query = new Query(getTwittQuery()); try {//from ww w . jav a 2s . c o m QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); StringBuilder builder = new StringBuilder(); double lon = 0; double lat = 0; for (Status s : tweets) { if ((s.getGeoLocation() != null)) { lon = s.getGeoLocation().getLongitude(); lat = s.getGeoLocation().getLatitude(); } Tweet t = new Tweet(s.getUser().getName(), s.getUser().getLocation(), s.getText(), s.getCreatedAt(), lat, lon); dao.insert(t); builder.append(t.toString()); } this.getUiResultQuery().setSubmittedValue(builder.toString()); } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); } }
From source file:ColourUs.OAuth.java
private void reauthorize() throws Exception { // In case we lose the A_SECRET Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(C_KEY, C_SECRET); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//from w w w . j av a 2s . c o m BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } show((int) twitter.verifyCredentials().getId(), accessToken); }
From source file:com.appdynamics.alerts.twitter.TwitterAlert.java
License:Apache License
public static void main(String[] args) { twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); twitter.addRateLimitStatusListener(new RateLimitStatusListener() { @Override/*from ww w .ja va2s .c o m*/ public void onRateLimitStatus(RateLimitStatusEvent rateLimitStatusEvent) { RateLimitStatus status = rateLimitStatusEvent.getRateLimitStatus(); if (status.getRemaining() <= 0) { logger.warn("Rate limit reached"); storeRateLimitStatus(status); } } @Override public void onRateLimitReached(RateLimitStatusEvent rateLimitStatusEvent) { //never called by API } }); if (args.length == 1 && args[0].equals("auth")) { try { getAuthorization(); System.out.println("Authenticated for user @" + twitter.getScreenName()); } catch (TwitterException e) { if (e.getStatusCode() == 401) { logger.error("Missing or incorrect authentication credentials"); } else { logger.error("Authentication failed", e); } } } else { try { parseEventParams(args); AccessToken accessToken = readAccessToken(); twitter.setOAuthAccessToken(accessToken); postUpdate(); } catch (IOException e) { logger.error("Access token unreadable,unable to authenticate. Please rerun authentication script"); } catch (ClassNotFoundException e) { logger.error("Access token unreadable,unable to authenticate. Please rerun authentication script"); } catch (Exception e) { logger.error("Failed to parse arguments"); } } }
From source file:com.gmail.altakey.joanne.service.TwitterAuthService.java
License:Apache License
@Override public void onHandleIntent(Intent data) { final Twitter tw = TwitterFactory.getSingleton(); try {/* www . j av a 2 s. c o m*/ tw.setOAuthConsumer(getString(R.string.consumer_key), getString(R.string.consumer_secret)); } catch (IllegalStateException e) { } final String action = data.getAction(); if (ACTION_AUTH.equals(action)) { authenticate(tw); } else if (ACTION_AUTH_VERIFY.equals(action)) { final String verifier = data.getStringExtra(EXTRA_VERIFIER); authenticateDone(tw, verifier); } stopSelf(); }
From source file:com.gmail.altakey.joanne.service.TwitterAuthService.java
License:Apache License
public static void updateRelations(final Context context, final AccessToken token) { final SharedPreferences prefs = context.getSharedPreferences(PREFERENCE, MODE_PRIVATE); try {//from w w w . j a v a2s . co m final Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthAccessToken(token); final Set<Long> friends = new HashSet<Long>(); for (IDs ids = twitter.getFriendsIDs(-1);; ids = twitter.getFriendsIDs(ids.getNextCursor())) { for (Long id : ids.getIDs()) { friends.add(id); } if (!ids.hasNext()) { break; } } final Set<Long> followers = new HashSet<Long>(); for (IDs ids = twitter.getFollowersIDs(-1);; ids = twitter.getFollowersIDs(ids.getNextCursor())) { for (Long id : ids.getIDs()) { followers.add(id); } if (!ids.hasNext()) { break; } } prefs.edit().putString(KEY_FRIENDS, new IdListCoder().encode(friends)) .putString(KEY_FOLLOWERS, new IdListCoder().encode(followers)).commit(); UserRelation.notifyRelationsChanged(); Log.d(TAG, String.format("got %d friends", friends.size())); Log.d(TAG, String.format("got %d followers", followers.size())); } catch (TwitterException e) { Log.w(TAG, "cannot get follower list", e); } }
From source file:com.ibm.TwitterAsyncService.java
License:Open Source License
@Override public void run() { String bookTitle = ac.getRequest().getParameter("title"); String bookAuthor = ac.getRequest().getParameter("author"); boolean translate = Boolean.parseBoolean(ac.getRequest().getParameter("enable")); logger.debug("Requested book title {} and author {}", bookTitle, bookAuthor); Query query = new Query(bookTitle + " " + bookAuthor); query.setResultType(Query.RECENT); Twitter twitter = TwitterFactory.getSingleton(); try {/*w ww .j av a 2 s . c om*/ PrintWriter writer = ac.getResponse().getWriter(); Locale locale = ac.getRequest().getLocale(); WatsonTranslate watson = new WatsonTranslate(locale); // Just get the first page of results to avoid exceeding the Twitter rate limit QueryResult result = twitter.search(query); Alchemy alchemy = new Alchemy(); List<Status> tweets = result.getTweets(); logger.debug("Current tweets {}", tweets.toString()); for (Status tweetMessage : tweets) { JSONObject json = new JSONObject(); JSONObject tweet = new JSONObject(); // We need to put the tweet and link into an inner object // so that we can use a special formatter in bootstrap table json.put("screenName", tweetMessage.getUser().getScreenName()); if (translate) { String message = watson.translate(tweetMessage.getText()); tweet.put("message", message); json.put("sentiment", alchemy.getSentiment(message)); } else { tweet.put("message", tweetMessage.getText()); json.put("sentiment", alchemy.getSentiment(tweetMessage.getText())); } String url = "https://twitter.com/" + tweetMessage.getUser().getScreenName() + "/status/" + tweetMessage.getId(); tweet.put("link", url); json.put("tweet", tweet); writer.write(("data: " + json.toString() + "\n\n")); writer.flush(); } writer.write(("event: finished\n")); writer.write(("data: \n\n")); writer.flush(); writer.close(); } catch (TwitterException e) { logger.error("Twitter Error {}", e.getMessage()); } catch (IOException e) { logger.error("could not write SSE {}", e.getMessage()); } catch (NullPointerException e) { logger.error("Exception Twitter Async Service {}", e.getMessage()); } finally { ac.complete(); } }
From source file:com.joanzapata.android.twitter.service.TwitterService.java
License:Apache License
public TwitterService() { twitter = TwitterFactory.getSingleton(); }
From source file:com.mastfrog.acteur.twitter.TwitterSign.java
@SuppressWarnings("unchecked") RemoteUserInfo zgetUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential, AuthorizationResponse auth)/*from w ww .ja v a 2 s . c o m*/ throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException { System.setProperty("twitter4j.http.useSSL", "false"); Twitter twitter = TwitterFactory.getSingleton(); try { // Idiotic - shutdown does not clear state twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); } catch (Exception e) { e.printStackTrace(); } twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret)); OAuthAuthorization a = new OAuthAuthorization(twitter.getConfiguration()); a.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); URL url = URL.builder(Protocols.HTTPS) // URL url = URL.builder(Protocols.HTTP) // XXX NOT UNENCRYPTED! JUST FOR DEBUGING .setHost(Host.parse("api.twitter.com")).setPath("1.1/account/verify_credentials.json").create(); String hdr = new SigBuilder().add(oauth_token, auth.accessToken).add(OAuthHeaders.oauth_nonce, oauth_nonce) .toHeader(Method.GET, url.getPathAndQuery(), auth); // XXX encode URL? String franken = a.xgenerateAuthorizationHeader(oauth_nonce, "GET", "/1.1/account/verify_credentials.json", new HttpParameter[0], new twitter4j.auth.AccessToken(auth.accessToken, auth.accessTokenSecret)); OAuthAuthorization oa = new OAuthAuthorization(twitter.getConfiguration()); oa.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); oa.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret)); twitter4j.internal.http.HttpRequest r = new twitter4j.internal.http.HttpRequest(RequestMethod.GET, "https://api.twitter.com/twitter4j.internal.http.HttpRequest", new HttpParameter[0], oa, Collections.<String, String>emptyMap()); ResponseLatch latch = new ResponseLatch(); RH rh = new RH(); client.get().setURL(url).addHeader(Headers.stringHeader("Authorization"), hdr) .addHeader(Headers.stringHeader("X-Twitter-Client-URL"), "http://twitter4j.org/en/twitter4j-3.0.4-SNAPSHOT.xml") .addHeader(Headers.stringHeader("X-Twitter-Client"), "Twitter4J") .addHeader(Headers.stringHeader("Accept-Encoding"), "gzip") .addHeader(Headers.stringHeader("X-Twitter-Client-Version"), "3.0.4-SNAPSHOT") .addHeader(Headers.stringHeader("Accept"), "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2") // .addHeader(Headers.stringHeader("Accept"), "*/*") // .addHeader(Headers.stringHeader("Connection"), "keep-alive") .noDateHeader() // .noConnectionHeader() // .addHeader(Headers.stringHeader("Content-Type"), "application/x-www-form-urlencoded") // .setBody("screen_name=kablosna", MediaType.PLAIN_TEXT_UTF_8) .on(StateType.Closed, latch).on(StateType.Timeout, latch).execute(rh); rh.await(1, TimeUnit.MINUTES); latch.latch.await(1, TimeUnit.MINUTES); String responseBody = rh.getResponse(); RUI rui = new RUI(); if (responseBody == null) { // System.out.println("NULL RESPONSE BODY."); throw new IOException(rh.toString()); } rui.putAll(new ObjectMapper().readValue(responseBody, Map.class)); return rui; }
From source file:com.mastfrog.acteur.twitter.TwitterSign.java
RemoteUserInfo getUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential, AuthorizationResponse auth)//from w ww. j a v a2 s . c om throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException { // System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.StdOutLogger"); System.setProperty("twitter4j.debug", "true"); System.setProperty("twitter4j.http.useSSL", "false"); Twitter twitter = TwitterFactory.getSingleton(); try { // Idiotic twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); } catch (Exception e) { e.printStackTrace(); } twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret)); try { User user = twitter.verifyCredentials(); RUI rui = new RUI(); rui.put("displayName", user.getName()); rui.put("name", user.getScreenName() + "@api.twitter.com"); rui.put("screen_name", user.getScreenName()); rui.put("picture", user.getProfileImageURLHttps()); rui.put("pictureLarge", user.getBiggerProfileImageURLHttps()); rui.put("id", user.getId()); return rui; } catch (TwitterException ex) { throw new IOException(ex); } finally { twitter.shutdown(); } }