Example usage for twitter4j Twitter createFavorite

List of usage examples for twitter4j Twitter createFavorite

Introduction

In this page you can find the example usage for twitter4j Twitter createFavorite.

Prototype

Status createFavorite(long id) throws TwitterException;

Source Link

Document

Favorites the status specified in the ID parameter as the authenticating user.

Usage

From source file:br.shura.team.mpsbot.venusext.Like.java

License:Open Source License

@Override
public void callVoid(Context context, FunctionCallDescriptor descriptor) throws ScriptRuntimeException {
    ConnectedBot bot = context.getApplicationContext().getUserData("bot", ConnectedBot.class);
    Twitter twitter = bot.getHandler();
    IntegerValue value = (IntegerValue) descriptor.get(0);

    Helper.execute(context, () -> twitter.createFavorite(value.value()));
}

From source file:com.daiv.android.twitter.ui.tweet_viewer.fragments.TweetFragment.java

License:Apache License

public void favoriteStatus(final TextView favs, final View favButton, final long tweetId, final int type) {
    if (isFavorited) {
        Toast.makeText(context, getResources().getString(R.string.removing_favorite), Toast.LENGTH_SHORT)
                .show();//from   w w w  . j a  va2  s  . co m
    } else {
        Toast.makeText(context, getResources().getString(R.string.favoriting_status), Toast.LENGTH_SHORT)
                .show();
    }

    new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                Twitter twitter = null;
                Twitter secTwitter = null;
                if (type == TYPE_ACC_ONE) {
                    twitter = Utils.getTwitter(context, settings);
                } else if (type == TYPE_ACC_TWO) {
                    secTwitter = Utils.getSecondTwitter(context);
                } else {
                    twitter = Utils.getTwitter(context, settings);
                    secTwitter = Utils.getSecondTwitter(context);
                }

                if (isFavorited && twitter != null) {
                    twitter.destroyFavorite(tweetId);
                } else if (twitter != null) {
                    try {
                        twitter.createFavorite(tweetId);
                    } catch (TwitterException e) {
                        // already been favorited by this account
                    }
                }

                if (secTwitter != null) {
                    try {
                        secTwitter.createFavorite(tweetId);
                    } catch (TwitterException e) {

                    }
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getResources().getString(R.string.success),
                                    Toast.LENGTH_SHORT).show();
                            getFavoriteCount(favs, favButton, tweetId);
                        } catch (Exception e) {
                            // they quit out of the activity
                        }
                    }
                });
            } catch (Exception e) {

            }
        }
    }).start();
}

From source file:com.klinker.android.twitter.ui.tweet_viewer.fragments.TweetFragment.java

License:Apache License

public void favoriteStatus(final TextView favs, final View favButton, final long tweetId) {
    if (!isFavorited) {
        Toast.makeText(context, getResources().getString(R.string.favoriting_status), Toast.LENGTH_SHORT)
                .show();/*from  w  w  w  .j a  v  a  2  s. co m*/
    } else {
        Toast.makeText(context, getResources().getString(R.string.removing_favorite), Toast.LENGTH_SHORT)
                .show();
    }

    new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                if (isFavorited) {
                    twitter.destroyFavorite(tweetId);
                } else {
                    twitter.createFavorite(tweetId);
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getResources().getString(R.string.success),
                                    Toast.LENGTH_SHORT).show();
                            getFavoriteCount(favs, favButton, tweetId);
                        } catch (Exception e) {
                            // they quit out of the activity
                        }
                    }
                });
            } catch (Exception e) {

            }
        }
    }).start();
}

From source file:com.twitstreet.twitter.AnnouncerMgrImpl.java

License:Open Source License

@Override
public void favourite(long statusId) {
    Twitter twitter = random();
    String screenName = "";
    try {// www.  j a  va 2  s  .  co m
        twitter.createFavorite(statusId);
        screenName = twitter.getScreenName();
    } catch (TwitterException e) {
        logger.error("Error while creating favorite: " + statusId + " Announcer: " + screenName, e);
    }
}

From source file:com.twitstreet.twitter.AnnouncerMgrImpl.java

License:Open Source License

