Example usage for twitter4j Query Query

List of usage examples for twitter4j Query Query

Introduction

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

Prototype

public Query(String query) 

Source Link

Usage

From source file:com.fsatir.twitter.TwitterManagedBean.java

public List<Media> trendImageList(Twitter twitter, String trendName) {

    Query query = new Query(trendName + " AND filter:images");
    query.setCount(1);/*from  w ww  . jav  a  2  s.  c  o  m*/
    QueryResult result;
    try {
        do {
            result = twitter.search(query);

            List<twitter4j.Status> tweets = result.getTweets();
            int counter = 0;
            for (twitter4j.Status status : tweets) {

                Media myMedia = new Media();
                int control = 0;
                for (MediaEntity me : status.getMediaEntities()) {
                    //Tek grsel almay kesinletirmek iin kontrol.
                    //leride modeldeki trendImgURL diziye dntrlerek kontrol kaldrlabilir.
                    if (control < 1)
                        myMedia.setTrendImgURL(me.getMediaURLHttps());
                    control++;
                }
                // URL null deilse, grsel ve bigileri list'e eklenir.
                if (myMedia.getTrendImgURL() != null) {
                    myMedia.setTweetID(status.getId());
                    myMedia.setFavorite_count(status.getFavoriteCount());
                    myMedia.setRetweet_count(status.getRetweetCount());
                    //myMedia.setTrendImgURL(status.getMediaEntities()[0].getMediaURLHttps());
                    myMedia.setTrendName(trendName);
                    myMedia.setName(Long.toString(status.getId()));
                    myMedia.setType(status.getMediaEntities()[0].getType());

                    myMediaList.add(counter++, myMedia);
                }
            }
        } while ((query = result.nextQuery()) != null && result.getRateLimitStatus().getRemaining() > 0);

    } catch (TwitterException e) {
        e.printStackTrace();
    }

    myMediaListFiltered = filterList(myMediaList);

    return myMediaListFiltered;

}

From source file:com.fuzuapp.model.resultados.TwitterAdapter.java

@Override
public List<Resultado> getResultados(GeoPoint ponto, double raio) {

    List<Resultado> resultados = new ArrayList();
    try {//from  w  w  w.j  av a2 s. c o m
        Query query = new Query("");
        GeoLocation geo = new GeoLocation(ponto.getLatitude(), ponto.getLongitude());
        query.setGeoCode(geo, raio, Query.KILOMETERS);
        query.resultType(Query.RECENT);
        query.setCount(20);
        QueryResult result = twitter.search(query);

        for (Status status : result.getTweets()) {
            Resultado r = new Resultado();

            r.setDescricao(status.getText());
            r.setUrl("http://twitter.com/statuses/" + String.valueOf(status.getId()));
            r.setNomeUsuario(status.getUser().getName());
            r.setHorario(new SimpleDateFormat("dd/MM HH:mm").format(status.getCreatedAt()));
            r.setFotoUrl(status.getUser().getProfileImageURL());
            //r.setLocal(new GeoPoint(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
            r.setTipo(Resultado.TEXTO);

            resultados.add(r);

        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterAdapter.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultados;
}

From source file:com.github.moko256.mastodon.MastodonTwitterImpl.java

License:Apache License

@Override
public QueryResult search(Query query) {
    Pageable<com.sys1yagi.mastodon4j.api.entity.Status> pageable = null;
    try {//from www .  j  a  v a2s  .  c o  m
        pageable = new com.sys1yagi.mastodon4j.api.method.Timelines(client)
                .getHashtagTimeline(query.getQuery(), false, false, MTRangeConverter.convert(query)).execute();
    } catch (Mastodon4jRequestException e) {
        e.printStackTrace();
    }

    long previous;
    long next;

    if (pageable == null)
        return null;

    if (pageable.getLink() != null) {
        next = pageable.getLink().getMaxId();
        previous = pageable.getLink().getSinceId();
    } else {
        next = -1;
        previous = -1;
    }

    List<com.sys1yagi.mastodon4j.api.entity.Status> part = pageable.getPart();
    Pageable<com.sys1yagi.mastodon4j.api.entity.Status> finalPageable = pageable;
    return new QueryResult() {
        @Override
        public long getSinceId() {
            return previous;
        }

        @Override
        public long getMaxId() {
            return next;
        }

        @Override
        public String getRefreshURL() {
            return null;
        }

        @Override
        public int getCount() {
            return part.size();
        }

        @Override
        public double getCompletedIn() {
            return 0;
        }

        @Override
        public String getQuery() {
            return query.getQuery();
        }

        @Override
        public List<Status> getTweets() {
            return MTResponseList.convert(finalPageable);
        }

        @Override
        public Query nextQuery() {
            return new Query(query.getQuery()).sinceId(next);
        }

        @Override
        public boolean hasNext() {
            return next != -1;
        }

        @Override
        public RateLimitStatus getRateLimitStatus() {
            return null;
        }

        @Override
        public int getAccessLevel() {
            return 0;
        }
    };
}

From source file:com.github.moko256.twitlatte.SearchResultFragment.java

License:Apache License

@Override
@NonNull//ww  w. j  a va 2  s .  c  om
protected ResponseList<Status> getResponseList(@NonNull Paging paging) throws TwitterException {
    SearchResultList result = new SearchResultList();
    if (!searchText.equals("")) {
        Query query = new Query(searchText).count(paging.getCount()).sinceId(paging.getSinceId())
                .maxId(paging.getMaxId()).resultType(Query.ResultType.recent);
        result.addAll(GlobalApplication.twitter.search().search(query).getTweets());
    }
    return result;
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Search for tweets or labels/*from   ww  w . j  ava2s.com*/
 */
@SimpleFunction(description = "This searches Twitter for the given String query."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void SearchTwitter(final String query) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "SearchTwitter", ErrorMessages.ERROR_TWITTER_SEARCH_FAILED,
                "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> tweets = Collections.emptyList();

        public void run() {
            try {
                tweets = twitter.search(new Query(query)).getTweets();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "SearchTwitter",
                        ErrorMessages.ERROR_TWITTER_SEARCH_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        searchResults.clear();
                        for (Status tweet : tweets) {
                            searchResults.add(tweet.getUser().getName() + " " + tweet.getText());
                        }
                        SearchSuccessful(searchResults);
                    }
                });
            }
        }
    });
}

