Twitter unauthenticatedTwitter = new TwitterFactory().getInstance(); //First param of Paging() is the page number, second is the number per page (this is capped around 200 I think. Paging paging = new Paging(1, 100); List<Status> statuses = unauthenticatedTwitter.getUserTimeline("google",paging);
/** * To upload a picture with some piece of text. * * * @param file The file which we want to share with our tweet * @param message Message to display with picture * @param twitter Instance of authorized Twitter class * @throws Exception exception if any */ public void uploadPic(File file, String message,Twitter twitter) throws Exception { try{ StatusUpdate status = new StatusUpdate(message); status.setMedia(file); twitter.updateStatus(status);} catch(TwitterException e){ Log.d("TAG", "Pic Upload error" + e.getErrorMessage()); throw e; } }
Predicate<User> isAuthorized = new Predicate<User>() { public boolean apply(User user) { // binds a boolean method in User to a reference return user.isAuthorized(); } }; // allUsers is a Collection<User> Collection<User> authorizedUsers = filter(allUsers, isAuthorized);
static Twitter getInstance( AppCredentials appCredentials, TokenSecretAuthData authData) { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(false) .setOAuthConsumerKey(appCredentials.getKey()) .setOAuthConsumerSecret(appCredentials.getSecret()) // TODO: I think the token/secret expire, we need to check into refreshing them .setOAuthAccessToken(authData.getToken()) .setOAuthAccessTokenSecret(authData.getSecret()); TwitterFactory tf = new TwitterFactory(cb.build()); return tf.getInstance(); } }
private Record extractRecord(String idPrefix, Schema avroSchema, Status status) { User user = status.getUser(); Record doc = new Record(avroSchema); doc.put("id", idPrefix + status.getId()); doc.put("created_at", formatterTo.format(status.getCreatedAt())); doc.put("retweet_count", status.getRetweetCount()); doc.put("retweeted", status.isRetweet()); doc.put("in_reply_to_user_id", status.getInReplyToUserId()); doc.put("in_reply_to_status_id", status.getInReplyToStatusId()); addString(doc, "source", status.getSource()); addString(doc, "text", status.getText()); MediaEntity[] mediaEntities = status.getMediaEntities(); if (mediaEntities.length > 0) { addString(doc, "media_url_https", mediaEntities[0].getMediaURLHttps()); addString(doc, "expanded_url", mediaEntities[0].getExpandedURL()); } doc.put("user_friends_count", user.getFriendsCount()); doc.put("user_statuses_count", user.getStatusesCount()); doc.put("user_followers_count", user.getFollowersCount()); addString(doc, "user_location", user.getLocation()); addString(doc, "user_description", user.getDescription()); addString(doc, "user_screen_name", user.getScreenName()); addString(doc, "user_name", user.getName()); return doc; }
private static TwitterFactory getUserTwitterFactory(String accessToken, String accessTokenSecret) { if (accessToken == null || accessToken.length() == 0 || accessTokenSecret == null || accessTokenSecret.length() == 0) return null; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(DAO.getConfig("client.twitterConsumerKey", "")) .setOAuthConsumerSecret(DAO.getConfig("client.twitterConsumerSecret", "")) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); cb.setJSONStoreEnabled(true); return new TwitterFactory(cb.build()); }
@Override public void configure(Context context) { String consumerKey = context.getString("consumerKey"); String consumerSecret = context.getString("consumerSecret"); String accessToken = context.getString("accessToken"); String accessTokenSecret = context.getString("accessTokenSecret"); twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.setOAuthConsumer(consumerKey, consumerSecret); twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); twitterStream.addListener(this); avroSchema = createAvroSchema(); dataFileWriter = new DataFileWriter<GenericRecord>( new GenericDatumWriter<GenericRecord>(avroSchema)); maxBatchSize = context.getInteger("maxBatchSize", maxBatchSize); maxBatchDurationMillis = context.getInteger("maxBatchDurationMillis", maxBatchDurationMillis); }
public static JSONObject getUser(String screen_name, boolean forceReload) throws TwitterException, IOException { if (!forceReload) { JsonFactory mapcapsule = DAO.user_dump.get("screen_name",screen_name); if (mapcapsule == null) mapcapsule = DAO.user_dump.get("id_str", screen_name); if (mapcapsule != null) { JSONObject json = mapcapsule.getJSON(); if (json.length() > 0) { // check if the entry is maybe outdated, i.e. if it is empty or too old try { Date d = DAO.user_dump.parseDate(json); if (d.getTime() + DateParser.DAY_MILLIS > System.currentTimeMillis()) return json; } catch (ParseException e) { return json; } } } } TwitterFactory tf = getUserTwitterFactory(screen_name); if (tf == null) tf = getAppTwitterFactory(); if (tf == null) return new JSONObject(); Twitter twitter = tf.getInstance(); User user = twitter.showUser(screen_name); RateLimitStatus rateLimitStatus = user.getRateLimitStatus(); getUserResetTime = System.currentTimeMillis() + rateLimitStatus.getSecondsUntilReset() * 1000; getUserRemaining = rateLimitStatus.getRemaining(); JSONObject json = user2json(user); enrichLocation(json); DAO.user_dump.putUnique(json); return json; }
@Override public void close() { log.info("CLOSE twitterstream"); twitterStream.shutdown(); // invokes twitterStream.cleanUp() } };
public static RateLimitStatus getRateLimitStatus(final String rate_type) throws TwitterException { return getAppTwitterFactory().getInstance().getRateLimitStatus().get(rate_type); }
public KaizenHarvester(KaizenQueries queries) { BACKEND = DAO.getBackend(); SUGGESTIONS_COUNT = DAO.getConfig("harvester.kaizen.suggestions_count", 1000); SUGGESTIONS_RANDOM = DAO.getConfig("harvester.kaizen.suggestions_random", 5); PLACE_RADIUS = DAO.getConfig("harvester.kaizen.place_radius", 5); VERBOSE = DAO.getConfig("harvester.kaizen.verbose", true); random = new Random(); this.queries = queries; TwitterFactory twitterFactory = TwitterAPI.getAppTwitterFactory(); if (twitterFactory != null) twitter = twitterFactory.getInstance(); if (twitter == null) DAO.log("Kaizen can utilize Twitter API to get more queries, If you want to use it, " + "Please add Application and Access tokens (twitterAccessToken, twitterAccessTokenSecret, " + "client.twitterConsumerKey, client.twitterConsumerSecret)"); }
private void grabTrending() { try { if (VERBOSE) { DAO.log("Kaizen is going to get trending topics ..."); } for (Location location : twitter.trends().getAvailableTrends()) { for (Trend trend : twitter.trends().getPlaceTrends(location.getWoeid()).getTrends()) { this.queries.addQuery(trend.getQuery()); } } } catch (TwitterException e) { if (e.getErrorCode() != 88) { DAO.severe(e); } } }
@Override public ImportResult importItem( UUID jobId, TokenSecretAuthData authData, PhotosContainerResource data) { Twitter twitterApi = TwitterApiWrapper.getInstance(appCredentials, authData); // Twitter doesn't support an 'Albums' concept, so that information is just lost. for (PhotoModel image : data.getPhotos()) { try { StatusUpdate update = new StatusUpdate(image.getDescription()); InputStreamContent content = new InputStreamContent(null, getImageAsStream(image.getFetchableUrl())); update.media(image.getTitle(), content.getInputStream()); twitterApi.tweets().updateStatus(update); } catch (IOException | TwitterException e) { monitor.severe(() -> "Error importing twitter photo", e); return new ImportResult(e); } } return new ImportResult(ResultType.OK); }
this.context().parent().tell(new StatusUpdate(i)); long j = 1;
public static JSONObject user2json(User user) throws IOException { String jsonstring = TwitterObjectFactory.getRawJSON(user); JSONObject json = new JSONObject(jsonstring); json.put("retrieval_date", AbstractObjectEntry.utcFormatter.print(System.currentTimeMillis())); Object status = json.remove("status"); // we don't need to store the latest status update in the user dump // TODO: store the latest status in our message database return json; }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PLACE_PICKER_REQUEST) { if (resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(data, this); String toastMsg = String.format("Place: %s", place.getName()); Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show(); } } }
Map<String, List<User>> usersByCountry = new HashMap<>(); for (User user : listOfUsers) { usersByCountry.computeIfAbsent(user.getCountry(), v -> new ArrayList<>()).add(user); }
@Controller @SessionAttributes({"user"}) public class InspectionTypeController { @RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST ) public void addInspectionType(InspectionType inspectionType, @ModelAttribute User user) { System.out.println("User: "+ user.getUserDetails().getFirstName); } }
@Override public synchronized void stop() { LOGGER.info("Twitter source {} stopping...", getName()); twitterStream.shutdown(); super.stop(); LOGGER.info("Twitter source {} stopped.", getName()); }
Map<String, List<User>> usersByCountry = new HashMap<>(); for (User user : listOfUsers) { List<User> users = usersByCountry.get(user.getCountry()); if (users == null) { users = new ArrayList<>(); usersByCountry.put(user.getCountry(), users); } users.add(user); }