Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

In this page you can find the example usage for twitter4j Status getUser.

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file:mitwitter.MiTwitter.java

/**
 * @param args the command line arguments
 *///from   w w w .j a v a 2s  .  c o m
public static void main(String[] args) throws TwitterException {
    // TODO code application logic here

    //camobios

    Twitter twitter = new TwitterFactory().getInstance();

    //CODIGO CAMBIAR ESTADO
    Status miStatus = twitter.updateStatus("Tercer ejemplo");//cambia el estado de twitter
    System.out.println(miStatus.getText());

    //CODIGO TIMELINE
    List<Status> statuses = twitter.getHomeTimeline();
    System.out.println("Showing home timeline.");//aparecen los ultimos twitts
    for (Status status : statuses) {
        System.out.println(status.getUser().getName() + ":" + status.getText());
    }

    //CODIGO BUSCAR TAGS
    Query query = new Query("Chelsea"); //Dentro del String va el tag que quieres buscar
    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
    }

}

From source file:moderation.Moderate.java

public List getTwitterpost() {

    List posts = new ArrayList();
    try {//  ww w .j a  v  a  2s . com
        List savedpost = getSavedList(album_id);
        String tagname = this.hash;
        Twitter twitter = setting.TwitterToken.twitterObject();
        Query query = new Query(tagname);
        query.setCount(50);
        QueryResult result;
        result = twitter.search(query);
        List<Status> tweets = result.getTweets();
        for (Status tweet : tweets) {
            System.out.println("\n\n\n" + tweet);
            PostModel post = new PostModel();
            post.setAlbum_id(this.album_id);
            if (savedpost.contains(tweet.getId()))
                post.setStatus("old");
            else
                post.setStatus("new");
            post.setPost_id("" + tweet.getId());
            post.setSender_name(URLEncoder.encode(tweet.getUser().getScreenName(), "UTF-8"));
            post.setCaption_text(URLEncoder.encode(tweet.getText(), "UTF-8"));
            post.setSender_pic(tweet.getUser().getProfileImageURL());
            post.setSender_id("" + tweet.getUser().getId());

            for (MediaEntity mediaEntity : tweet.getMediaEntities()) {
                post.setImage_standard(mediaEntity.getMediaURL());
                post.setImage_low(mediaEntity.getMediaURL());
            }
            post.setPost_time(tweet.getCreatedAt().toString());
            post.setType("twitter_post");
            post.setLink(null);
            post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id() + "&type="
                    + post.getType() + "&post_time=" + post.getPost_time() + "&link=" + post.getLink()
                    + "&pic_low=" + post.getImage_low() + "&pic_standard=" + post.getImage_standard()
                    + "&post_message=" + post.getCaption_text() + "&sender_name=" + post.getSender_name()
                    + "&sender_id=" + post.getSender_id() + "&sender_pic=" + post.getSender_pic());

            posts.add(post);

        }
        this.twitternext = result.nextQuery();

    } catch (Exception e) {
        System.err.println("Exception occure in getTwitter " + e);
    }

    return posts;
}

From source file:module.ihm.MainFrameInitializer.java

public void initJList() {
    JList jList = (JList) application.getMainFrameJComponent("jListTweet");
    DefaultListModel model = new DefaultListModel();
    jList.setCellRenderer(new ListCellRenderer() {

        @Override//from ww  w . j a  va 2  s.c o  m
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            JLabel renderer = (JLabel) new DefaultListCellRenderer().getListCellRendererComponent(list, value,
                    index, isSelected, cellHasFocus);
            if (value instanceof Status) {
                Status s = (Status) value;
                renderer.setForeground(new Color(0, 51, 102));
                try {
                    renderer.setIcon(new ImageIcon(new URL(s.getUser().getProfileImageURL().toString())));
                } catch (MalformedURLException ex) {
                    Logger.getLogger(MainFrameInitializer.class.getName()).log(Level.SEVERE, null, ex);
                }
                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                renderer.setText("<html><b>" + s.getUser().getName() + " @" + s.getUser().getScreenName()
                        + "</b><br>" + s.getText() + "<br>" + "Ecrit le " + dateformat.format(s.getCreatedAt())
                        + "<br><br> </html>");
            }
            if (value instanceof twitter4j.User) {
                twitter4j.User u = (twitter4j.User) value;
                try {
                    renderer.setIcon(new ImageIcon(new URL(u.getProfileImageURL().toString())));
                } catch (MalformedURLException ex) {
                    Logger.getLogger(MainFrameInitializer.class.getName()).log(Level.SEVERE, null, ex);
                }

                renderer.setText(u.getName() + " @" + u.getScreenName());
            }
            return renderer;
        }
    });
    jList.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            JList jList = (JList) application.getMainFrameJComponent("jListTweet");
            if (jList.getSelectedValue() instanceof Status) {
                Status s = (Status) jList.getSelectedValue();
                //                  System.out.println(s);
                PandaProdButton button = (PandaProdButton) hsJcomponent.get("pandaProdButtonRetweet");
                button.setVisible(true);

            } else if (jList.getSelectedValue() instanceof twitter4j.User) {
                twitter4j.User s = (twitter4j.User) jList.getSelectedValue();
                //                    System.out.println(s);
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    });

    for (Status s : user.getListOfTweet()) {
        model.addElement(s);
    }

    jList.setModel(model);

}