From source file:com.happy_coding.viralo.twitter.FriendDiscoverer.java

License:Apache License

/**
 * Returns list of Twitter Friends by the given keywords.
 *
 * @param keywords//w  w  w  .  j  av a 2  s  .  c  o  m
 * @return
 */
public List<Contact> findFriends(List<String> keywords) {

    Joiner joiner = Joiner.on(" ").skipNulls();

    String twitterKeywords = joiner.join(keywords);

    Twitter twitter = new TwitterFactory().getInstance();
    List<Contact> contacts = new ArrayList<Contact>();

    for (int i = 1; i <= MAX_FRIENDS_ITERATIONS; i++) {

        Query query = new Query(twitterKeywords);
        query.setPage(i);
        query.setRpp(FRIENDS_PER_PAGE);

        QueryResult result = null;
        try {
            result = twitter.search(query);
        } catch (TwitterException e) {
            logger.error("can't find friends", e);
            return null;
        }

        List<String> tmpFriendList = new ArrayList<String>();

        for (Tweet tweet : result.getTweets()) {
            String user = tweet.getFromUser();

            if (!tmpFriendList.contains(user)) {
                Contact newContact = new Contact(user);
                newContact.setUid(tweet.getFromUserId());
                contacts.add(newContact);
                tmpFriendList.add(user);
            }
        }
        try {
            Thread.sleep(WAIT_BETWEEN_KEYWORD_SEARCH_IN_MS);
        } catch (InterruptedException e) {
            logger.error("can't find friends", e);
            return null;
        }
    }

    return contacts;
}

From source file:com.happy_coding.viralo.twitter.SmartPoster.java

License:Apache License

/**
 * Returns tweet for keywords.//from  w  ww.  ja  va  2s.com
 *
 * @param keywords
 * @return
 */
public ContactTweet getTweet(String keywords) {

    Query query = new Query(keywords);
    query.setPage(1);
    query.setRpp(TWEETS_PER_PAGE);

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

    QueryResult result = null;

    try {
        result = twitter.search(query);
    } catch (TwitterException e) {
        logger.error("can't load tweet", e);
        return null;
    }

    /*
    just get the first tweet.
     */
    Tweet firstTweet = result.getTweets().get(0);

    Contact contact = new Contact(firstTweet.getFromUserId());
    contact.setName(firstTweet.getFromUser());

    ContactTweet contactTweet = new ContactTweet(contact, firstTweet.getText());

    return contactTweet;
}

From source file:com.ibm.TwitterAsyncService.java

License:Open Source License