@Override
public void favouriteForDiabloBird(long statusId) {
    Twitter twitter = diablobird;
    String screenName = "";
    try {//from www.  ja va  2 s  .c o  m
        twitter.createFavorite(statusId);
        screenName = twitter.getScreenName();
        logger.info("favouriteForDiabloBird");
    } catch (TwitterException e) {
        logger.error("Error while creating favorite: " + statusId + " Announcer: " + screenName, e);
    }
}

From source file:ikemen.Main.java

License:Apache License

public static void main(String[] args) {
    final Twitter twitter = TwitterFactory.getSingleton();
    final TwitterStream stream = TwitterStreamFactory.getSingleton();
    stream.addListener(new UserStreamAdapter() {
        public void onStatus(Status status) {
            if (yonda(status.getText())) {
                try {
                    twitter.createFavorite(status.getId());
                } catch (TwitterException ignore) {
                }/*from  ww w .  j av a 2  s.co m*/
                try {
                    twitter.sendDirectMessage("yusuke", "http://twitter.com/yusuke/status/" + status.getId());
                } catch (TwitterException ignore) {
                }
            }
        }
    });
    stream.user();
}

From source file:jp.gihyo.wicket.page.ajax.AjaxTimeline.java

License:Apache License

private void constructPage() {
    final TweetForm form = new TweetForm("tweetForm");
    add(form);//from   ww  w  . jav  a  2 s .c o m

    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    add(feedback);

    IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() {
        @Override
        protected List<Status> load() {
            try {
                Twitter twitter = AppSession.get().getTwitterSession();
                return twitter.getFriendsTimeline(new Paging(currentPageNumber, ITEMS_PER_PAGE));
            } catch (TwitterException ex) {
                AjaxTimeline.this.error(getString("canNotRetrieveFriendTimeline"));
                return Collections.emptyList();
            }
        }
    };

    ListView<Status> timeline = new ListView<Status>("statusView", statusModel) {
        @Override
        protected void populateItem(final ListItem<Status> item) {
            final Status status = item.getModelObject();
            String userUrl = "http://twitter.com/" + status.getUser().getScreenName();
            ExternalLink imageLink = new ExternalLink("imageLink", userUrl);

            //ImageR|?[lg?A<img>^Osrc??X`?X
            WebMarkupContainer userImage = new WebMarkupContainer("userImage");
            userImage.add(new SimpleAttributeModifier("src", status.getUser().getProfileImageURL().toString()));

            imageLink.add(userImage);
            item.add(imageLink);

            ExternalLink screenNameLink = new ExternalLink("screenName", userUrl,
                    status.getUser().getScreenName());
            item.add(screenNameLink);

            Label content = new Label("tweetContent", status.getText());
            item.add(content);

            ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null);
            item.add(tweetLink);

            Label time = new Label("tweetTime",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt()));
            tweetLink.add(time);

            Label clientName = new Label("clientName", status.getSource());
            item.add(clientName.setEscapeModelStrings(false));

            /*
             * YXe?[^XCo^\xNX?B
             * ?\bh?A??[JNX`?B
             * ??[JNX?ANXOstatus?ANZX?B
             */
            class FavorateLabel extends Label {
                private static final long serialVersionUID = -2194580825236126312L;
                private Status targetStatus;
                private boolean needRefresh;

                public FavorateLabel(String id) {
                    super(id);
                    this.targetStatus = status;

                    setDefaultModel(new AbstractReadOnlyModel<String>() {
                        @Override
                        public String getObject() {
                            try {
                                if (needRefresh) {
                                    targetStatus = getCurrentStatus(status.getId());
                                    needRefresh = false;
                                }
                                return targetStatus == null ? "" : targetStatus.isFavorited() ? "unfav" : "fav";
                            } catch (TwitterException ex) {
                                LOGGER.error("Can not fetch current status for status id = " + status.getId(),
                                        ex);
                                return "error";
                            }
                        }
                    });
                }

                public void setNeedRefresh(boolean needRefresh) {
                    this.needRefresh = needRefresh;
                }
            }

            //CNx
            final FavorateLabel favName = new FavorateLabel("favName");
            favName.setOutputMarkupId(true);

            /*
             * AjaxCN?B
             * Xe?[^XCo^o^?Ao^???s?B
             * o^???AAjaxg?Ay?[WS?ACo^Xe?[^X
             * Nx??B
             */
            AjaxLink<Void> favLink = new AjaxLink<Void>("favLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        Status currentStatus = getCurrentStatus(status.getId());
                        Twitter twitterSession = AppSession.get().getTwitterSession();
                        if (currentStatus.isFavorited()) {
                            twitterSession.destroyFavorite(currentStatus.getId());
                            info(getString("favorateRemoved"));
                        } else {
                            twitterSession.createFavorite(currentStatus.getId());
                            info(getString("favorateRegistered"));
                        }
                        favName.setNeedRefresh(true);
                        target.addComponent(feedback); //o^?bZ?[W\?AtB?[hobNpl?X?V?B
                        target.addComponent(favName);
                    } catch (TwitterException ex) {
                        String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode();
                        error(message);
                        LOGGER.error(message, ex);
                    }
                }
            };
            item.add(favLink);
            favLink.add(favName);

            //AJAX LINK
            item.add(new AjaxLink<Void>("replyLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    String targetScreenName = status.getUser().getScreenName();
                    form.insertText(target, "@" + targetScreenName + " ");
                }
            });

            //Q?l?AreplyLinkJavaScriptp
            //                item.add(new Link<Void>("replyLink") {
            //                    @Override
            //                    public void onClick() {
            //                    }
            //
            //                    @Override
            //                    protected CharSequence getOnClickScript(CharSequence url) {
            //                        return "getElementById('" + form.getTextAreaId() + "').value = '@" + status.getUser().getScreenName() + " ';" +
            //                               "getElementById('" + form.getTextAreaId() + "').focus(); return false;";
            //                    }
            //                });
        }
    };

    //ListView\e?s????BreuseItemsv?peB??A
    //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B
    //twitterey?[We?X??AXg????AXge?
    //Xe?[^Xu?A??dv?B
    timeline.setReuseItems(true);
    add(timeline);

    /*
     * y?[WO?EirQ?[^
     */
    add(new PagingLink("paging", AjaxTimeline.class, new AbstractReadOnlyModel<Integer>() {
        @Override
        public Integer getObject() {
            return getCurrentPage();
        }
    }));
}