From source file:monitoring.tools.TwitterAPI.java

License:Apache License

private void resetStream() {
    //logger.debug("Initialising kafka producer...");
    //kafka.initProducer(confParams.getKafkaEndpoint());
    logger.debug("Initialising proxy...");
    kafka.initProxy(confParams.getKafkaEndpoint());
    logger.debug("Initialising streaming...");
    firstConnection = true;//from   w w w  .  j  a  v a  2 s.c  om
    tweetInfo = new ArrayList<>();
    stream = new TwitterStreamFactory().getInstance();
    timer = new Timer();
    stream.onStatus(new Consumer<Status>() {
        @Override
        public void accept(Status arg0) {
            if (confParams.getAccounts() != null && !confParams.getAccounts().isEmpty()) {
                if (confParams.getAccounts().contains(arg0.getUser().getScreenName())) {
                    tweetInfo.add(arg0);
                }
            } else
                tweetInfo.add(arg0);
        }
    });
    stream.addConnectionLifeCycleListener(new ConnectionLifeCycleListener() {
        @Override
        public void onCleanUp() {
        }

        @Override
        public void onConnect() {
            logger.debug("Connection established successfully");
            timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    if (firstConnection) {
                        firstConnection = false;
                    } else {
                        generateData((new Timestamp((new Date()).getTime()).toString()));
                    }
                }
            }, 0, Integer.parseInt(confParams.getTimeSlot()) * 1000);
        }

        @Override
        public void onDisconnect() {
            logger.debug("Connection closed");
        }
    });

    FilterQuery filterQuery = new FilterQuery();
    if (this.confParams.getKeywordExpression() != null)
        filterQuery.track(Utils.generateKeywordExp(this.confParams.getKeywordExpression()));
    stream.filter(filterQuery);
}

From source file:monitoring.tools.TwitterAPI.java

License:Apache License

private void generateData(String searchTimeStamp) {

    List<MonitoringData> data = new ArrayList<>();
    for (Status s : tweetInfo) {
        String id = String.valueOf(s.getId());
        String timeStamp = String.valueOf(s.getCreatedAt());
        String message = s.getText();
        String author = "@" + s.getUser().getScreenName();
        String link = "https://twitter.com/" + s.getUser().getName().replace(" ", "") + "/status/" + s.getId();
        MonitoringData dataObj = new MonitoringData(id, timeStamp, message, author, link);
        data.add(dataObj);/*from   ww  w .j  a va 2 s.  c om*/
    }
    tweetInfo = new ArrayList<>();
    //kafka.generateResponseKafka(data, searchTimeStamp, id, configurationId, this.confParams.getKafkaTopic);
    kafka.generateResponseIF(data, searchTimeStamp, id, configurationId, this.confParams.getKafkaTopic());
    logger.debug("Data successfully sent to Kafka endpoint");
    ++id;
}

