List of usage examples for twitter4j Twitter updateStatus
Status updateStatus(String status) throws TwitterException;
From source file:de.ecw.ant.twitter.AntTwitterTask.java
License:Apache License
/** * Executes Ant task://from ww w. j a va2 s .c o m * <ul> * <li>establish a connection to Twitter via twitter4j</li> * <li>if enabled, execute URL shortening via bitly</li> * <li>check the input message and split it into chunks if message is larger * than 140 characters</li> * <li>update status of every message</li> * </ul> */ public void execute() throws BuildException { String useMessage = getMessage(); // validate Twitter parameters if ((getConsumerKey() == null) || ((getConsumerKey() != null) && (getConsumerKey().length() == 0)) || (getConsumerSecret() == null) || ((getConsumerSecret() != null) && (getConsumerSecret().length() == 0))) { log("You have to enter a valid Twitter username/password combination, missing arguments!", Project.MSG_ERR); return; } // should URLs be shortened? if ((getEnableBitly() != null) && (getEnableBitly().toLowerCase().equals(TRUE))) { // validate bit.ly parameters if ((getBitlyUsername() == null) || ((getBitlyUsername() != null) && (getBitlyUsername().length() == 0)) || (getBitlyApiKey() == null) || ((getBitlyApiKey() != null) && (getBitlyApiKey().length() == 0))) { log("You have enabled bit.ly support, but bit.ly username or API key is missing - bit.ly support is disabled", Project.MSG_WARN); } else { useMessage = shortenUrls(message); } } // new Twitter client ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(getConsumerKey()).setOAuthConsumerSecret(getConsumerSecret()) .setOAuthAccessToken(getAccessToken()).setOAuthAccessTokenSecret(getAccessTokenSecret()); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); // assume that all messages are longer than 140 chars List<String> messages = AntTwitterTask.splitMessage(useMessage); log("Twittering update (" + messages.size() + " tweets)", Project.MSG_INFO); int iTotalPosts = messages.size(); int iSuccededUpdates = 0; try { // post every tweet for (int i = 0; i < iTotalPosts; i++) { String msg = messages.get(i); log(msg.length() + " chars: " + msg, Project.MSG_INFO); twitter.updateStatus(msg); iSuccededUpdates++; } } catch (TwitterException e) { log("Failed to update Twitter status", e, Project.MSG_ERR); } log("Tweets posted: " + iSuccededUpdates + "/" + iTotalPosts, Project.MSG_INFO); }
From source file:de.hikinggrass.eiwomisarc.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * //from ww w . jav a 2 s.c o m * @param args * message */ public UpdateStatus() { try { ConfigurationBuilder confBuilder = new ConfigurationBuilder(); //use https for oauth confBuilder.setUseSSL(true); Configuration conf = confBuilder.build(); Twitter twitter = new TwitterFactory(conf).getInstance(); twitter.setOAuthConsumer("HaBxuZMHygmtcuPeCbOLg", "zg6bV26ksBrgKHdhmiLlubTtV9MaDhoIRZC1ODUKw"); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; 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 available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus("test from eiwomisarc"); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:de.hoesel.dav.buv.twitter.baustelle.BaustelleTwitternDialog.java
License:Open Source License
@Override protected void okPressed() { RahmenwerkService service = RahmenwerkService.getService(); Twitter twitter = service.getTwitter(); try {/* w w w .j a v a2s.c om*/ // TODO:Bilder funktionieren noch nicht richtig // InputStream resourceAsStream = // BaustelleTwitternDialog.class.getResourceAsStream("baustelle.gif"); StatusUpdate update = new StatusUpdate("[Test] " + messgae.getText()); if (location != null) { // TODO: Das funktioniert nur, wenn man in seinen Twitter // Setting via Opt-In das Anzeigen der Location erlaubt. update.displayCoordinates(true); update.setLocation(location); } // update.setMedia("Baustelle",resourceAsStream); twitter.updateStatus(update); super.okPressed(); } catch (TwitterException e) { setErrorMessage(e.getLocalizedMessage()); e.printStackTrace(); } }
From source file:de.vanita5.twittnuker.service.BackgroundOperationService.java
License:Open Source License
private List<SingleResponse<ParcelableStatus>> updateStatus(final Builder builder, final ParcelableStatusUpdate statusUpdate) { final ArrayList<ContentValues> hashtag_values = new ArrayList<ContentValues>(); final Collection<String> hashtags = extractor.extractHashtags(statusUpdate.text); for (final String hashtag : hashtags) { final ContentValues values = new ContentValues(); values.put(CachedHashtags.NAME, hashtag); hashtag_values.add(values);//from w w w . ja va 2 s. c o m } boolean notReplyToOther = false; mResolver.bulkInsert(CachedHashtags.CONTENT_URI, hashtag_values.toArray(new ContentValues[hashtag_values.size()])); final List<SingleResponse<ParcelableStatus>> results = new ArrayList<SingleResponse<ParcelableStatus>>(); if (statusUpdate.accounts.length == 0) return Collections.emptyList(); try { final boolean hasMedia = statusUpdate.medias != null && statusUpdate.medias.length > 0; final String imagePath = hasMedia ? getImagePathFromUri(this, Uri.parse(statusUpdate.medias[0].uri)) : null; final File imageFile = imagePath != null ? new File(imagePath) : null; String uploadResultUrl = null; if (mUseUploader && imageFile != null && imageFile.exists()) { uploadResultUrl = uploadMedia(imageFile, statusUpdate.accounts, statusUpdate.text); } final String unshortenedContent = mUseUploader && uploadResultUrl != null ? getImageUploadStatus(new String[] { uploadResultUrl.toString() }, statusUpdate.text) : statusUpdate.text; final boolean shouldShorten = mValidator.getTweetLength(unshortenedContent) > mValidator .getMaxTweetLength(); Map<Long, ShortenedStatusModel> shortenedStatuses = null; if (shouldShorten && mUseShortener) { if (mShortener.equals(SERVICE_SHORTENER_HOTOTIN)) { shortenedStatuses = postHototIn(statusUpdate); if (shortenedStatuses == null) throw new ShortenException(this); } else if (mShortener.equals(SERVICE_SHORTENER_TWITLONGER)) { shortenedStatuses = postTwitlonger(statusUpdate); if (shortenedStatuses == null) throw new ShortenException(this); } else { throw new IllegalArgumentException("BackgroundOperationService.java#updateStatus()"); } } if (shouldShorten) { if (!mUseShortener) throw new StatusTooLongException(this); else if (unshortenedContent == null) throw new ShortenException(this); } if (!mUseUploader && statusUpdate.medias != null) { for (final ParcelableMediaUpdate media : statusUpdate.medias) { final String path = getImagePathFromUri(this, Uri.parse(media.uri)); final File file = path != null ? new File(path) : null; if (file != null && file.exists()) { Utils.downscaleImageIfNeeded(file, 95); } } } for (final Account account : statusUpdate.accounts) { String shortenedContent = ""; ShortenedStatusModel shortenedStatusModel = null; final Twitter twitter = getTwitterInstance(this, account.account_id, true, true); if (shouldShorten && mUseShortener && shortenedStatuses != null) { shortenedStatusModel = shortenedStatuses.get(account.account_id); shortenedContent = shortenedStatusModel.getText(); } final StatusUpdate status = new StatusUpdate( shouldShorten && mUseShortener ? shortenedContent : unshortenedContent); 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.medias.length]; try { for (int i = 0, j = mediaIds.length; i < j; i++) { final ParcelableMediaUpdate media = statusUpdate.medias[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); final ContentLengthInputStream 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) { } catch (final TwitterException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); continue; } status.mediaIds(mediaIds); } status.setPossiblySensitive(statusUpdate.is_possibly_sensitive); if (twitter == null) { results.add(new SingleResponse<ParcelableStatus>(null, new NullPointerException())); continue; } try { final Status twitter_result = twitter.updateStatus(status); //Update Twitlonger statuses if (shouldShorten && mUseShortener && mShortener.equals(SERVICE_SHORTENER_TWITLONGER)) { TweetShortenerUtils.updateTwitlonger(shortenedStatusModel, twitter_result.getId(), twitter); } if (!notReplyToOther) { final long inReplyToUserId = twitter_result.getInReplyToUserId(); if (inReplyToUserId <= 0) { notReplyToOther = true; } } final ParcelableStatus result = new ParcelableStatus(twitter_result, account.account_id, false); results.add(new SingleResponse<ParcelableStatus>(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); } return results; }
From source file:edu.stanford.muse.slant.PostServlet.java
License:Apache License
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String text = request.getParameter("text"); Twitter twitter = (Twitter) JSPHelper.getSessionAttribute(request.getSession(), "twitter"); try {/* w w w .ja v a2 s . c o m*/ twitter.updateStatus(text); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
From source file:ens.demo.twitter.PostServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va2 s .c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String text = request.getParameter("text"); Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); try { StatusUpdate update = new StatusUpdate(text); twitter.updateStatus(update); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
From source file:ens.demo.twitter.TwittEmergencyMessage.java
@Override public void run() { try {/*from ww w . j a va2s . co m*/ if (toCustomer.getToken() == null || toCustomer.getToken().isEmpty()) { return; } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Properties properties = new Properties(); properties.load(classLoader.getResourceAsStream("twitter4j.properties")); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(properties.getProperty("twitter4j.oauth.consumerKey")) .setOAuthConsumerSecret(properties.getProperty("twitter4j.oauth.consumerSecret")) .setOAuthAccessToken(toCustomer.getToken()) .setOAuthAccessTokenSecret(toCustomer.getTokenSecret()); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); StatusUpdate update = new StatusUpdate(message); Status status = twitter.updateStatus(update); System.out.println("Successfully updated the status to [" + status.getText() + "]."); } catch (TwitterException ex) { Logger.getLogger(TwittEmergencyMessage.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TwittEmergencyMessage.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:entities.TwitterFeed.java
public void postTweet() { KeyReader keyreader = new KeyReader(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(keyreader.getConsumerKey()); cb.setOAuthConsumerSecret(keyreader.getConsumerSecret()); cb.setOAuthAccessToken(keyreader.getAccessToken()); cb.setOAuthAccessTokenSecret(keyreader.getAccessTokenSecret()); Twitter tf = new TwitterFactory(cb.build()).getInstance(); try {//from w w w. j a v a2 s .co m tf.updateStatus(typeTweet.getText()); System.out.println("tweet post success"); } catch (TwitterException te) { System.out.println("tweet post failed"); te.printStackTrace(); } }
From source file:erando.controllers.AddProductController.java
@FXML private void addProductAction(ActionEvent event) throws FileNotFoundException, IOException, TwitterException, DocumentException { Product p = new Product(); Sms sms = new Sms(); ISms smsservice = new SmsService(); IShopService productService = new ProductService(); Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY:MM/HH:mm:ss"); p.setTitre(pTitre.getText());//ww w.jav a2 s . c o m p.setPrix(Integer.parseInt(pPrix.getText())); p.setDescription(pDescription.getText()); p.setType(pType.getValue().toString()); p.setDate(sdf.format(cal.getTime())); p.setImage(imageName); if (!pTitre.getText().isEmpty() && !pPrix.getText().isEmpty() && !pDescription.getText().isEmpty() && !pType.getValue().toString().isEmpty()) { productService.add(p); ////////send sms to subs sms.setNum("" + Parameters.user.getNumTel()); sms.setMessagetel("Product Added To Store go check it !"); smsservice.sendSms(sms); ////////share on facebook (when asked by the owner ! ) if (shareFacebook.isSelected()) { String accessToken = "EAACEdEose0cBAKLtkZBKZCBoEkx4MApf3HxDMAR93PoJ6lAAuZAMdfY9vtob2ii78C6TN88hSV8HK0tDZBskaUz5pcbH1HqVeDRISuEHsG0qqUZBca4gHGnANPWcZBSZA9RNFHpbwVHJ46ITntn52SGQWetPPaZBsNlsFXbpcDrKytOVtmspQzfrM8GiUQtm1kQZD"; FacebookClient fbClient = new DefaultFacebookClient(accessToken, Version.LATEST); File fs = new File("C:\\Users\\F.Mouhamed\\Desktop\\Esprit\\ERandoPi\\userfiles\\"); fs.getParentFile().setExecutable(true); fs.getParentFile().setReadable(true); fs.getParentFile().setWritable(true); ////////FileInputStream fis = new FileInputStream(fs.getParentFile()); User me = fbClient.fetchObject("me", User.class); FacebookType response; response = fbClient.publish("me/feed", FacebookType.class, Parameter.with("message", p.getTitre() + "\n " + p.getDescription() + "\n Prix:" + p.getPrix())); } ////////share on twitter (when asked by the owner ! ) if (shareTwitter.isSelected()) { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("dHU6c4cXI6HDeLI3pakG8PYtp") .setOAuthConsumerSecret("n0NxZVXgpEMGJboWYBSD1nfbaa3Ov2qL0e9h2GzyUsa8wQ0q0p") .setOAuthAccessToken("729655065716346881-gukmKiOsT5WFv05t3yfQFrWgoPycQGD") .setOAuthAccessTokenSecret("4qTGW5YdG8j9biJeAybzIcivCPZaAOqES2PhoJI9S7WKL"); TwitterFactory tf = new TwitterFactory(cb.build()); twitter4j.Twitter tw = tf.getInstance(); String StatusMessage = ("Titre :" + p.getTitre() + "\nDescription:\n" + p.getDescription() + "\nPrix:" + p.getPrix()); StatusUpdate status = new StatusUpdate(StatusMessage); tw.updateStatus(status); } /////////show notification Notifications notificationBuilder = Notifications.create().title("sucess").text("produit ajouter") .graphic(null).hideAfter(Duration.seconds(4)).position(Pos.BOTTOM_RIGHT); notificationBuilder.darkStyle(); notificationBuilder.showConfirm(); /////////send emails to users subscribed to this type of product List<String> subs = productService.getSubscribes(p.getType()); mailToSubs mails = new mailToSubs(); for (String s : subs) { mails.envoyerfacture(s.toString(), p.getImage().toString(), p.getId(), p.getTitre(), p.getPrix(), p.getDescription()); } } }
From source file:es.portizsan.twitrector.tasks.TweetReplyTask.java
License:Open Source License
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { String message = null;/*w w w . j a va 2s .c om*/ if (req.getParameter("message") != null) { message = req.getParameter("message"); } else { logger.log(Level.WARNING, "message is null."); return; } long inReplyToStatusId = 0; if (req.getParameter("statusId") != null) { try { inReplyToStatusId = Long.parseLong(req.getParameter("statusId")); } catch (NumberFormatException nfe) { logger.log(Level.WARNING, "Invalid statusId.", nfe); return; } } else { logger.log(Level.WARNING, "statusId is null."); return; } try { logger.info("repling: " + message + " , " + inReplyToStatusId); Twitter twitter = new TwitterService().getTwitterInstance(); StatusUpdate su = new StatusUpdate(message); su.setInReplyToStatusId(inReplyToStatusId); twitter.updateStatus(su); } catch (TwitterException te) { logger.log(Level.WARNING, "Failed to search tweets: ", te); } }