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:org.botlibre.sense.twitter.Twitter.java

License:Open Source License

/**
 * Check search keywords.//  ww  w .j av a  2s  .  co m
 */
public void checkAutoFollowSearch(int friendCount) {
    if (getAutoFollowSearch().isEmpty()) {
        return;
    }
    log("Processing autofollow search", Level.FINE, getAutoFollowSearch());
    try {
        Network memory = getBot().memory().newMemory();
        Vertex twitter = memory.createVertex(getPrimitive());
        Vertex vertex = twitter.getRelationship(Primitive.LASTAUTOFOLLOWSEARCH);
        long last = 0;
        long max = 0;
        int count = 0;
        if (vertex != null) {
            last = ((Number) vertex.getData()).longValue();
        }
        for (String followSearch : getAutoFollowSearch()) {
            Query query = new Query(followSearch);
            if (vertex != null) {
                query.setSinceId(last);
            }
            SearchResource search = getConnection().search();
            QueryResult result = search.search(query);
            List<Status> tweets = result.getTweets();
            if (tweets != null) {
                for (Status tweet : tweets) {
                    if (count > this.maxSearch) {
                        break;
                    }
                    if (tweet.getId() > last) {
                        log("Autofollow search", Level.FINE, tweet.getText(), tweet.getUser().getScreenName(),
                                followSearch);
                        if (checkFriendship(tweet.getUser().getId(), false)) {
                            friendCount++;
                            if (friendCount >= getMaxFriends()) {
                                log("Max friend limit", Level.FINE, getMaxFriends());
                                return;
                            }
                        }
                        count++;
                        if (tweet.getId() > max) {
                            max = tweet.getId();
                        }
                    }
                }
            }
            if (count > this.maxSearch) {
                break;
            }
        }
        if (max != 0) {
            twitter.setRelationship(Primitive.LASTAUTOFOLLOWSEARCH, memory.createVertex(max));
            memory.save();
        }
    } catch (Exception exception) {
        log(exception);
    }
}

From source file:org.codice.ddf.catalog.twitter.source.TwitterSource.java

License:Open Source License

@Override
public SourceResponse query(QueryRequest request) throws UnsupportedQueryException {
    Twitter instance = twitterFactory.getInstance();
    try {/*from w  w  w.j a va 2s .c  om*/
        instance.getOAuth2Token();
    } catch (TwitterException e) {
        throw new UnsupportedQueryException("Unable to get OAuth2 token.", e);
    }
    TwitterFilterVisitor visitor = new TwitterFilterVisitor();
    request.getQuery().accept(visitor, null);
    Query query = new Query();
    query.setCount(request.getQuery().getPageSize());
    if (visitor.hasSpatial()) {
        GeoLocation geoLocation = new GeoLocation(visitor.getLatitude(), visitor.getLongitude());
        query.setGeoCode(geoLocation, visitor.getRadius(), Query.Unit.km);
    }
    if (visitor.getContextualSearch() != null) {
        query.setQuery(visitor.getContextualSearch().getSearchPhrase());
    }
    if (visitor.getTemporalSearch() != null) {
        Calendar.Builder builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getStartDate());
        Calendar calendar = builder.build();
        query.setSince(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));

        builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getEndDate());
        calendar = builder.build();
        query.setUntil(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));
    }

    QueryResult queryResult;
    try {
        queryResult = instance.search().search(query);
    } catch (TwitterException e) {
        throw new UnsupportedQueryException(e);
    }
    List<Result> resultList = new ArrayList<>(queryResult.getCount());
    resultList.addAll(queryResult.getTweets().stream().map(status -> new ResultImpl(getMetacard(status)))
            .collect(Collectors.toList()));
    return new SourceResponseImpl(request, resultList);
}

From source file:org.glassfish.jersey.sample.sse.TwitterBean.java

License:Open Source License

/**
 * Since twitter uses the v1.1 API we use twitter4j to get
 * the search results using OAuth//from  w  ww.j  av a  2 s.c  o m
 * @return a JsonArray containing tweets
 * @throws TwitterException
 * @throws IOException
 */
public JsonArray getFeedData() throws TwitterException, IOException {

    Properties prop = new Properties();
    // try {
    //load a properties file
    prop.load(this.getClass().getResourceAsStream("twitter4j.properties"));

    //get the property value and print it out
    String consumerKey = prop.getProperty("oauth.consumerKey");
    String consumerSecret = prop.getProperty("oauth.consumerSecret");
    String accessToken = prop.getProperty("oauth.accessToken");
    String accessTokenSecret = prop.getProperty("oauth.accessTokenSecret");
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    Query query = new Query("glassfish");
    QueryResult result = twitter.search(query);

    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    for (Status status : result.getTweets()) {
        jsonArrayBuilder.add(Json.createObjectBuilder().add("text", status.getText()).add("created_at",
                status.getCreatedAt().toString()));

        System.out.println(
                "@" + status.getUser().getScreenName() + ":" + status.getText() + status.getCreatedAt());
    }

    return jsonArrayBuilder.build();
}