From source file:my.twittergui.TwitterUI.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    String text;//from  www  . ja v a  2 s. co  m
    text = jTextField1.getText();
    //jTextArea1.append(text+"\n");
    jTextArea1.append("Searching for: ");
    String[] strarray = text.split(" ");
    for (int i = 0; i < strarray.length; i++) {
        jTextArea1.append(strarray[i] + "\n");
    }

    File filed = null;
    filed = new File("C:\\Results");
    if (!filed.exists()) {
        filed.mkdir();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("")
            .setOAuthAccessTokenSecret("");

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {

            try {

                int fileno = 0;
                String strI = Integer.toString(fileno);
                String fname = "C:\\results\\DataCol" + strI + ".csv";
                File file = new File(fname);
                FileWriter bw = new FileWriter(file, true);

                if (file.length() == 0) {
                    bw.write("\"Screen Name\", text, \"created at\", geolocation, Retweet? \r\n");
                    bw.flush();
                }
                while (file.length() > 10485760) {
                    fileno += 1;
                    strI = Integer.toString(fileno);
                    fname = "DataCol" + strI + ".txt";
                    file = new File(fname);
                    bw = new FileWriter(file, true);
                    bw.write("\"Screen Name\", \"text\", \"created_at\", \"geolocation\" \r\n");
                    bw.flush();

                }

                // if(!status.isRetweet()){
                bw.write("\r\n");
                bw.write("\"" + status.getUser().getScreenName() + "\",");
                String tweettxt = status.getText();
                tweettxt = tweettxt.replace("\n", "");
                tweettxt = tweettxt.replace(",", "");
                tweettxt = tweettxt.replace("\"", "");
                bw.write("\"" + tweettxt + "\",");

                bw.write("\"" + status.getCreatedAt() + "\",");
                if (status.getGeoLocation() != null) {
                    bw.write("\"" + status.getGeoLocation() + "\"");
                } else
                    bw.write("N/A,");
                if (status.isRetweet())
                    bw.write("Yes");
                else
                    bw.write("No");

                bw.flush();

                bw.close();
                //System.out.print("\n");
                String str = "@" + status.getUser().getScreenName() + "  " + status.getText() + " "
                        + status.getCreatedAt() + " ";
                if (status.getGeoLocation() != null)
                    str += status.getGeoLocation();
                //System.out.print(str);
                jTextArea1.append(str + "\n");
                // }

                bw.close();
            } catch (IOException e) {
                //System.out.print("EXCEPTION");
                e.printStackTrace();
            }

        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onStallWarning(StallWarning stall) {
        }

        public void onScrubGeo(long a, long b) {
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };
    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    TwitterStream twitterStream = tf.getInstance();
    twitterStream.addListener(listener);
    // Filter
    FilterQuery filtre = new FilterQuery();
    Scanner in = new Scanner(System.in);

    filtre.track(strarray);
    twitterStream.filter(filtre);

}

From source file:net.craftrepo.CraftBird.TwitterUpdates.java

License:Open Source License

public void run() {
    while (true) {
        if (CraftBird.twitter.getAuthorization().isEnabled()) {
            net.craftrepo.CraftBird.CraftBird.config.load();
            String[] users = ((String[]) net.craftrepo.CraftBird.CraftBird.config.getProperty("users"));
            if (users == null) {
                CraftBird.log.warning("[Twitter] No users defined in the config! Turning updates off.");
                CraftBird.updates = false;
                CraftBird.scheduler.cancelAllTasks();
                return;
            }//from   w  w w .ja va 2s . com
            for (String s : users) {
                try {
                    List<Status> statuses;
                    statuses = CraftBird.twitter.getFriendsTimeline();
                    if (lastStatuses == null || !statuses.containsAll(lastStatuses)) {
                        for (Status status : statuses) {
                            if (status.getUser().getName().contains(s)) {
                                CraftBird.log.info(
                                        "[Twitter] " + status.getUser().getName() + ":" + status.getText());
                                CraftBird.notifyPlayers(
                                        "[Twitter] " + status.getUser().getName() + ":" + status.getText());
                            }
                        }
                        lastStatuses = statuses;
                    }
                } catch (TwitterException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:net.lacolaco.smileessence.command.status.StatusCommandCongratulate.java

License:Open Source License

public String build() {
    Status status = getOriginalStatus();
    int favCount;
    Random rand = new Random();
    int r = rand.nextInt(100);
    if (r < 50) {
        favCount = 50;/*from w ww  .j  a v  a2 s  . c  o m*/
    } else if (r < 80) {
        favCount = 100;
    } else if (r < 90) {
        favCount = 250;
    } else if (r < 99) {
        favCount = 1000;
    } else {
        favCount = 10000;
    }
    return String.format("@%s Congrats on your %s  tweet! http://favstar.fm/t/%s",
            status.getUser().getScreenName(), favCount, status.getId());
}

From source file:net.lacolaco.smileessence.command.status.StatusCommandNanigaja.java

License:Open Source License

public String build() {
    Status status = getOriginalStatus();
    String str = status.getText();
    String header = "";
    if (str.startsWith(".")) {
        str = str.replaceFirst(".", "");
    }/*  ww  w  . j a  v a 2 s .co  m*/
    if (str.startsWith(String.format("@%s", account.screenName))) {
        str = str.replaceFirst(String.format("@%s", account.screenName), "").trim();
        header = "@" + status.getUser().getScreenName();
    }
    str = String.format("%s %s", header, String.format(getFormatString(getActivity()), str)).trim();
    return str;
}

From source file:net.lacolaco.smileessence.twitter.TweetBuilder.java

License:Open Source License

public TweetBuilder setQuotation(Status status) {
    return setText(String.format(" RT @%s: %s", status.getUser().getScreenName(), status.getText()));
}