List of usage examples for twitter4j Twitter updateStatus
Status updateStatus(String status) throws TwitterException;
From source file:org.fossasia.phimpme.share.twitter.HelperMethods.java
License:Apache License
public static void postToTwitterWithImage(Context context, final String imageUrl, final String message, final String token, final String secret, final TwitterCallback postResponse) { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); configurationBuilder.setOAuthAccessToken(token); configurationBuilder.setOAuthAccessTokenSecret(secret); Configuration configuration = configurationBuilder.build(); final Twitter twitter = new TwitterFactory(configuration).getInstance(); final File file = new File(imageUrl); boolean success = true; if (file.exists()) { try {/*from w ww . j ava 2s.co m*/ StatusUpdate status = new StatusUpdate(message); status.setMedia(file); twitter.updateStatus(status); } catch (TwitterException e) { e.printStackTrace(); success = false; } } else { Log.d(TAG, "----- Invalid File ----------"); success = false; } postResponse.onFinsihed(success); }
From source file:org.getlantern.firetweet.service.BackgroundOperationService.java
License:Open Source License
private List<SingleResponse<ParcelableStatus>> updateStatus(final Builder builder, final ParcelableStatusUpdate statusUpdate) { final ArrayList<ContentValues> hashTagValues = new ArrayList<>(); final Collection<String> hashTags = extractor.extractHashtags(statusUpdate.text); for (final String hashTag : hashTags) { final ContentValues values = new ContentValues(); values.put(CachedHashtags.NAME, hashTag); hashTagValues.add(values);// w w w.j a v a2 s .com } final boolean hasEasterEggTriggerText = statusUpdate.text.contains(EASTER_EGG_TRIGGER_TEXT); final boolean hasEasterEggRestoreText = statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART1) && statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART2) && statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART3); boolean mentionedHondaJOJO = false, notReplyToOther = false; mResolver.bulkInsert(CachedHashtags.CONTENT_URI, hashTagValues.toArray(new ContentValues[hashTagValues.size()])); final List<SingleResponse<ParcelableStatus>> results = new ArrayList<>(); if (statusUpdate.accounts.length == 0) return Collections.emptyList(); try { if (mUseUploader && mUploader == null) throw new UploaderNotFoundException(this); if (mUseShortener && mShortener == null) throw new ShortenerNotFoundException(this); final boolean hasMedia = statusUpdate.media != null && statusUpdate.media.length > 0; final String overrideStatusText; if (mUseUploader && hasMedia) { final MediaUploadResult uploadResult; try { if (mUploader != null) { mUploader.waitForService(); } uploadResult = mUploader.upload(statusUpdate, UploaderMediaItem.getFromStatusUpdate(this, statusUpdate)); } catch (final Exception e) { Crashlytics.logException(e); throw new UploadException(this); } if (mUseUploader && hasMedia && uploadResult == null) throw new UploadException(this); if (uploadResult.error_code != 0) throw new UploadException(uploadResult.error_message); overrideStatusText = getImageUploadStatus(this, uploadResult.media_uris, statusUpdate.text); } else { overrideStatusText = null; } final String unShortenedText = isEmpty(overrideStatusText) ? statusUpdate.text : overrideStatusText; final boolean shouldShorten = mValidator.getTweetLength(unShortenedText) > mValidator .getMaxTweetLength(); final String shortenedText; if (shouldShorten) { if (mUseShortener) { final StatusShortenResult shortenedResult; mShortener.waitForService(); try { shortenedResult = mShortener.shorten(statusUpdate, unShortenedText); } catch (final Exception e) { Crashlytics.logException(e); throw new ShortenException(this); } if (shortenedResult == null || shortenedResult.shortened == null) throw new ShortenException(this); shortenedText = shortenedResult.shortened; } else throw new StatusTooLongException(this); } else { shortenedText = unShortenedText; } if (statusUpdate.media != null) { for (final ParcelableMediaUpdate media : statusUpdate.media) { final String path = getImagePathFromUri(this, Uri.parse(media.uri)); final File file = path != null ? new File(path) : null; if (!mUseUploader && file != null && file.exists()) { BitmapUtils.downscaleImageIfNeeded(file, 95); } } } for (final ParcelableAccount account : statusUpdate.accounts) { final Twitter twitter = getTwitterInstance(this, account.account_id, true, true); final StatusUpdate status = new StatusUpdate(shortenedText); status.setInReplyToStatusId(statusUpdate.in_reply_to_status_id); if (statusUpdate.location != null) { status.setLocation(ParcelableLocation.toGeoLocation(statusUpdate.location)); } if (!mUseUploader && hasMedia) { final BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; final long[] mediaIds = new long[statusUpdate.media.length]; ContentLengthInputStream is = null; try { for (int i = 0, j = mediaIds.length; i < j; i++) { final ParcelableMediaUpdate media = statusUpdate.media[i]; final String path = getImagePathFromUri(this, Uri.parse(media.uri)); if (path == null) throw new FileNotFoundException(); BitmapFactory.decodeFile(path, o); final File file = new File(path); is = new ContentLengthInputStream(file); is.setReadListener(new StatusMediaUploadListener(this, mNotificationManager, builder, statusUpdate)); final MediaUploadResponse uploadResp = twitter.uploadMedia(file.getName(), is, o.outMimeType); mediaIds[i] = uploadResp.getId(); } } catch (final FileNotFoundException e) { Crashlytics.logException(e); Log.w(LOGTAG, e); } catch (final TwitterException e) { Crashlytics.logException(e); final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); continue; } finally { IoUtils.closeSilently(is); } status.mediaIds(mediaIds); } status.setPossiblySensitive(statusUpdate.is_possibly_sensitive); if (twitter == null) { results.add(new SingleResponse<ParcelableStatus>(null, new NullPointerException())); continue; } try { final Status resultStatus = twitter.updateStatus(status); if (!mentionedHondaJOJO) { final UserMentionEntity[] entities = resultStatus.getUserMentionEntities(); if (entities == null || entities.length == 0) { mentionedHondaJOJO = statusUpdate.text.contains("@" + HONDAJOJO_SCREEN_NAME); } else if (entities.length == 1 && entities[0].getId() == HONDAJOJO_ID) { mentionedHondaJOJO = true; } Utils.setLastSeen(this, entities, System.currentTimeMillis()); } if (!notReplyToOther) { final long inReplyToUserId = resultStatus.getInReplyToUserId(); if (inReplyToUserId <= 0 || inReplyToUserId == HONDAJOJO_ID) { notReplyToOther = true; } } final ParcelableStatus result = new ParcelableStatus(resultStatus, account.account_id, false); results.add(new SingleResponse<>(result, null)); } catch (final TwitterException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); Crashlytics.logException(e); } } } catch (final UpdateStatusException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); Crashlytics.logException(e); } if (mentionedHondaJOJO) { triggerEasterEgg(notReplyToOther, hasEasterEggTriggerText, hasEasterEggRestoreText); } return results; }
From source file:org.iadb.knl.twitter.twitterknlapi.Twitterro.java
public static void main(String[] args) { // Config.registerSmbURLHandler(); // Config.setProperty("jcifs.smb.client.domain", domain); // Config.setProperty("jcifs.smb.client.username", user); // Config.setProperty("jcifs.smb.client.password", password); try {//from www . ja v a2s. c om // Config.setProperty("jcifs.netbios.hostname", // Config.getProperty("jcifs.netbios.hostname", // InetAddress.getLocalHost().getHostName())); System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); System.setProperty("http.auth.ntlm.domain", domain); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password.toCharArray()); } }; Authenticator.setDefault(authenticator); Twitter twitter = TwitterFactory.getSingleton(); Status status = twitter.updateStatus("Este arbitro va pitar la final de #bra vrs #uru"); System.out.println("Successfully updated the status to [" + status.getText() + "]."); // Query query = new Query(); // query.setQuery(""); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.jetbrains.webdemo.servlet.TwitterServlet.java
License:Apache License
private void tweet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {// www . j av a 2 s . co m Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); twitter.getOAuthAccessToken(requestToken, verifier); String status = (String) request.getSession().getAttribute("tweetText"); request.getSession().removeAttribute("tweetText"); StatusUpdate statusUpdate = new StatusUpdate(status); String level = (String) request.getSession().getAttribute("kotlin-level"); request.getSession().removeAttribute("level"); statusUpdate.setMedia( new File(CommonSettings.WEBAPP_ROOT_DIRECTORY + "static/images/" + level + "level.gif")); twitter.updateStatus(statusUpdate); request.getSession().removeAttribute("requestToken"); response.sendRedirect(request.getContextPath() + "/"); } catch (Throwable e) { throw new ServletException(e); } }
From source file:org.jorge.twitterpromoter.io.net.TwitterManager.java
License:Open Source License
public void tweet(String message) { Twitter twitter = new TwitterFactory(new ConfigurationBuilder().setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET).build()).getInstance(); try {//from www.j av a2s.co m twitter.updateStatus(message); System.out.println("Tweet " + message + " sent!"); } catch (TwitterException e) { System.err.println("Tweet " + message + "not sent!"); e.printStackTrace(System.err); } }
From source file:org.jrecruiter.service.notification.impl.DefaultNotificationServiceImpl.java
/** {@inheritDoc} */ @Override/*from w ww.j a v a 2 s . c o m*/ public void sendTweetToTwitter(final String tweet) { final Twitter twitter = new Twitter(apiKeysHolder.getTwitterUsername(), apiKeysHolder.getTwitterPassword()); try { twitter.updateStatus(tweet); } catch (TwitterException e) { throw new IllegalStateException(e); } }
From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java
License:Apache License
/** * posts a Twitter message on behalf of a OAtuh authenticated user by using * the retrieved AccessToken and its verifier. * * @param aConnector//from w ww. j a v a 2s.c om * @param aToken */ private void tweet(WebSocketConnector aConnector, Token aToken) { TokenServer lServer = getServer(); // instantiate response token Token lResponse = lServer.createResponse(aToken); String lMsg = aToken.getString("message"); try { // to send tweet we need an authenticated user Twitter lTwitter = (Twitter) aConnector.getVar(TWITTER_VAR); RequestToken lReqToken = (RequestToken) aConnector.getVar(OAUTH_REQUEST_TOKEN); String lVerifier = aConnector.getString(OAUTH_VERIFIER); if (lTwitter == null) { lResponse.setInteger("code", -1); lResponse.setString("msg", "Not yet authenticated against Twitter!"); } else if (lReqToken == null) { lResponse.setInteger("code", -1); lResponse.setString("msg", "No Access Token available!"); } else if (lVerifier == null) { lResponse.setInteger("code", -1); lResponse.setString("msg", "No Access Verifier available!"); } else if (lMsg == null || lMsg.length() <= 0) { lResponse.setInteger("code", -1); lResponse.setString("msg", "No message passed for tweet."); } else { AccessToken lAccessToken = lTwitter.getOAuthAccessToken(lReqToken, lVerifier); lTwitter.setOAuthAccessToken(lAccessToken); lTwitter.updateStatus(lMsg); lMsg = "Twitter status successfully updated for user '" + lTwitter.getScreenName() + "'."; lResponse.setString("msg", lMsg); if (mLog.isInfoEnabled()) { mLog.info(lMsg); } } } catch (Exception lEx) { lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage(); mLog.error(lMsg); lResponse.setInteger("code", -1); lResponse.setString("msg", lMsg); } // send response to requester lServer.sendToken(aConnector, lResponse); }
From source file:org.luwrain.app.twitter.Base.java
License:Open Source License
static boolean updateStatusImpl(Twitter twitter, String tweet) { NullCheck.notNull(twitter, "twitter"); NullCheck.notEmpty(tweet, "tweet"); try {//from w w w . j a va2 s .co m twitter.updateStatus(tweet); return true; } catch (TwitterException e) { Log.error("twitter", "unable to update status:" + e.getClass().getName() + ":" + e.getMessage()); e.printStackTrace(); return false; } }
From source file:org.mariotaku.twidere.service.BackgroundOperationService.java
License:Open Source License
private List<SingleResponse<ParcelableStatus>> updateStatus(final Builder builder, final ParcelableStatusUpdate statusUpdate) { final ArrayList<ContentValues> hashTagValues = new ArrayList<>(); final Collection<String> hashTags = extractor.extractHashtags(statusUpdate.text); for (final String hashTag : hashTags) { final ContentValues values = new ContentValues(); values.put(CachedHashtags.NAME, hashTag); hashTagValues.add(values);/*w ww . j a v a 2 s.co m*/ } final boolean hasEasterEggTriggerText = statusUpdate.text.contains(EASTER_EGG_TRIGGER_TEXT); final boolean hasEasterEggRestoreText = statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART1) && statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART2) && statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART3); boolean mentionedHondaJOJO = false, notReplyToOther = false; mResolver.bulkInsert(CachedHashtags.CONTENT_URI, hashTagValues.toArray(new ContentValues[hashTagValues.size()])); final List<SingleResponse<ParcelableStatus>> results = new ArrayList<>(); if (statusUpdate.accounts.length == 0) return Collections.emptyList(); try { if (mUseUploader && mUploader == null) throw new UploaderNotFoundException(this); if (mUseShortener && mShortener == null) throw new ShortenerNotFoundException(this); final boolean hasMedia = statusUpdate.media != null && statusUpdate.media.length > 0; final String overrideStatusText; if (mUseUploader && mUploader != null && hasMedia) { final MediaUploadResult uploadResult; try { mUploader.waitForService(); uploadResult = mUploader.upload(statusUpdate, UploaderMediaItem.getFromStatusUpdate(this, statusUpdate)); } catch (final Exception e) { throw new UploadException(this); } finally { mUploader.unbindService(); } if (mUseUploader && hasMedia && uploadResult == null) throw new UploadException(this); if (uploadResult.error_code != 0) throw new UploadException(uploadResult.error_message); overrideStatusText = getImageUploadStatus(this, uploadResult.media_uris, statusUpdate.text); } else { overrideStatusText = null; } final String unShortenedText = isEmpty(overrideStatusText) ? statusUpdate.text : overrideStatusText; final boolean shouldShorten = mValidator.getTweetLength(unShortenedText) > mValidator .getMaxTweetLength(); final String shortenedText; if (shouldShorten) { if (mUseShortener) { final StatusShortenResult shortenedResult; mShortener.waitForService(); try { shortenedResult = mShortener.shorten(statusUpdate, unShortenedText); } catch (final Exception e) { throw new ShortenException(this); } finally { mShortener.unbindService(); } if (shortenedResult == null || shortenedResult.shortened == null) throw new ShortenException(this); shortenedText = shortenedResult.shortened; } else throw new StatusTooLongException(this); } else { shortenedText = unShortenedText; } if (statusUpdate.media != null) { for (final ParcelableMediaUpdate media : statusUpdate.media) { final String path = getImagePathFromUri(this, Uri.parse(media.uri)); final File file = path != null ? new File(path) : null; if (!mUseUploader && file != null && file.exists()) { BitmapUtils.downscaleImageIfNeeded(file, 95); } } } for (final ParcelableAccount account : statusUpdate.accounts) { final Twitter twitter = getTwitterInstance(this, account.account_id, true, true); final StatusUpdate status = new StatusUpdate(shortenedText); status.setInReplyToStatusId(statusUpdate.in_reply_to_status_id); if (statusUpdate.location != null) { status.setLocation(ParcelableLocation.toGeoLocation(statusUpdate.location)); } if (!mUseUploader && hasMedia) { final BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; final long[] mediaIds = new long[statusUpdate.media.length]; ContentLengthInputStream is = null; try { for (int i = 0, j = mediaIds.length; i < j; i++) { final ParcelableMediaUpdate media = statusUpdate.media[i]; final String path = getImagePathFromUri(this, Uri.parse(media.uri)); if (path == null) throw new FileNotFoundException(); BitmapFactory.decodeFile(path, o); final File file = new File(path); is = new ContentLengthInputStream(file); is.setReadListener(new StatusMediaUploadListener(this, mNotificationManager, builder, statusUpdate)); final MediaUploadResponse uploadResp = twitter.uploadMedia(file.getName(), is, o.outMimeType); mediaIds[i] = uploadResp.getId(); } } catch (final FileNotFoundException e) { Log.w(LOGTAG, e); } catch (final TwitterException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); continue; } finally { IoUtils.closeSilently(is); } status.mediaIds(mediaIds); } status.setPossiblySensitive(statusUpdate.is_possibly_sensitive); if (twitter == null) { results.add(new SingleResponse<ParcelableStatus>(null, new NullPointerException())); continue; } try { final Status resultStatus = twitter.updateStatus(status); if (!mentionedHondaJOJO) { final UserMentionEntity[] entities = resultStatus.getUserMentionEntities(); if (entities == null || entities.length == 0) { mentionedHondaJOJO = statusUpdate.text.contains("@" + HONDAJOJO_SCREEN_NAME); } else if (entities.length == 1 && entities[0].getId() == HONDAJOJO_ID) { mentionedHondaJOJO = true; } Utils.setLastSeen(this, entities, System.currentTimeMillis()); } if (!notReplyToOther) { final long inReplyToUserId = resultStatus.getInReplyToUserId(); if (inReplyToUserId <= 0 || inReplyToUserId == HONDAJOJO_ID) { notReplyToOther = true; } } final ParcelableStatus result = new ParcelableStatus(resultStatus, account.account_id, false); results.add(new SingleResponse<>(result, null)); } catch (final TwitterException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); } } } catch (final UpdateStatusException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); } if (mentionedHondaJOJO) { triggerEasterEgg(notReplyToOther, hasEasterEggTriggerText, hasEasterEggRestoreText); } return results; }
From source file:org.opencrx.kernel.portal.wizard.TwitterUpdateStatusWizardController.java
License:BSD License
/** * OK action.// w w w .j av a 2 s. c o m * * @param formFields * @param serviceAccountId * @throws ServiceException */ public void doOK(@FormParameter(forms = "TwitterUpdateStatusForm") Map<String, Object> formFields, @RequestParameter(name = "serviceAccountId") String serviceAccountId) throws ServiceException { PersistenceManager pm = this.getPm(); this.doRefresh(formFields, serviceAccountId); RefObject_1_0 obj = this.getObject(); javax.jdo.PersistenceManager rootPm = pm.getPersistenceManagerFactory() .getPersistenceManager(org.opencrx.kernel.generic.SecurityKeys.ROOT_PRINCIPAL, null); org.opencrx.kernel.home1.jmi1.UserHome userHome = UserHomes.getInstance().getUserHome(obj.refGetPath(), pm); serviceAccountId = (String) formFields.get("serviceAccountId"); String text = (String) formFields.get("org:opencrx:kernel:base:Note:text"); if ((serviceAccountId != null) && (serviceAccountId.length() > 0) && (text != null) && (text.length() > 0)) { org.opencrx.kernel.admin1.jmi1.ComponentConfiguration configuration = org.opencrx.application.twitter.TwitterUtils .getComponentConfiguration(this.getProviderName(), this.getSegmentName(), rootPm); // Find default twitter account org.opencrx.kernel.home1.jmi1.TwitterAccount twitterAccount = (org.opencrx.kernel.home1.jmi1.TwitterAccount) userHome .getEMailAccount(serviceAccountId); if (twitterAccount != null) { TwitterFactory twitterFactory = new TwitterFactory(); AccessToken accessToken = new AccessToken(twitterAccount.getAccessToken(), twitterAccount.getAccessTokenSecret()); Twitter twitter = twitterFactory.getInstance(); twitter.setOAuthConsumer(TwitterUtils.getConsumerKey(twitterAccount, configuration), TwitterUtils.getConsumerSecret(twitterAccount, configuration)); twitter.setOAuthAccessToken(accessToken); try { @SuppressWarnings("unused") Status status = twitter.updateStatus(text); } catch (Exception e) { new ServiceException(e).log(); } // Send alert if invoked on user's home String title = NOTE_TITLE_PREFIX + " [" + twitterAccount.getName() + "] @ " + new Date(); if (obj instanceof org.opencrx.kernel.home1.jmi1.UserHome) { org.opencrx.kernel.home1.jmi1.UserHome user = (org.opencrx.kernel.home1.jmi1.UserHome) obj; Base.getInstance().sendAlert(user, // target user.refGetPath().getBase(), title, text, (short) 2, // importance 0, // resendDelayInSeconds null // reference ); } // Attach message as Note else if (obj instanceof org.opencrx.kernel.generic.jmi1.CrxObject) { try { pm.currentTransaction().begin(); org.opencrx.kernel.generic.jmi1.CrxObject crxObject = (org.opencrx.kernel.generic.jmi1.CrxObject) obj; org.opencrx.kernel.generic.jmi1.Note note = pm .newInstance(org.opencrx.kernel.generic.jmi1.Note.class); note.setTitle(title); note.setText(text); crxObject.addNote(Base.getInstance().getUidAsString(), note); pm.currentTransaction().commit(); // FollowUp if obj is an activity if (obj instanceof Activity) { try { Activity activity = (Activity) obj; ActivityProcess activityProcess = activity.getActivityType().getControlledBy(); org.opencrx.kernel.activity1.cci2.ActivityProcessTransitionQuery processTransitionQuery = (org.opencrx.kernel.activity1.cci2.ActivityProcessTransitionQuery) pm .newQuery( org.opencrx.kernel.activity1.cci2.ActivityProcessTransition.class); processTransitionQuery.thereExistsPrevState().equalTo(activity.getProcessState()); processTransitionQuery.orderByNewPercentComplete().ascending(); List<ActivityProcessTransition> processTransitions = activityProcess .getTransition(processTransitionQuery); if (!processTransitions.isEmpty()) { ActivityProcessTransition processTransition = processTransitions.iterator() .next(); pm.currentTransaction().begin(); @SuppressWarnings("unused") ActivityFollowUp followUp = Activities.getInstance().doFollowUp(activity, title, text, processTransition, null, // reportingContact null // parentProcessInstance ); pm.currentTransaction().commit(); } } catch (Exception e) { try { pm.currentTransaction().rollback(); } catch (Exception e0) { } } } } catch (Exception e) { try { pm.currentTransaction().rollback(); } catch (Exception e0) { } } } this.forward("Cancel", this.getRequest().getParameterMap()); } } }