Example usage for twitter4j Query RECENT

List of usage examples for twitter4j Query RECENT

Introduction

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

Prototype

ResultType RECENT

To view the source code for twitter4j Query RECENT.

Click Source Link

Document

recent: return only the most recent results in the response

Usage

From source file:com.daemon.Minion.java

License:Open Source License

/**
 * Sends a request specified as search term to Twitter and returns the
 * results Twitter returned./*from   w w w . j a  v a2s. c  o  m*/
 * 
 * @param term The search term object.
 * @return The answer of the sent request as QueryResult.
 * @throws TwitterException Thrown whenever there is a problem querying Twitter
 * (i. e the Rate Limit was reached).
 */
public QueryResult search(SearchTerm term) throws TwitterException {
    Query query = new Query(term.getTerm());
    query.setCount(100);
    query.setResultType(Query.RECENT);
    if (term.getLastFetchedTweetId() == null) {
        // Start a new backwards search fron the current given start
        if (term.getOldStart() == null)
            query.setUntil(Localization.DATETIME_FORMATTER.print(term.getCurrentStart().plusDays(1)));
    } else
        // Continue the current search from the last fetched tweet id
        query.setMaxId(term.getLastFetchedTweetId());

    return _twitter.search(query);
}

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

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

    List<Resultado> resultados = new ArrayList();
    try {/*w w  w.  java2 s .  co 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.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 {/*from ww w .  ja  va 2  s .  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:controllers.modules.CorpusModule.java

License:Open Source License

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;//from w w w .ja v a 2 s .  co  m
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

Query createQuery(String str) {
    Query q = new Query(str);
    q.setResultType(Query.RECENT);
    return q;
}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void SearchForTermUsingGeolocation(String queryPar, int PageSize, double latitude, double longitude,
        double radius) {
    try {/*from  w  ww .  j a  v a2  s  .c  o m*/
        results = new ArrayList<TwitterPostData>();

        if (queryPar != null) {
            this.pageSize = PageSize;
            this.queryPar = queryPar;
            Query query = new Query(queryPar);
            query.setPage(pageIndex);
            query.setRpp(PageSize);
            query.setResultType(Query.RECENT);
            query.setGeoCode(new GeoLocation(latitude, longitude), radius, "km");
            QueryResult result = twitter.search(query);
            ArrayList tweets = (ArrayList) result.getTweets();
            for (int i = 0; i < tweets.size(); i++) {
                results.add(new TwitterPostData((Tweet) tweets.get(i)));
            }

        }
    } catch (TwitterException ex) {
        System.err.println("Twitter Error");
        // Logger.getLogger(TwitterSearch.class.getName()).log(Level.SEVERE,
        // null, ex);
    }

}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void setNextPage() {
    results = new ArrayList<TwitterPostData>();
    pageIndex++;/*from   w  w w.  j  a v  a2  s. c  om*/

    Query query = new Query(queryPar);
    query.setRpp(pageSize);
    query.setResultType(Query.RECENT);
    query.setPage(pageIndex);

    QueryResult result;
    try {
        result = twitter.search(query);
        ArrayList tweets = (ArrayList) result.getTweets();

        for (int i = 0; i < tweets.size(); i++) {
            results.add(new TwitterPostData((Tweet) tweets.get(i)));
        }
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

public void setPreviousPage() {
    results = new ArrayList<TwitterPostData>();
    pageIndex--;//from   www  .j av  a  2  s  .com

    Query query = new Query(queryPar);
    query.setRpp(pageSize);
    query.setResultType(Query.RECENT);
    query.setPage(pageIndex);

    QueryResult result;
    try {
        result = twitter.search(query);
        ArrayList tweets = (ArrayList) result.getTweets();

        for (int i = 0; i < tweets.size(); i++) {
            results.add(new TwitterPostData((Tweet) tweets.get(i)));
        }
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void SearchForTerm(String queryPar, Integer PageSize) {
    Query query = null;//from   w  ww  .j a v  a2s . co m
    try {
        results = new ArrayList<TwitterPostData>();
        this.pageSize = PageSize;
        if (queryPar != null) {

            this.queryPar = queryPar.replace("%24", "#");
            System.out.println(this.queryPar);
            query = new Query(this.queryPar);
            query.setPage(pageIndex);
            query.setRpp(PageSize);
            query.setResultType(Query.RECENT);
            QueryResult result = twitter.search(query);
            ArrayList tweets = (ArrayList) result.getTweets();
            for (int i = 0; i < tweets.size(); i++) {
                results.add(new TwitterPostData((Tweet) tweets.get(i)));
            }

        }
    } catch (TwitterException ex) {
        System.err.println(ex);
        System.err.println(query);
        // Logger.getLogger(TwitterSearch.class.getName()).log(Level.SEVERE,
        // null, ex);
    }
}

From source file:net.lacolaco.smileessence.twitter.task.SearchTask.java

License:Open Source License

public static Query getBaseQuery(MainActivity activity, String queryString) {
    Configuration config = activity.getResources().getConfiguration();
    Query query = new Query();
    query.setQuery(queryString);/*from   w  w  w. j  a v  a  2 s .  co  m*/
    query.setLang(config.locale.getLanguage());
    query.setCount(TwitterUtils.getPagingCount(activity));
    query.setResultType(Query.RECENT);
    return query;
}