Example usage for twitter4j QueryResult getTweets

List of usage examples for twitter4j QueryResult getTweets

Introduction

In this page you can find the example usage for twitter4j QueryResult getTweets.

Prototype

List<Status> getTweets();

Source Link

Usage

From source file:webServices.RestServiceImpl.java

@GET
@Path("/findTwittsRest")
@Produces({ MediaType.TEXT_PLAIN })/*from w w w. j av a2  s. c  om*/
public String twitterSearchRest(@QueryParam("keys") String searchKeys, @QueryParam("sinceId") long sinceId,
        @QueryParam("maxId") long maxId, @QueryParam("update") boolean update,
        @QueryParam("location") String location) {

    final Vector<String> results = new Vector<String>();
    String output = "";
    long higherStatusId = Long.MIN_VALUE;
    long lowerStatusId = Long.MAX_VALUE;

    Query searchQuery = new Query(searchKeys);
    searchQuery.setCount(50);
    searchQuery.setResultType(Query.ResultType.recent);

    if (sinceId != 0) {
        if (update) {
            searchQuery.setSinceId(sinceId);
        }
        higherStatusId = sinceId;
    }
    if (maxId != 0) {
        if (!update) {
            searchQuery.setMaxId(maxId);
        }
        lowerStatusId = maxId;
    }
    if (location != null) {
        double lat = Double.parseDouble(location.substring(0, location.indexOf(",")));
        double lon = Double.parseDouble(location.substring(location.indexOf(",") + 1, location.length()));

        searchQuery.setGeoCode(new GeoLocation(lat, lon), 10, Query.KILOMETERS);
    }

    try {
        QueryResult qResult = twitter.search(searchQuery);

        for (Status status : qResult.getTweets()) {
            //System.out.println(Long.toString(status.getId())+"  ***  "+Long.toString(status.getUser().getId())+"  ***  "+status.isRetweet()+"  ***  "+status.isRetweeted());

            higherStatusId = Math.max(status.getId(), higherStatusId);
            lowerStatusId = Math.min(status.getId(), lowerStatusId);

            if (!status.isRetweet()) {
                if (status.getGeoLocation() != null) {
                    System.out.println(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                    results.add(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                } else {
                    results.add(Long.toString(status.getId()) + "@null");
                }
            }
        }

    } catch (TwitterException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    TwitterResults resultsObj = new TwitterResults(results.toString(), higherStatusId, lowerStatusId);
    ObjectMapper mapper = new ObjectMapper();
    try {
        output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultsObj);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return output;
}

From source file:wedt.project.MainWindow.java

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
    statusLabel.setText("Trwa wyszukiwanie...");
    lockUI();/* ww w . j  a v a2 s  .  co  m*/
    SwingWorker<List<Status>, Void> worker = new SwingWorker<List<Status>, Void>() {

        @Override
        protected List<Status> doInBackground() throws Exception {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey("PG0vtiQ73sbKKCfp9JfqyQ")
                    .setOAuthConsumerSecret("ITCkTQiqCh3aVZexXentwnwCJooVpUOcpkIENPKowI")
                    .setOAuthAccessToken("89783194-z0J1KLudg6MFMhhysKmL29zB5wBjxfxWUboAh6lAI")
                    .setOAuthAccessTokenSecret("ytOdt7t8P1OrmAI2ZCRoX30ZC3eLcDSgPY8gOa6FCwQ");
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();

            try {
                Query query = new Query(searchField.getText());
                query.setCount(10);
                query.setLang("en");
                if (checkBoxLatest.isSelected() && checkBoxPopular.isSelected())
                    query.setResultType(Query.ResultType.mixed);
                else if (checkBoxLatest.isSelected())
                    query.setResultType(Query.ResultType.recent);
                else if (checkBoxPopular.isSelected())
                    query.setResultType(Query.ResultType.popular);

                QueryResult result = twitter.search(query);
                return result.getTweets();

            } catch (TwitterException e) {
                statusLabel.setText("Wyszukiwanie nie powiodlo sie");
                e.printStackTrace();
                //System.out.println("Failed to search tweets: " + te.getMessage());
                JOptionPane.showMessageDialog(null, e.getMessage(), "Blad pobierania wynikow wyszukiwania",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            return null;
        }

        @Override
        protected void done() {
            try {
                List<Status> tweets = get();
                listModel = new DefaultListModel();
                tweetsList.setModel(listModel);
                tweets.stream().forEach((tweet) -> {
                    listModel.addElement(tweet.getText());
                });
                statusLabel.setText("Gotowe");
            } catch (Exception ex) {
                ex.printStackTrace();
                statusLabel.setText("Wyszukiwanie nie powiodlo sie");
            }
            unlockUI();
        }
    };
    worker.execute();
}

From source file:wise.TwitterUtils.java

public ArrayList<CheckinObject> dataList(String cityCode, String selectedDate, String maxTweetParam,
        String topTweetParam) throws IOException, JSONException, ParseException {
    ArrayList<CheckinObject> checkinList = new ArrayList<>();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.CONSUMER_KEY)
            .setOAuthConsumerSecret(Constants.CONSUMER_SECRET).setOAuthAccessToken(Constants.TOKEN)
            .setOAuthAccessTokenSecret(Constants.TOKEN_SECRET);

    Integer maxTweet = Integer.parseInt(maxTweetParam);
    Integer topTweet = Integer.parseInt(topTweetParam);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();/*from www . j av  a 2  s  .  com*/

    DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);

    Date startDate = format.parse(selectedDate);

    Calendar c = Calendar.getInstance();
    c.setTime(startDate);
    c.add(Calendar.DATE, 1);
    Date endDate = c.getTime();

    Query query = SetQueryString(cityCode, startDate, endDate);

    QueryResult result = null;
    try {
        while (query != null && checkinList.size() <= maxTweet) {
            result = twitter.search(query);
            if (result != null) {
                for (Status status : result.getTweets()) {

                    for (URLEntity urlEntity : status.getURLEntities()) {
                        String urlCheckinId = urlEntity.getExpandedURL()
                                .substring(urlEntity.getExpandedURL().lastIndexOf("/") + 1);
                        GeoLocation geo = status.getGeoLocation();

                        CheckinObject checkin = new CheckinObject();
                        checkin.CheckinId = urlCheckinId;
                        checkin.Count = 1;//status.getRetweetCount() + status.getFavoriteCount() + 1;
                        checkin.Latitude = geo.getLatitude();
                        checkin.Longitude = geo.getLongitude();

                        if (!checkin.containsSameCoordinates(checkinList, checkin.Latitude,
                                checkin.Longitude)) {
                            checkinList.add(checkin);
                        } else {
                            int indexOfCheckinId = checkin.getIndexByCoordinates(checkinList, checkin.Latitude,
                                    checkin.Longitude);
                            checkinList.get(indexOfCheckinId).setCheckinCount(checkin.Count);
                            checkinList.get(indexOfCheckinId).setReplacementCheckinId(checkin.CheckinId);
                        }
                    }
                }

                query = result.nextQuery();
            } else {
                query = null;
            }
        }

    } catch (TwitterException e) {
    }

    Collections.sort(checkinList, new CountComparator());

    if (checkinList.size() > topTweet) {
        checkinList.subList(topTweet, checkinList.size()).clear(); // get top x
    }

    FourSquareCheckin fsq = new FourSquareCheckin();

    for (CheckinObject checkin : checkinList) {
        fsq = getVenueInfo(checkin);
        checkin.LocationName = fsq.VenueName;
        checkin.Image = fsq.VenueImage;
    }

    return checkinList;
}