From source file:jp.gihyo.wicket.page.paging.PagingTimeline.java

License:Apache License

private void constructPage() {
    final TweetForm form = new TweetForm("tweetForm");
    add(form);//from www .  j a  v a2  s  . com

    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    add(feedback);

    /*
     * ^CCpIModel?B
     * ??[hf?[^NGXg?EX|X?ETCNLbV?A
     * LoadableDetachableModelNXgp?B
     */
    IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() {
        @Override
        protected List<Status> load() {
            try {
                Twitter twitter = AppSession.get().getTwitterSession();
                return twitter.getFriendsTimeline(new Paging(currentPageNumber, ITEMS_PER_PAGE));
            } catch (TwitterException ex) {
                PagingTimeline.this.error(getString("canNotRetrieveFriendTimeline"));
                return Collections.emptyList();
            }
        }
    };

    /*
     * ^CCXg
     */
    ListView<Status> timeline = new ListView<Status>("statusView", statusModel) {
        @Override
        protected void populateItem(final ListItem<Status> item) {
            final Status status = item.getModelObject();
            String userUrl = "http://twitter.com/" + status.getUser().getScreenName();
            ExternalLink imageLink = new ExternalLink("imageLink", userUrl);

            //ImageR|?[lg?A<img>^Osrc??X`?X
            WebMarkupContainer userImage = new WebMarkupContainer("userImage");
            userImage.add(new SimpleAttributeModifier("src", status.getUser().getProfileImageURL().toString()));

            imageLink.add(userImage);
            item.add(imageLink);

            ExternalLink screenNameLink = new ExternalLink("screenName", userUrl,
                    status.getUser().getScreenName());
            item.add(screenNameLink);

            Label content = new Label("tweetContent", status.getText());
            item.add(content);

            ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null);
            item.add(tweetLink);

            Label time = new Label("tweetTime",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt()));
            tweetLink.add(time);

            Label clientName = new Label("clientName", status.getSource());
            item.add(clientName.setEscapeModelStrings(false));

            /*
             * CNx?BIModel?f?A?fav/unfav
             * \?B
             */
            final Label favName = new Label("favName", new AbstractReadOnlyModel<String>() {
                @Override
                public String getObject() {
                    return status.isFavorited() ? "unfav" : "fav";
                }
            });

            /*
             * CN?BNbN?C?E??s?B
             */
            Link<Void> favLink = new Link<Void>("favLink") {
                @Override
                public void onClick() {
                    try {
                        Twitter twitterSession = AppSession.get().getTwitterSession();
                        if (status.isFavorited()) {
                            twitterSession.destroyFavorite(status.getId());
                            info(getString("favorateRemoved"));
                        } else {
                            twitterSession.createFavorite(status.getId());
                            info(getString("favorateRegistered"));
                        }
                    } catch (TwitterException ex) {
                        String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode();
                        error(message);
                        LOGGER.error(message, ex);
                    }
                }
            };
            item.add(favLink);
            favLink.add(favName);

            /*
             * vCpN?B
             * ?u@screenName?v?B
             */
            item.add(new Link<Void>("replyLink") {
                @Override
                public void onClick() {
                    String targetScreenName = status.getUser().getScreenName();
                    form.insertText("@" + targetScreenName + " ");
                }
            });
        }
    };

    //ListView\e?s????BreuseItemsv?peB??A
    //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B
    //twitterey?[We?X??AXg????AXge?
    //Xe?[^Xu?A??dv?B
    timeline.setReuseItems(true);

    add(timeline);

    /*
     * y?[WO?EirQ?[^
     */
    add(new PagingLink("paging", PagingTimeline.class, new AbstractReadOnlyModel<Integer>() {
        @Override
        public Integer getObject() {
            return getCurrentPage();
        }
    }));
}

