List of usage examples for twitter4j Status getText
String getText();
From source file:com.amandine.twitterpostforcoucou.Tweet.java
private void publishStatusUpdateWithMedia(String message) throws MalformedURLException, IOException { Status status = null; try {//from w w w . j av a 2 s . c o m Twitter twitter = new TwitterFactory().getInstance(); try { RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; while (null == accessToken) { logger.fine("Open the following URL and grant access to your account:"); logger.fine(requestToken.getAuthorizationURL()); try { accessToken = twitter.getOAuthAccessToken(requestToken); } catch (TwitterException te) { if (401 == te.getStatusCode()) { logger.severe("Unable to get the access token."); } else { te.printStackTrace(); } } } logger.log(Level.INFO, "Got access token."); logger.log(Level.INFO, "Access token: {0}", accessToken.getToken()); logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { logger.severe("OAuth consumer key/secret is not set."); return; } } //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate(message); //attach any media, if you want to statusUpdate.setMedia( //title of media "Amandine Leforestier Spring Summer 2015 white", new URL("https://issuu.com/kadiemurphy/docs/volume_xxi_issuu/52?e=0").openStream()); //tweet or update status status = twitter.updateStatus(statusUpdate); //Status status = twitter.updateStatus(message); logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText()); } catch (TwitterException te) { te.printStackTrace(); logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage()); } }
From source file:com.amandine.twitterpostforcoucou.Tweet.java
public void tweetMessageToUser(String username, String hashtags, String imageUrl, String targetUrl, String twitterid) {//from w w w .ja va2 s. c om Twitter twitterHandle = this.getTwitter(); //Instantiate and initialize a new twitter status update String message = username + " " + targetUrl + " " + hashtags + " #amandineleforestier"; StatusUpdate statusUpdate = new StatusUpdate(message); try { //attach any media, if you want to statusUpdate.setMedia(//title of media "Amandine Leforestier Athleasure Sport-Chic Autumn Winter 2015 http://shop.amandineleforestier.fr", new URL(imageUrl).openStream()); } catch (MalformedURLException ex) { logger.log(Level.SEVERE, "Bad image Url {0}", ex.getMessage()); } catch (IOException ex) { logger.log(Level.SEVERE, "Cannot open Url {0}", ex.getMessage()); } //tweet or update status Status status = null; try { status = twitterHandle.updateStatus(statusUpdate); logTheStatusUpdate(twitterid, message, imageUrl, targetUrl); } catch (TwitterException te) { logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage()); } //Status status = twitter.updateStatus(message); if (status != null) { logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText()); } else { logger.log(Level.SEVERE, "Status update failed [{0}].", status); } }
From source file:com.android.calendar.AllInOneActivity.java
License:Apache License
@Override protected void onCreate(Bundle icicle) { if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) { setTheme(R.style.CalendarTheme_WithActionBarWallpaper); }//from w w w . ja v a 2 s . c o m super.onCreate(icicle); dynamicTheme.onCreate(this); if (icicle != null && icicle.containsKey(BUNDLE_KEY_CHECK_ACCOUNTS)) { mCheckForAccounts = icicle.getBoolean(BUNDLE_KEY_CHECK_ACCOUNTS); } // Launch add google account if this is first time and there are no // accounts yet if (mCheckForAccounts && !Utils.getSharedPreference(this, GeneralPreferences.KEY_SKIP_SETUP, false)) { mHandler = new QueryHandler(this.getContentResolver()); mHandler.startQuery(0, null, Calendars.CONTENT_URI, new String[] { Calendars._ID }, null, null /* selection args */, null /* sort order */); } // This needs to be created before setContentView mController = CalendarController.getInstance(this); // Check and ask for most needed permissions checkAppPermissions(); // Get time from intent or icicle long timeMillis = -1; int viewType = -1; final Intent intent = getIntent(); if (icicle != null) { timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME); viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1); } else { String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { // Open EventInfo later timeMillis = parseViewAction(intent); } if (timeMillis == -1) { timeMillis = Utils.timeFromIntentInMillis(intent); } } if (viewType == -1 || viewType > ViewType.MAX_VALUE) { viewType = Utils.getViewTypeFromIntentAndSharedPref(this); } mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater); Time t = new Time(mTimeZone); t.set(timeMillis); if (DEBUG) { if (icicle != null && intent != null) { Log.d(TAG, "both, icicle:" + icicle.toString() + " intent:" + intent.toString()); } else { Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent); } } Resources res = getResources(); mHideString = res.getString(R.string.hide_controls); mShowString = res.getString(R.string.show_controls); mOrientation = res.getConfiguration().orientation; if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) { mControlsAnimateWidth = (int) res.getDimension(R.dimen.calendar_controls_width); if (mControlsParams == null) { mControlsParams = new LayoutParams(mControlsAnimateWidth, 0); } mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } else { // Make sure width is in between allowed min and max width values mControlsAnimateWidth = Math.max(res.getDisplayMetrics().widthPixels * 45 / 100, (int) res.getDimension(R.dimen.min_portrait_calendar_controls_width)); mControlsAnimateWidth = Math.min(mControlsAnimateWidth, (int) res.getDimension(R.dimen.max_portrait_calendar_controls_width)); } mControlsAnimateHeight = (int) res.getDimension(R.dimen.calendar_controls_height); mHideControls = !Utils.getSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, true); mIsMultipane = Utils.getConfigBool(this, R.bool.multiple_pane_config); mIsTabletConfig = Utils.getConfigBool(this, R.bool.tablet_config); mShowAgendaWithMonth = Utils.getConfigBool(this, R.bool.show_agenda_with_month); mShowCalendarControls = Utils.getConfigBool(this, R.bool.show_calendar_controls); mShowEventDetailsWithAgenda = Utils.getConfigBool(this, R.bool.show_event_details_with_agenda); mShowEventInfoFullScreenAgenda = Utils.getConfigBool(this, R.bool.agenda_show_event_info_full_screen); mShowEventInfoFullScreen = Utils.getConfigBool(this, R.bool.show_event_info_full_screen); mCalendarControlsAnimationTime = res.getInteger(R.integer.calendar_controls_animation_time); Utils.setAllowWeekForDetailView(mIsMultipane); // setContentView must be called before configureActionBar setContentView(R.layout.all_in_one_material); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavigationView = (NavigationView) findViewById(R.id.navigation_view); mFab = (FloatingActionButton) findViewById(R.id.floating_action_button); if (mIsTabletConfig) { mDateRange = (TextView) findViewById(R.id.date_bar); mWeekTextView = (TextView) findViewById(R.id.week_num); } else { mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null); } setupToolbar(viewType); setupNavDrawer(); setupFloatingActionButton(); mHomeTime = (TextView) findViewById(R.id.home_time); mMiniMonth = findViewById(R.id.mini_month); if (mIsTabletConfig && mOrientation == Configuration.ORIENTATION_PORTRAIT) { mMiniMonth.setLayoutParams( new RelativeLayout.LayoutParams(mControlsAnimateWidth, mControlsAnimateHeight)); } mCalendarsList = findViewById(R.id.calendar_list); mMiniMonthContainer = findViewById(R.id.mini_month_container); mSecondaryPane = findViewById(R.id.secondary_pane); // Must register as the first activity because this activity can modify // the list of event handlers in it's handle method. This affects who // the rest of the handlers the controller dispatches to are. mController.registerFirstEventHandler(HANDLER_KEY, this); initFragments(timeMillis, viewType, icicle); // Listen for changes that would require this to be refreshed SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener(this); mContentResolver = getContentResolver(); //set layout background AnimationDrawable animation = new AnimationDrawable(); animation.addFrame(getResources().getDrawable(R.mipmap.namo1), 5000); animation.addFrame(getResources().getDrawable(R.mipmap.namo2), 10000); animation.addFrame(getResources().getDrawable(R.mipmap.namo3), 15000); animation.addFrame(getResources().getDrawable(R.mipmap.namo4), 20000); animation.addFrame(getResources().getDrawable(R.mipmap.namo7), 25000); animation.addFrame(getResources().getDrawable(R.mipmap.namo8), 30000); animation.addFrame(getResources().getDrawable(R.mipmap.namo9), 35000); animation.addFrame(getResources().getDrawable(R.mipmap.namo10), 40000); animation.addFrame(getResources().getDrawable(R.mipmap.namo11), 45000); animation.addFrame(getResources().getDrawable(R.mipmap.namo12), 50000); animation.addFrame(getResources().getDrawable(R.mipmap.namo13), 55000); animation.addFrame(getResources().getDrawable(R.mipmap.namo14), 60000); animation.addFrame(getResources().getDrawable(R.mipmap.namo15), 65000); animation.addFrame(getResources().getDrawable(R.mipmap.namo16), 70000); animation.addFrame(getResources().getDrawable(R.mipmap.namo17), 75000); animation.addFrame(getResources().getDrawable(R.mipmap.namo18), 80000); animation.addFrame(getResources().getDrawable(R.mipmap.namo19), 85000); animation.addFrame(getResources().getDrawable(R.mipmap.namo20), 90000); animation.setOneShot(false); mDrawerLayout.setBackground(animation); animation.start(); //sharedpreference for get n save tweet tvSlogan = (TextView) findViewById(R.id.modi_Slogan); list = new ArrayList<>(); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = sharedpreferences.edit(); final Set<String> set = new HashSet<String>(); new Thread(new Runnable() { @Override public void run() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("IXJTMZRCoCPs0pnZfODmpvCem") .setOAuthConsumerSecret("ReF3xJiSdFcePKeFv2or5JFDxERnkgKBjEl1u9tc6zgsmmgvl7") .setOAuthAccessToken("580688604-FsMXIhAgOVLuMvpieiwTFLHAerMvUXmdvvq6Zsal") .setOAuthAccessTokenSecret("93IEkCWSikYPQw6RsjifUu70COSOJumHQyXTFUyhKh1XJ"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { List<Status> statuses; String user; user = "@narendramodi"; statuses = twitter.getUserTimeline(user); Log.i("Status Count", statuses.size() + " Feeds"); for (int i = 0; i < statuses.size(); i++) { Status status = statuses.get(i); set.add(status.getText()); editor.putStringSet("key", set); editor.commit(); Log.i("Tweet Count " + (i + 1), status.getText() + "\n\n"); } } catch (TwitterException te) { te.printStackTrace(); } } }).start(); Set<String> mySet = new HashSet<String>(); mySet = sharedpreferences.getStringSet("key", set); Timer timer = new Timer(); if (mySet != null) { for (final String tweet : mySet) { list.add(tweet); /* Toast.makeText(getApplicationContext(), tweet, Toast.LENGTH_LONG).show();*/ } } //set modi's slogan // list = new ArrayList<>(); /* sharedpreferences= getSharedPreferences(MyPREFERENCES, MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); for(int i=0;i<slogan.length;i++) editor.putString(slogan + "_" + i, slogan[i]); editor.commit(); Map<String, ?> str = sharedpreferences.getAll(); for (final Map.Entry<String, ?> entry : str.entrySet()) { list.add(entry.getValue().toString()); }*/ getTweet(); getSlogan(); }
From source file:com.androtwitt.ExampleAppWidgetProvider.java
License:Apache License
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { Log.d(TAG, "updateAppWidget appWidgetId=" + appWidgetId); ArrayList lines = new ArrayList(); Twitter unauthenticatedTwitter = new TwitterFactory().getInstance(); System.out.println("Showing public timeline."); try {// ww w . ja v a 2 s. c om List<Status> statuses = unauthenticatedTwitter.getPublicTimeline(); // Other methods require authentication String username = ExampleAppWidgetConfigure.loadTitlePref(context, appWidgetId, "username"); String password = ExampleAppWidgetConfigure.loadTitlePref(context, appWidgetId, "password"); Twitter twitter = new TwitterFactory().getInstance(username, password); statuses = twitter.getFriendsTimeline(); for (Status status : statuses) { lines.add(status.getUser().getScreenName() + ":" + status.getText()); } } catch (TwitterException te) { Log.d("AT_Error", "Failed to get timeline: " + te.getMessage()); } // Construct the RemoteViews object. It takes the package name (in our case, it's our // package, but it needs this because on the other side it's the widget host inflating // the layout from our package). RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider); ArrayList<Integer> widgetTexts = new ArrayList(); widgetTexts.add(R.id.appwidget_text0); widgetTexts.add(R.id.appwidget_text1); widgetTexts.add(R.id.appwidget_text2); widgetTexts.add(R.id.appwidget_text3); widgetTexts.add(R.id.appwidget_text4); widgetTexts.add(R.id.appwidget_text5); widgetTexts.add(R.id.appwidget_text6); widgetTexts.add(R.id.appwidget_text7); widgetTexts.add(R.id.appwidget_text8); widgetTexts.add(R.id.appwidget_text9); Iterator i = widgetTexts.iterator(); Iterator j = lines.iterator(); while (i.hasNext()) { Integer value = (Integer) i.next(); if (j.hasNext()) { views.setTextViewText(value, (String) j.next()); } } // Tell the widget manager appWidgetManager.updateAppWidget(appWidgetId, views); }
From source file:com.appspot.bitlyminous.handler.twitter.AbstractTwitterHandler.java
License:Apache License
/** * Gets the mention text./*from ww w . ja va2 s. c om*/ * * @param tweet the tweet * * @return the mention text */ protected String getMentionText(Status tweet) { String text = tweet.getText().replaceAll("@" + ApplicationConstants.TWITTER_SCREEN_NAME, ""); if (commandName != null) { text = text.replaceFirst(commandName, ""); } return text; }
From source file:com.appspot.bitlyminous.handler.twitter.RetweetRelatedTweetsHandler.java
License:Apache License
/** * Gets the best matches.//from w w w .j av a2 s . co m * * @param status the status * @param relatedTweets the related tweets * @param count the count * * @return the best matches */ // private List<Tweet> getBestMatches(Status status, List<Tweet> relatedTweets, int count) { // RecommendationService recommendationService = ServiceFactory.newInstance().createRecommendationService(); // Map<String, Tweet> tweetTexts = new HashMap<String, Tweet>(); // for (Tweet tweet : relatedTweets) { // tweetTexts.put(tweet.getText(), tweet); // } // List<Map.Entry<String, Double>> textSimilarities = recommendationService.getTextSimilarities(status.getText(), new ArrayList<String>(tweetTexts.keySet())); // // List<Tweet> similarTweets = new ArrayList<Tweet>(); // for (int i = 0; i < textSimilarities.size() && i < count; i++) { // similarTweets.add(tweetTexts.get(textSimilarities.get(i).getKey())); // } // return similarTweets; // } private List<WebResult> getBestMatches(Status status, List<WebResult> relatedTweets, int count) { RecommendationService recommendationService = ServiceFactory.newInstance().createRecommendationService(); Map<String, WebResult> tweetTexts = new HashMap<String, WebResult>(); for (WebResult tweet : relatedTweets) { tweetTexts.put(tweet.getContent(), tweet); } List<Map.Entry<String, Double>> textSimilarities = recommendationService .getTextSimilarities(status.getText(), new ArrayList<String>(tweetTexts.keySet())); List<WebResult> similarTweets = new ArrayList<WebResult>(); for (int i = 0; i < textSimilarities.size() && i < count; i++) { similarTweets.add(tweetTexts.get(textSimilarities.get(i).getKey())); } return similarTweets; }
From source file:com.appspot.bitlyminous.handler.twitter.SaveUrlHandler.java
License:Apache License
@Override public StatusUpdate execute(Status tweet) { try {//from ww w. j a v a2s . c o m List<String> shortUrls = extractBitlyUrls(tweet.getText()); if (!shortUrls.isEmpty()) { Set<Url> longUrls = getBitlyClient() .call(Bitly.expand(shortUrls.toArray(new String[shortUrls.size()]))); List<com.appspot.bitlyminous.entity.Url> entities = new ArrayList<com.appspot.bitlyminous.entity.Url>(); for (Url url : longUrls) { if (!isEmpty(url.getLongUrl())) { com.appspot.bitlyminous.entity.Url entity = new com.appspot.bitlyminous.entity.Url(); entity.setDescription(tweet.getText()); entity.setUrl(url.getLongUrl()); entity.setShortUrl(url.getShortUrl()); entity.setDateSubmitted(tweet.getCreatedAt()); List<String> suggestedTags = new ArrayList<String>(); DeliciousGateway deliciousGateway = getDeliciousGateway(context.getVersion()); try { suggestedTags = deliciousGateway.getSuggestedTags(url.getLongUrl()); } catch (GatewayException e) { logger.log(Level.WARNING, "Seems like Delicious token expired again.", e); if (e.getErrorCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { deliciousGateway .refreshToken(context.getVersion().getDeliciousSessionHandle().getValue()); context.getVersion().setDeliciousToken( new Text(deliciousGateway.getOAuthAuthentication().getAccessToken())); context.getVersion().setDeliciousSecret( new Text(deliciousGateway.getOAuthAuthentication().getAccessTokenSecret())); context.getVersion().setDeliciousSessionHandle(new Text( deliciousGateway.getOAuthAuthentication().getOauthSessionHandle())); suggestedTags = deliciousGateway.getSuggestedTags(url.getLongUrl()); } else { throw e; } } entity.setTags(suggestedTags); entity.setUser(context.getUser()); updateUserTags(context.getUser(), suggestedTags); entities.add(entity); } } context.setUrls(entities); updateUserUrls(context.getUser(), entities); } } catch (Exception e) { logger.log(Level.SEVERE, "Error while persisting urls.", e); } return null; }
From source file:com.appspot.bitlyminous.handler.twitter.ScanLinkHandler.java
License:Apache License
@Override public StatusUpdate execute(Status tweet) { try {/* w w w . j av a2 s . co m*/ List<String> shortUrls = extractBitlyUrls(tweet.getText()); if (!shortUrls.isEmpty()) { Set<Url> longUrls = getBitlyClient() .call(Bitly.expand(shortUrls.toArray(new String[shortUrls.size()]))); GoogleSafeBrowsingGateway gateway = getGoogleSafeBrowsingGateway(); for (Url url : longUrls) { if (!isEmpty(url.getLongUrl())) { if (gateway.isBlacklisted(url.getLongUrl())) { StatusUpdate reply = new StatusUpdate(ApplicationResources.getLocalizedString( "com.appspot.bitlyminous.message.badurl", new String[] { "@" + tweet.getUser().getScreenName(), trimText(tweet.getText(), 20), ApplicationConstants.GOOGLE_SAFE_BROWSING_REF_URL })); reply.setInReplyToStatusId(tweet.getId()); return reply; } if (gateway.isMalwarelisted(url.getLongUrl())) { StatusUpdate reply = new StatusUpdate(ApplicationResources.getLocalizedString( "com.appspot.bitlyminous.message.badurl", new String[] { "@" + tweet.getUser().getScreenName(), trimText(tweet.getText(), 20), ApplicationConstants.GOOGLE_SAFE_BROWSING_REF_URL })); reply.setInReplyToStatusId(tweet.getId()); return reply; } } } } } catch (Exception e) { logger.log(Level.SEVERE, "Error while scanning urls.", e); } return null; }
From source file:com.appspot.bitlyminous.handler.twitter.TwitterHandlerFactory.java
License:Apache License
/** * Creates a new TwitterHandler object.//w w w . j a va2 s .co m * * @param tweet the tweet * * @return the twitter handler */ public TwitterHandler createCommand(Status tweet) { String action = tweet.getText().replaceAll("@" + ApplicationConstants.TWITTER_SCREEN_NAME, "").trim() .split("\\s+")[0]; if (HANDLERS.containsKey(action)) { return HANDLERS.get(action); } return new SearchHandler(context); }
From source file:com.appspot.socialinquirer.server.service.impl.UserServiceImpl.java
License:Apache License
@Override public void aggregateQuotes() { EntityManager entityManager = createEntityManager(); try {/*from w w w . j a v a 2 s . com*/ DataAccessObject dao = getDao(entityManager); Version version = getCurrentVersion(); Twitter twitter = getTwitterClient(); List<Status> homeTimeline = twitter.getUserTimeline(ApplicationConstants.TWITTER_SCREEN_NAME, new Paging(version.getLastHomeTweetId())); long lastTweetId = 0L; for (Status status : homeTimeline) { if (status.getId() > lastTweetId) { lastTweetId = status.getId(); } if (!status.isRetweet() && status.getInReplyToStatusId() == -1) { Quote quote = new Quote(); quote.setPublishedDate(status.getCreatedAt()); quote.setText(new Text(status.getText())); quote.setTweetId(status.getId()); dao.saveOrUpdate(quote); } } if (lastTweetId > version.getLastHomeTweetId()) { version.setLastHomeTweetId(lastTweetId); dao.saveOrUpdate(version); } } catch (Exception e) { throw new ServiceException(e); } finally { closeEntityManager(entityManager); } }