/** * It returns MAX(available_tweets,200,limit) tweets from the search of the specified query. In * case of error, returns null. */ public QueryResult searchTweets(String queryTerm, int limit) { try { Query query = new Query(queryTerm); query.setCount(limit); QueryResult result = twitter.search(query); LoggerClass.log( Level.INFO, "OK. Searching tweets for term " + queryTerm + " and limit " + limit + ". " + result.getCount() + " results."); return result; } catch (Exception ex) { LoggerClass.log( Level.SEVERE, "ERROR searching tweets for term " + queryTerm + " and limit " + limit + "."); System.err.println("[ERROR] Can't search tweets"); ex.printStackTrace(); return null; } }
/** {@inheritDoc} */ @Override public void updateStory( String message, String name, String caption, String description, String link, String picture, final SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "updateStory"); RefProvider = getProvider(); RefSocialActionListener = socialActionListener; preformingAction = ACTION_PUBLISH_STORY; try { twitter.updateStatus(message + " " + link); } catch (Exception e) { failListener(ACTION_PUBLISH_STORY, e.getMessage()); } }
public void onDisable() { try { if (connection != null && !connection.isClosed()) { connection.close(); } } catch (Exception e) { // e.printStackTrace(); this.getLogger().warning("Couldn't close MySQL Connection: " + e.getMessage() + "\n"); } }
/* * Favorites the specified tweet, returning true in case of success. * If error, returns false. */ public boolean doFav(Status tweet) { try { twitter.createFavorite(tweet.getId()); return true; } catch (Exception ex) { System.err.println("[ERROR] Can't favorite " + tweet.getId()); ex.printStackTrace(); return false; } }
/* * Follows the specified user, returning true in case of success. * If error, returns false. */ public boolean doFollow(long user) { try { twitter.friendsFollowers().createFriendship(user); return true; } catch (Exception ex) { System.err.println("[ERROR] Can't follow " + user); ex.printStackTrace(); return false; } }
/* * Re-tweets the specified tweet, returning true in case of success. * If error, returns false. */ public boolean doRT(Status tweet) { try { twitter.retweetStatus(tweet.getId()); return true; } catch (Exception ex) { System.err.println("[ERROR] Can't retweet " + tweet.getId()); ex.printStackTrace(); return false; } }
/** * Returns a list of id of the users the configured account follows. Returns null in case of * error. */ public ArrayList<Long> getFollowing() { ArrayList<Long> following = new ArrayList<Long>(); try { long lCursor = -1; IDs friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor); do { for (long i : friendsIDs.getIDs()) { following.add(i); } } while (friendsIDs.hasNext()); return following; } catch (Exception ex) { System.err.println("[ERROR] Can't get following users."); ex.printStackTrace(); return null; } }
/** {@inheritDoc} */ @Override public void getUserProfile(final AuthCallbacks.UserProfileListener userProfileListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getUserProfile"); RefProvider = getProvider(); RefUserProfileListener = userProfileListener; preformingAction = ACTION_GET_USER_PROFILE; try { twitter.showUser(twitterScreenName); } catch (Exception e) { failListener(ACTION_GET_USER_PROFILE, e.getMessage()); } }
// loadArray Method loads a file into an array and returns the array ArrayList<String> loadArray(String thefile) { // System.out.println("Load array"); ArrayList<String> myarray = new ArrayList<String>(); try { BufferedReader an = new BufferedReader(new FileReader(thefile)); String line; while ((line = an.readLine()) != null) { myarray.add(line); } an.close(); } catch (Exception e) { e.printStackTrace(); } ; return myarray; }
/** {@inheritDoc} */ @Override public void updateStatus( String status, final SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "updateStatus"); RefProvider = getProvider(); RefSocialActionListener = socialActionListener; preformingAction = ACTION_PUBLISH_STATUS; try { twitter.updateStatus(status); } catch (Exception e) { failListener(ACTION_PUBLISH_STATUS, e.getMessage()); } }
/** {@inheritDoc} */ @Override public void getContacts( boolean fromStart, final SocialCallbacks.ContactsListener contactsListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getContacts"); RefProvider = getProvider(); RefContactsListener = contactsListener; preformingAction = ACTION_GET_USER_PROFILE; try { twitter.getFriendsList(twitterScreenName, fromStart ? -1 : this.lastContactCursor); this.lastContactCursor = -1; } catch (Exception e) { failListener(ACTION_GET_USER_PROFILE, e.getMessage()); } }
/** {@inheritDoc} */ @Override public void uploadImage( String message, String filePath, final SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "uploadImage"); RefProvider = getProvider(); RefSocialActionListener = socialActionListener; preformingAction = ACTION_UPLOAD_IMAGE; try { StatusUpdate updateImage = new StatusUpdate(message); updateImage.media(new File(filePath)); twitter.updateStatus(updateImage); } catch (Exception e) { failListener(ACTION_UPLOAD_IMAGE, e.getMessage()); } }
/** {@inheritDoc} */ @Override public void getFeed(Boolean fromStart, final SocialCallbacks.FeedListener feedListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getFeed"); RefProvider = getProvider(); RefFeedListener = feedListener; preformingAction = ACTION_GET_FEED; try { if (fromStart) { this.lastFeedCursor = 1; } Paging paging = new Paging(this.lastFeedCursor, PAGE_SIZE); twitter.getUserTimeline(paging); } catch (Exception e) { failListener(ACTION_GET_FEED, e.getMessage()); } }
public static void main(String[] args) { try { meet myobj = new meet(); // load jsiconfig.txt ArrayList<String> myconfiglist = new ArrayList<String>(); myconfiglist = myobj.loadArray("jsiconfig.txt"); // The text uri // "mongodb://*****:*****@ds023288.mongolab.com:23288/sample"; String textUri = myconfiglist.get(0); // Create MongoClientURI object from which you get MongoClient obj MongoClientURI uri = new MongoClientURI(textUri); // Connect to that uri MongoClient m = new MongoClient(uri); // get the database named sample String DBname = myconfiglist.get(1); DB d = m.getDB(DBname); // get the collection mycollection in sample String collectionName = myconfiglist.get(2); DBCollection collection = d.getCollection(collectionName); // System.out.println("Config: "+textUri+":"+DBname+":"+collectionName); // twitter4j // Twitter twitter = new TwitterFactory().getInstance(); Twitter twitter = new TwitterFactory().getSingleton(); User user = twitter.verifyCredentials(); // Twitter collection of latest tweets into the home account - defaulted to latest 20 tweets// ////////////////////////////////////////////////////////////// ArrayList<String> mylatesttweetslist = new ArrayList<String>(); // get list of tweets from a user or the next tweet listed try { long actid = 0; // twitter.createFriendship(actid); // The factory instance is re-useable and thread safe. // Twitter twitter = TwitterFactory.getSingleton(); List<Status> statuses = twitter.getHomeTimeline(); System.out.println("Showing home timeline."); for (Status status : statuses) { // System.out.println(status.getUser().getName() + ":" +status.getText()); // Addes timeline to an array String mytweets = status.getUser().getName() + ":" + status.getText(); mylatesttweetslist.add(mytweets); } ; } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } // MongoDB Insert Below // ////////////////////////// // System Date Date sd = new Date(); String sysdate = sd.toString(); // Toggle the below to display and insert the transactions as required boolean showtrans = true; boolean inserttrans = true; // checkArray - loads args to a text string to allow the contains function String checkString = ""; for (int ck = 0; ck < args.length; ck++) { checkString = checkString + args[ck]; } ; // display transactions flag on runnning jsimongo eg: java jsimongo -d will NOT display // transactions // insert transactions flag on runnning jsimongo eg: java jsimongo -i will NOT insert // transactions if (args.length > 0) { if (checkString.contains("-d")) showtrans = false; if (checkString.contains("-i")) inserttrans = false; } ; int x = 0; for (String atweet : mylatesttweetslist) { x++; // Display tweets to console if (showtrans == true) { System.out.println("tweet : " + atweet); System.out.println("Created_DateTime : " + sysdate); // was sysdate } ; // Insert JSON into MongoDB if (inserttrans == true) { BasicDBObject b = new BasicDBObject(); System.out.println("tweet : " + atweet); System.out.println("Created_DateTime : " + sysdate); // was sysdate // Insert the JSON object into the chosen collection collection.insert(b); } ; Thread.sleep(1); } ; System.out.println("End, the number of tweets inserted at this time was: " + x); } catch (Exception e) { e.printStackTrace(); } }
public List<Tweet> readFile(String fileLocation, int limit, String fromTweetId) { long startTime = System.currentTimeMillis(); int errors = 0; int added = 0; int ignored = 0; int skipped = 0; List<Tweet> tweets = new ArrayList<Tweet>(); try { // Read gzFile InputStream inputStream = new GZIPInputStream(new FileInputStream(fileLocation)); Reader decoder = new InputStreamReader(inputStream); BufferedReader br = new BufferedReader(decoder); String status; while ((status = br.readLine()) != null) { // Ignore garbage and log output lines, all statuses start with JSON bracket if (!status.equals("") && status.charAt(0) == '{') { try { JSONObject jsonObject = new JSONObject(status); // We use created_at as an indicator that this is a Tweet. if (jsonObject.has("created_at")) { Status statusObject = TwitterObjectFactory.createStatus(status); Tweet tweet = this.getTweetObjectFromStatus(statusObject); if (fromTweetId != null) { if (fromTweetId.equals(tweet.getId())) { this.log.write("StatusFileReader - Scanner pickup from " + fromTweetId); fromTweetId = null; } else { skipped++; } continue; } added++; tweets.add(tweet); if (limit > 0 && added >= limit) { break; } } else { ignored++; } } catch (JSONException e) { this.log.write( "Exception in StatusFileReader: Json Parse Failure on: " + status + ", " + e.getMessage()); } } else { ignored++; } } br.close(); decoder.close(); inputStream.close(); } catch (Exception e) { this.log.write( "Exception in StatusFileReader: Error Reading File: " + e.getClass().getName() + ": " + e.getMessage()); } long runTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); double ops = ((double) added / (double) Math.max(runTimeSeconds, 1)); this.log.write( "StatusFileReader - " + fileLocation + " processed in " + runTimeSeconds + "s. " + added + " ok / " + errors + " errors / " + ignored + " ignored / " + skipped + " skipped. " + ops + " ops. Limit: " + limit + ", Fetch: " + tweets.size()); return tweets; }
public void dumpError(Exception exc) { exc.printStackTrace(System.err); }