From source file:jp.gihyo.wicket.page.simple.MyTimeline.java

License:Apache License

private void constructPage() {
    final TweetForm form = new TweetForm("tweetForm");
    add(form);/*from  www.  j av a2  s.  c om*/

    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    add(feedback);

    /*
     * ^CCpIModel?B
     * ??[hf?[^NGXg?EX|X?ETCNLbV?A
     * LoadableDetachableModelNXgp?B
     */
    IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() {
        @Override
        protected List<Status> load() {
            try {
                Twitter twitter = AppSession.get().getTwitterSession();
                return twitter.getFriendsTimeline(new Paging(1, ITEMS_PER_PAGE));
            } catch (TwitterException ex) {
                MyTimeline.this.error(getString("canNotRetrieveFriendTimeline"));
                return Collections.emptyList();
            }
        }
    };

    /*
     * ^CCXg
     */
    ListView<Status> timeline = new ListView<Status>("statusView", statusModel) {
        @Override
        protected void populateItem(final ListItem<Status> item) {
            final Status status = item.getModelObject();
            String userUrl = "http://twitter.com/" + status.getUser().getScreenName();
            ExternalLink imageLink = new ExternalLink("imageLink", userUrl);
            byte[] byteArray = {};/* f?[^?? */
            UrlResourceStream stream = new UrlResourceStream(status.getUser().getProfileImageURL());
            try {
                stream.getInputStream().read(byteArray);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ResourceStreamNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Image userImage = new Image("userImage", new ByteArrayResource("image/jpeg", byteArray));
            imageLink.add(userImage);
            item.add(imageLink);

            ExternalLink screenNameLink = new ExternalLink("screenName", userUrl,
                    status.getUser().getScreenName());
            item.add(screenNameLink);

            Label content = new Label("tweetContent", status.getText());
            item.add(content);

            ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null);
            item.add(tweetLink);

            Label time = new Label("tweetTime",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt()));
            tweetLink.add(time);

            Label clientName = new Label("clientName", status.getSource());
            item.add(clientName.setEscapeModelStrings(false));

            /*
             * CNx?BIModel?f?A?fav/unfav
             * \?B
             */
            final Label favName = new Label("favName", new AbstractReadOnlyModel<String>() {
                @Override
                public String getObject() {
                    return status.isFavorited() ? "unfav" : "fav";
                }
            });

            /*
             * CN?BNbN?C?E??s?B
             */
            Link<Void> favLink = new Link<Void>("favLink") {
                @Override
                public void onClick() {
                    try {
                        Twitter twitterSession = AppSession.get().getTwitterSession();
                        if (status.isFavorited()) {
                            twitterSession.destroyFavorite(status.getId());
                            info(getString("favorateRemoved"));
                        } else {
                            twitterSession.createFavorite(status.getId());
                            info(getString("favorateRegistered"));
                        }
                    } catch (TwitterException ex) {
                        String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode();
                        error(message);
                        LOGGER.error(message, ex);
                    }
                }
            };
            item.add(favLink);
            favLink.add(favName);

            /*
             * vCpN?B
             * ?u@screenName?v?B
             */
            item.add(new Link<Void>("replyLink") {
                @Override
                public void onClick() {
                    String targetScreenName = status.getUser().getScreenName();
                    form.insertText("@" + targetScreenName + " ");
                }
            });
        }
    };
    //ListView\e?s????BreuseItemsv?peB??A
    //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B
    //twitterey?[We?X??AXg????AXge?
    //Xe?[^Xu?A??dv?B
    timeline.setReuseItems(true);

    add(timeline);
}

