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:org.getlantern.firetweet.loader.support.TweetSearchLoader.java

License:Open Source License

@NonNull
@Override/*from  w  ww.  ja v a 2s.  co m*/
public List<Status> getStatuses(@NonNull final Twitter twitter, final Paging paging) throws TwitterException {
    final Query query = new Query(processQuery(mQuery));
    query.setRpp(paging.getCount());
    if (paging.getMaxId() > 0) {
        query.setMaxId(paging.getMaxId());
    }
    return twitter.search(query);
}

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//  w w  w .  j  ava 2s.com
 * @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.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void query(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();//from  w  w  w.j a v  a  2 s.  co  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 {/* w w  w .  j  ava 2s .  c o m*/
        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.kie.twitter.TwitterClient.java

License:Apache License

public List<Entry> getEntriesByHashTag(final String hashTag) {
    try {/*from   w  w w . ja v a2  s  .co  m*/
        return twitter().search(new Query("#" + hashTag).count(SEARCH_MAX_VALUE)).getTweets().stream()
                .map(Entry::new).collect(Collectors.toList());

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

    return new ArrayList<>();
}

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;//from   w  ww. j  a  va 2s  . com
    query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01");
    query.setCount(100);
    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 {/*w w  w .j  a  v  a  2  s .  c o 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.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Returns tweets that match a specified query.
 * <p/>//from   w  w  w  . j a v a  2 s.  c  o  m
 * This method calls http://search.twitter.com/search.json
 * <p/>
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:search}
 *
 * @param query The search query.
 * @param lang Restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
 * @param locale Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases.
 * @param maxId If specified, returns tweets with status ids less than the given id
 * @param since If specified, returns tweets since the given date. Date should be formatted as YYYY-MM-DD
 * @param sinceId Returns tweets with status ids greater than the given id.
 * @param geocode A {@link String} containing the latitude and longitude separated by ','. Used to get the tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile
 * @param radius The radius to be used in the geocode -ONLY VALID IF A GEOCODE IS GIVEN-
 * @param unit The unit of measurement of the given radius. Can be 'mi' or 'km'. Miles by default.
 * @param until If specified, returns tweets with generated before the given date. Date should be formatted as YYYY-MM-DD
 * @param resultType If specified, returns tweets included popular or real time or both in the responce. Both by default. Can be 'mixed', 'popular' or 'recent'.
 * @return the {@link QueryResult}
 * @throws TwitterException when Twitter service or network is unavailable
 */
@Processor
public QueryResult search(String query, @Optional String lang, @Optional String locale, @Optional Long maxId,
        @Optional String since, @Optional Long sinceId, @Optional String geocode, @Optional String radius,
        @Default(value = Query.MILES) @Optional String unit, @Optional String until,
        @Optional String resultType) throws TwitterException {
    final Query q = new Query(query);

    if (lang != null) {
        q.setLang(lang);
    }
    if (locale != null) {
        q.setLocale(locale);
    }
    if (maxId != null && maxId.longValue() != 0) {
        q.setMaxId(maxId.longValue());
    }

    if (since != null) {
        q.setSince(since);
    }
    if (sinceId != null && sinceId.longValue() != 0) {
        q.setSinceId(sinceId.longValue());
    }
    if (geocode != null) {
        final String[] geocodeSplit = StringUtils.split(geocode, ',');
        final double latitude = Double.parseDouble(StringUtils.replace(geocodeSplit[0], " ", ""));
        final double longitude = Double.parseDouble(StringUtils.replace(geocodeSplit[1], " ", ""));
        q.setGeoCode(new GeoLocation(latitude, longitude), Double.parseDouble(radius), unit);
    }
    if (until != null) {
        q.setUntil(until);
    }
    if (resultType != null) {
        q.setResultType(resultType);
    }
    return twitter.search(q);
}

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

License:Open Source License

@Override
public Collection<TwitterMessage> search(String... tags) throws TwitterException, DecodingException {
    if (tags.length == 0) {
        return Collections.emptyList();
    }/*from w ww.jav  a  2  s  .c  om*/
    StringBuffer tagsBuffer = new StringBuffer();
    for (String tag : tags) {
        tag = tag.trim();
        tagsBuffer.append(tag).append(" OR ").append("#").append(tag).append(" OR ");
    }
    tagsBuffer = tagsBuffer.replace(tagsBuffer.length() - 4, tagsBuffer.length(), "");
    LOGGER.debug("Created search string: '{}'", tagsBuffer.toString());
    Query searchQuery = new Query(tagsBuffer.toString());
    // 40074 is circumference of the earth
    // TODO doesn't map the whole
    searchQuery.setGeoCode(new GeoLocation(0.0, 0.0), 40074 / 2, Unit.km);
    return executeApiRequest(searchQuery);
}

From source file:org.nsoft.openbus.view.SearchColumn.java

License:Open Source License

@Override
public void onGetUpdate(AccessToken token) {
    final List<Mensagem> last = new ArrayList<Mensagem>();

    for (Mensagem m : facade.getMensagemOf(Mensagem.TIPO_TWEET_SEARCH)) {
        try {/* w ww . ja v  a  2  s. c o  m*/
            Vector<String> parts = new Vector<String>(Arrays.asList(m.getMensagem().toLowerCase().split(" ")));
            if (parts.contains(search.toLowerCase()))
                last.add(m);
        } catch (Exception e) {

        }

    }

    Twitter twitter = TwitterUtils.getTwitter(token);
    Query q = new Query(search);
    if (flagNextPage)
        currentpage++;
    else
        currentpage = 1;

    flagNextPage = false;
    //      q.setPage(currentpage);
    //      try {
    //         QueryResult result = twitter.search(q);
    //         final Vector<Mensagem> mensagens = new Vector<Mensagem>();
    //
    //         for (Tweet tweet : result.getTweets()) {
    //            try {
    //               Mensagem m = Mensagem.createFromTweet(tweet);
    //
    //               Facade facade = Facade.getInstance(ctx);
    //
    //               if (!facade.exsistsStatus(m.getIdMensagem(), m.getTipo())) {
    //
    //                  facade.insert(m);
    //                  mensagens.add(m);
    //
    //               }
    //            } catch (Exception e) {
    //               
    //            }
    //
    //         }
    //
    //         if (h == null)
    //            return;
    //
    //         h.post(new Runnable() {
    //
    //            @Override
    //            public void run() {
    //
    //               if (currentpage == 1) {
    //                  ((PullToRefreshListView) listView).onRefreshComplete();
    //                  if (!mensagens.isEmpty()) {
    //                     adapter.clear();
    //                     for (Mensagem m : last)
    //                        facade.deleteMensagem(m.getIdMensagem(),
    //                              m.getTipo());
    //
    //                  }
    //               }
    //
    //               for (Mensagem m : mensagens)
    //                  adapter.addItem(m);
    //
    //               if (currentpage > 1) {
    //                  notifyNextPageFinish();
    //
    //               }
    //            }
    //         });
    //
    //      } catch (TwitterException e) {
    //         e.printStackTrace();
    //      }catch (Exception e) {
    //
    //      }

}