From source file:org.ipccenter.newsagg.impl.twitterapi.TwitterPuller.java

public void findPosts() throws TwitterException {
    StringBuilder searchURL = new StringBuilder();
    searchURL.append("https://api.twitter.com/1.1/search/tweets.json&q=");
    QueryResult searchResult = null;
    List<Status> posts = new ArrayList<Status>();
    Query q = new Query();
    LOG.info("Query: {}", q.getQuery());
    List<String> requests = new ArrayList<String>();
    requests.add("");
    requests.add("");
    requests.add("");
    for (String request : requests) {
        q.query(request.toString());//w  w  w . j a v a 2 s .  co m
        LOG.info("New query: {}", q.getQuery());
        searchResult = twitter.search(q);
        posts.addAll(searchResult.getTweets());
    }
    LOG.info("Posts amount: {}", posts.size());
    for (Status status : posts) {
        parsePost(status);
    }
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void query(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();/*from  ww  w  .  j  a  v  a2 s .c  o  m*/

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg;
    String lQuery = aToken.getString("query");

    try {
        if (mLog.isDebugEnabled()) {
            mLog.debug("Searching for '" + (lQuery != null ? lQuery : "[not given]") + "'...");
        }
        if (!mCheckAuth(lResponse)) {
            mLog.error(lResponse.getString("msg"));
        } else {
            // return the list of messages as an array of strings...
            List<String> lMessages = new FastList<String>();

            QueryResult lQueryRes;
            // getting timelines is public so we can use the mTwitter object here
            if (lQuery != null && lQuery.length() > 0) {
                Query lTwQuery = new Query(lQuery);
                lQueryRes = mTwitter.search(lTwQuery);
                List<Tweet> lTweets = lQueryRes.getTweets();
                for (Tweet lTweet : lTweets) {
                    lMessages.add(lTweet.getText());
                }
                lResponse.setList("messages", lMessages);

                if (mLog.isInfoEnabled()) {
                    mLog.info("Tweets for query '" + (lQuery != null ? lQuery : "[not given]")
                            + "' successfully received");
                }
            } else {
                lMsg = "No query string given";
                mLog.error(lMsg);
                lResponse.setInteger("code", -1);
                lResponse.setString("msg", 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.kawalpemilukada.web.controller.SentimentAnalysis.java

private void cariText(JSONArray returnVals, Twitter twitter, String topic) throws ParseException {
    try {//from  w w w  .  j a  v a  2  s .  com
        Query query = new Query(topic);
        query.setCount(100);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                JSONObject returnVal = new JSONObject();
                returnVal.put("Text", tweet.getText());
                //returnVal.put("HashtagEntities", tweet.getHashtagEntities().toString());
                //returnVal.put("UserMentionEntities", tweet.getUserMentionEntities().toString());
                returnVal.put("FavoriteCount", tweet.getFavoriteCount());
                returnVal.put("RetweetCount", tweet.getRetweetCount());
                returnVal.put("UserImg", tweet.getUser().getBiggerProfileImageURLHttps().toString());
                returnVal.put("UserLink",
                        "https://twitter.com/" + CommonServices.getVal(tweet.getUser().getScreenName()));
                returnVal.put("CreatedAt", JakartaTime(tweet.getCreatedAt()).toString());
                returnVals.add(returnVal);
            }
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        te.printStackTrace();
    }
}

From source file:org.kuali.mobility.conference.controllers.ConferenceController.java

License:Open Source License

@RequestMapping(value = "twitter-search", method = RequestMethod.GET)
public ResponseEntity<String> twitterSearch(@RequestParam(value = "term", required = true) String searchParam,
        @RequestParam(value = "since", required = false) String sinceParam, HttpServletRequest request) {

    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query(searchParam.isEmpty() ? "#kualidays" : searchParam);
    QueryResult result = null;
    query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01");
    query.setCount(100);//from w ww.j av  a2s.  c o m
    query.setResultType(Query.MIXED);
    String json = "";
    List<String> tweetList = new ArrayList<String>();

    try {
        result = twitter.search(query);
    } catch (TwitterException e) {
        System.err.println("Caught 'twitterSearch' IOException: " + e.getMessage());
    }

    String tweetInfo = "";
    for (Status status : result.getTweets()) {
        tweetInfo = "{";
        tweetInfo += "\"id\" : \"" + status.getId() + "\", ";
        tweetInfo += "\"avatar\" : \"" + status.getUser().getProfileImageURL() + "\", ";
        tweetInfo += "\"tweetedOn\" : \"" + status.getCreatedAt() + "\", ";
        tweetInfo += "\"tweetedOnParsed\" : \"" + status.getCreatedAt().getTime() + "\", ";
        tweetInfo += "\"screenname\" : \"" + status.getUser().getScreenName() + "\", ";
        tweetInfo += "\"status\" : \""
                + StringEscapeUtils.escapeHtml(status.getText().replaceAll("(\\r|\\n)", "")) + "\", ";
        tweetInfo += "\"truncated\" : \"" + (status.isTruncated() ? "true" : "false") + "\",";
        tweetInfo += "\"retweeted\" : \"" + (status.isRetweet() ? "true" : "false") + "\"";
        tweetInfo += "}";

        tweetList.add(tweetInfo);
    }

    json = "[" + StringUtils.arrayToDelimitedString(tweetList.toArray(), ",") + "]";

    return new ResponseEntity<String>(json, HttpStatus.OK);
}

From source file:org.luwrain.app.twitter.Base.java

License:Open Source License

static private TweetWrapper[] search(Twitter twitter, String text, int numPages) {
    NullCheck.notNull(twitter, "twitter");
    NullCheck.notEmpty(text, "text");
    if (numPages < 1)
        throw new IllegalArgumentException("numPages must be greater than zero");
    final LinkedList<TweetWrapper> wrappers = new LinkedList<TweetWrapper>();
    try {/*from  ww  w .  j a  v  a 2 s.co m*/
        Query query = new Query(text);
        QueryResult result;
        int pageNum = 1;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            System.out.println("" + tweets.size());
            for (Status tweet : tweets)
                wrappers.add(new TweetWrapper(tweet));
            if (pageNum >= numPages)
                return wrappers.toArray(new TweetWrapper[wrappers.size()]);
            ++pageNum;
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException e) {
        e.printStackTrace();
        return null;
    }
    return wrappers.toArray(new TweetWrapper[wrappers.size()]);
}

From source file:org.mixare.utils.TwitterClient.java

License:Open Source License

/**
 * Query the twitter search API using oAuth 2.0
 * @return/* w w  w .  j  av  a 2s  . c om*/
 */
public static String queryData() {
    ConfigurationBuilder cb = new ConfigurationBuilder(); //to be configured in a properties...
    cb.setDebugEnabled(true).setOAuthConsumerKey("mt10dv6tTKacqlm14lw5w")
            .setOAuthConsumerSecret("4kRV1E1XIU3kj4JQj2R5LE1yct0RRaRl9sB5PpPrB0")
            .setOAuthAccessToken("390019380-IQ5VdvUKvxY9JOsTToEU8ElCabebc76H9X2g3QX4")
            .setOAuthAccessTokenSecret("ghJn4LTfDr7uHUCsbt6ycmpeVTwwpa3hZnXyEjyZvs");
    cb.setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    Query query = new Query();
    query = query.geoCode(new GeoLocation(lat, lon), rad, Query.KILOMETERS);

    String jsonArrayAsString = "{\"results\":[";//start
    try {
        QueryResult result = twitter.search(query);
        int size = 0;
        for (Status status : result.getTweets()) {
            {
                if (status.getGeoLocation() != null) {
                    String jsonSingleObject = DataObjectFactory.getRawJSON(status);
                    if (size == 0)
                        jsonArrayAsString += jsonSingleObject;
                    else
                        jsonArrayAsString += "," + jsonSingleObject;
                    size++;
                }
            }
        }
        jsonArrayAsString += "]}";//close array
        return jsonArrayAsString;
    } catch (Exception e) {
        Log.e(Config.TAG, "Error querying twitter data :" + e);
        e.printStackTrace();
    }
    return null;
}

From source file:org.n52.twitter.dao.TwitterAbstractDAO.java

License:Open Source License

/**
 * @throws TwitterException - when Twitter service or network is unavailable
 * @throws DecodingException /* www . j  a v a2  s.c  o m*/
 */
protected Collection<TwitterMessage> executeApiRequest(Query query) throws TwitterException, DecodingException {
    LinkedList<TwitterMessage> tweets = new LinkedList<>();
    long lastID = Long.MAX_VALUE;
    int requestCount = 0;

    query.setResultType(ResultType.mixed);

    while (tweets.size() < MAX_TWEETS_TO_HARVEST) {
        if (MAX_TWEETS_TO_HARVEST - tweets.size() > TWEETS_TO_LOAD_PER_API_REQUEST) {
            query.setCount(TWEETS_TO_LOAD_PER_API_REQUEST);
        } else {
            query.setCount(MAX_TWEETS_TO_HARVEST - tweets.size());
        }
        try {
            QueryResult result = twitter.search(query);
            requestCount++;
            if (result.getTweets().isEmpty()) {
                break;
            }
            for (Status tweet : result.getTweets()) {
                TwitterMessage message = TwitterMessage.create(tweet);
                if (message != null) {
                    tweets.add(message);
                }
                if (tweet.getId() < lastID) {
                    lastID = tweet.getId();
                }
            }
            query.setMaxId(lastID - 1);
            LOGGER.debug("Progress: " + tweets.size() + "/" + MAX_TWEETS_TO_HARVEST + "(Requests: "
                    + requestCount + ")");
        } catch (TwitterException e) {
            LOGGER.error(e.getErrorMessage(), e);
            throw e;
        }
    }

    LOGGER.debug("Result count :" + tweets.size());

    return tweets;
}