Example usage for twitter4j Query setResultType

List of usage examples for twitter4j Query setResultType

Introduction

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

Prototype

public void setResultType(ResultType resultType) 

Source Link

Document

Default value is Query.MIXED if parameter not specified

Usage

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 {/*w  w w  .j  a va 2s  .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 ww w . ja va2s .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 ww  w  . ja  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

@Override
public void SearchForTerm(String queryPar, Integer PageSize) {
    Query query = null;
    try {/*from w w  w . j  av a 2 s . com*/
        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.  java  2  s  .c o  m*/
    query.setLang(config.locale.getLanguage());
    query.setCount(TwitterUtils.getPagingCount(activity));
    query.setResultType(Query.RECENT);
    return query;
}

From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java

/**
 * Entry point for a Lappsgrid service./*from  w  w  w .j a v a2s  .com*/
 * <p>
 * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object
 * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container}
 * payload.
 * <p>
 * Errors and exceptions that occur during processing should be wrapped in a {@code Data}
 * object with the discriminator set to http://vocab.lappsgrid.org/ns/error
 * <p>
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br />
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br />
 *
 * @param input A JSON string representing a Data object
 * @return A JSON string containing a Data object with a Container payload.
 */
@Override
public String execute(String input) {
    Data<String> data = Serializer.parse(input, Data.class);
    String discriminator = data.getDiscriminator();

    // Return ERRORS back
    if (Discriminators.Uri.ERROR.equals(discriminator)) {
        return input;
    }

    // Generate an error if the used discriminator is wrong
    if (!Discriminators.Uri.GET.equals(discriminator)) {
        return generateError(
                "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator);
    }

    Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false)
            .build();

    // Authentication using saved keys
    Twitter twitter = new TwitterFactory(config).getInstance();
    String key = readProperty(KEY_PROPERTY);
    if (key == null) {
        return generateError("The Twitter Consumer Key property has not been set.");
    }

    String secret = readProperty(SECRET_PROPERTY);
    if (secret == null) {
        return generateError("The Twitter Consumer Secret property has not been set.");
    }

    twitter.setOAuthConsumer(key, secret);

    try {
        twitter.getOAuth2Token();
    } catch (TwitterException te) {
        String errorData = generateError(te.getMessage());
        logger.error(errorData);
        return errorData;
    }

    // Get query String from data payload
    Query query = new Query(data.getPayload());

    // Set the type to Popular or Recent if specified
    // Results will be Mixed by default.
    if (data.getParameter("type") == "Popular")
        query.setResultType(Query.POPULAR);
    if (data.getParameter("type") == "Recent")
        query.setResultType(Query.RECENT);

    // Get lang string
    String langCode = (String) data.getParameter("lang");

    // Verify the validity of the language code and add it to the query if it's valid
    if (validateLangCode(langCode))
        query.setLang(langCode);

    // Get date strings
    String sinceString = (String) data.getParameter("since");
    String untilString = (String) data.getParameter("until");

    // Verify the format of the date strings and set the parameters to query if correctly given
    if (validateDateFormat(untilString))
        query.setUntil(untilString);
    if (validateDateFormat(sinceString))
        query.setSince(sinceString);

    // Get GeoLocation
    if (data.getParameter("address") != null) {
        String address = (String) data.getParameter("address");
        double radius = (double) data.getParameter("radius");
        if (radius <= 0)
            radius = 10;
        Query.Unit unit = Query.MILES;
        if (data.getParameter("unit") == "km")
            unit = Query.KILOMETERS;
        GeoLocation geoLocation;
        try {
            double[] coordinates = getGeocode(address);
            geoLocation = new GeoLocation(coordinates[0], coordinates[1]);
        } catch (Exception e) {
            String errorData = generateError(e.getMessage());
            logger.error(errorData);
            return errorData;
        }

        query.geoCode(geoLocation, radius, String.valueOf(unit));

    }

    // Get the number of tweets from count parameter, and set it to default = 15 if not specified
    int numberOfTweets;
    try {
        numberOfTweets = (int) data.getParameter("count");
    } catch (NullPointerException e) {
        numberOfTweets = 15;
    }

    // Generate an ArrayList of the wanted number of tweets, and handle possible errors.
    // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed
    ArrayList<Status> allTweets;
    Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter);
    String tweetsDataDisc = tweetsData.getDiscriminator();
    if (Discriminators.Uri.ERROR.equals(tweetsDataDisc))
        return tweetsData.asPrettyJson();

    else {
        allTweets = (ArrayList<Status>) tweetsData.getPayload();
    }

    // Initialize StringBuilder to hold the final string
    StringBuilder builder = new StringBuilder();

    // Append each Status (each tweet) to the initialized builder
    for (Status status : allTweets) {
        String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : "
                + status.getText() + "\n";
        builder.append(single);
    }

    // Output results
    Container container = new Container();
    container.setText(builder.toString());
    Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container);
    return output.asPrettyJson();
}

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 w  w.j ava 2 s  . c  om
    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.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Returns tweets that match a specified query.
 * <p/>/*from  ww  w .  j  a va 2s.co 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.TwitterAbstractDAO.java

License:Open Source License

/**
 * @throws TwitterException - when Twitter service or network is unavailable
 * @throws DecodingException /*w w  w  .  j  a  va2  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;
}

From source file:org.xmlsh.twitter.search.java

License:BSD License

@Override
public int run(List<XValue> args) throws Exception {

    Options opts = new Options(sCOMMON_OPTS
            + ",q=query:,geo=geocode:,lang:,locale:,t=result_type:,until:,since_id:,max_id:,include_entities:,sanitize",
            SerializeOpts.getOptionDefs());
    opts.parse(args);//from w  ww  . ja  v a  2  s  .  c  om
    mSerializeOpts = this.getSerializeOpts(opts);
    final boolean bSanitize = opts.hasOpt("sanitize");

    args = opts.getRemainingArgs();

    try {

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

        if (opts.hasOpt("query"))
            query.setQuery(opts.getOptStringRequired("query"));

        if (opts.hasOpt("lang"))
            query.setLang(opts.getOptStringRequired("lang"));

        if (opts.hasOpt("locale"))
            query.setLocale(opts.getOptStringRequired("locale"));

        if (opts.hasOpt("result_type"))
            query.setResultType(opts.getOptStringRequired("result_type"));

        if (opts.hasOpt("until"))
            query.setUntil(opts.getOptStringRequired("until"));

        if (opts.hasOpt("since_id"))
            query.setSinceId(opts.getOptValue("since_id").toLong());
        if (opts.hasOpt("since"))
            query.setUntil(opts.getOptStringRequired("since"));

        if (opts.hasOpt("max_id"))
            query.setSinceId(opts.getOptValue("max_id").toLong());

        QueryResult result = twitter.search(query);
        List<Status> tweets = result.getTweets();

        OutputPort out = this.getStdout();
        mWriter = new TwitterWriter(out.asXMLStreamWriter(mSerializeOpts), bSanitize);

        mWriter.startDocument();
        mWriter.startElement("twitter");
        mWriter.writeDefaultNamespace();

        for (Status t : tweets)
            mWriter.write(t);

        mWriter.endElement();
        mWriter.endDocument();
        mWriter.closeWriter();

        out.release();
    } finally {

    }
    return 0;

}