@Override
public void run() {
    String bookTitle = ac.getRequest().getParameter("title");
    String bookAuthor = ac.getRequest().getParameter("author");
    boolean translate = Boolean.parseBoolean(ac.getRequest().getParameter("enable"));

    logger.debug("Requested book title {} and author {}", bookTitle, bookAuthor);

    Query query = new Query(bookTitle + " " + bookAuthor);
    query.setResultType(Query.RECENT);

    Twitter twitter = TwitterFactory.getSingleton();

    try {/* ww  w. j  ava2s.c  o m*/
        PrintWriter writer = ac.getResponse().getWriter();
        Locale locale = ac.getRequest().getLocale();
        WatsonTranslate watson = new WatsonTranslate(locale);

        // Just get the first page of results to avoid exceeding the Twitter rate limit
        QueryResult result = twitter.search(query);

        Alchemy alchemy = new Alchemy();

        List<Status> tweets = result.getTweets();

        logger.debug("Current tweets {}", tweets.toString());

        for (Status tweetMessage : tweets) {
            JSONObject json = new JSONObject();
            JSONObject tweet = new JSONObject();
            // We need to put the tweet and link into an inner object
            // so that we can use a special formatter in bootstrap table

            json.put("screenName", tweetMessage.getUser().getScreenName());

            if (translate) {
                String message = watson.translate(tweetMessage.getText());
                tweet.put("message", message);
                json.put("sentiment", alchemy.getSentiment(message));
            } else {
                tweet.put("message", tweetMessage.getText());
                json.put("sentiment", alchemy.getSentiment(tweetMessage.getText()));
            }

            String url = "https://twitter.com/" + tweetMessage.getUser().getScreenName() + "/status/"
                    + tweetMessage.getId();

            tweet.put("link", url);

            json.put("tweet", tweet);

            writer.write(("data: " + json.toString() + "\n\n"));
            writer.flush();
        }

        writer.write(("event: finished\n"));
        writer.write(("data: \n\n"));
        writer.flush();
        writer.close();
    } catch (TwitterException e) {
        logger.error("Twitter Error {}", e.getMessage());
    } catch (IOException e) {
        logger.error("could not write SSE {}", e.getMessage());
    } catch (NullPointerException e) {
        logger.error("Exception Twitter Async Service {}", e.getMessage());
    } finally {
        ac.complete();
    }
}

From source file:com.infine.android.devoxx.service.TwitterService.java

License:Apache License

public void triggerRefresh() {
    try {//  w w w. jav a  2  s  .  c  o m
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        long lastTweetId = prefs.getLong(LAST_TWEET_ID, 0);
        Query query = new Query(TWEETS_QUERY);
        if (lastTweetId > 0) {
            query.setSinceId(lastTweetId);
        }
        QueryResult result = mTwitter.search(query);
        Log.i("Twitter", "nombre de tweets recu:" + result.getTweets().size());
        ArrayList<ContentProviderOperation> databaseOps = new ArrayList<ContentProviderOperation>();
        long maxId = 0;
        for (Status status : result.getTweets()) {
            maxId = Math.max(maxId, status.getId());
            databaseOps.add(buildCPOperation(status));
        }
        // batch update
        if (!databaseOps.isEmpty()) {
            mResolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, databaseOps);
        }
        if (maxId > 0) {
            prefs.edit().putLong(LAST_TWEET_ID, maxId);
        }

    } catch (TwitterException e) {
        // pas de message c'est qui doit pas avoir de reseau
        // Toast.makeText(this, "Erreur durant la rcupration des Tweets",
        // Toast.LENGTH_SHORT).show();
    } catch (RemoteException e) {
        // pas de message
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // pas de message
        e.printStackTrace();
    }
}

From source file:com.javielinux.api.loaders.UserMentionsLoader.java

License:Apache License

@Override
public BaseResponse loadInBackground() {

    try {//from ww  w . j  a v a2  s  . com
        UserMentionsResponse response = new UserMentionsResponse();

        ArrayList<InfoTweet> infoTweets = new ArrayList<InfoTweet>();

        String query_text = " to:" + this.request.getInfoUsers().getName();
        Query query = new Query(query_text);
        QueryResult result = ConnectionManager.getInstance().getUserForSearchesTwitter().search(query);

        ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();
        for (Status tweet : tweets) {
            infoTweets.add(new InfoTweet(tweet));
        }

        response.setInfoTweets(infoTweets);

        return response;
    } catch (Exception e) {
        e.printStackTrace();
        ErrorResponse response = new ErrorResponse();
        response.setError(e, e.getMessage());
        return response;
    }
}