From source file:kerguelenpetrel.RespondServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    StringBuilder builder = new StringBuilder();
    resp.setContentType("text/plain; charset=UTF-8");

    try {//w ww .j ava  2  s  .co m
        //Get the Twitter object
        Twitter twit = TwitterFactory.getSingleton();
        ResponseList<Status> mentions = twit.getMentionsTimeline();

        lastPostIdEntity = datastore.get(KeyFactory.createKey("lastPostIDEntity", "ID"));
        lastPostId = Long.parseLong(lastPostIdEntity.getProperty("lastPostID").toString());

        if (mentions.size() == 0) {
            resp.getWriter().println("No mentions so far...\n");
            return;
        }

        for (Status mention : mentions) {
            if (lastPostId < mention.getId()) {
                if (mention.getUser().getId() == twit.getId())
                    ; //don't respond to myself

                else if (mention.isRetweeted())
                    mention = twit.createFavorite(mention.getId()); //mark the retweet as a favourite
                else if (mention.getText().toLowerCase().contains("bye")) {
                    builder.setLength(0);
                    builder.append("@");
                    builder.append(mention.getUser().getScreenName());
                    builder.append(" Bye");
                } else {
                    builder.setLength(0);
                    //Add the screen name of the person we are responding to
                    builder.append("@");
                    builder.append(mention.getUser().getScreenName() + " ");

                    //Get feed title as content
                    builder.append(getFeedTitle(resp));

                    //Get a Wordnik trend
                    builder.append(getWordnikTrend(resp));

                    /* Tweets are maximum 280 characters */
                    if (builder.length() > 280) {
                        builder.setLength(builder.lastIndexOf(" ", 270));
                        builder.append(end[(r.nextInt(end.length))]);
                    }
                }
                //Set the status
                StatusUpdate status = new StatusUpdate(builder.toString());

                //Post the status
                twit.updateStatus(status);
                resp.getWriter().println("Tweet posted: " + status.getStatus());
            }
        }
        //Save last post ID
        lastPostIdEntity.setProperty("lastPostID", (Long.toString(mentions.get(0).getId())));
        datastore.put(lastPostIdEntity);
    } catch (EntityNotFoundException e) {
        // Make new ResponseIDentity
        lastPostIdEntity = new Entity("lastPostIDEntity", "ID");
        lastPostIdEntity.setProperty("lastPostID", "0");
        datastore.put(lastPostIdEntity);
        resp.getWriter()
                .println("Made new lastPostId " + lastPostIdEntity.getProperty("lastPostID").toString());
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter \n");
        e.printStackTrace(resp.getWriter());
    }
}