Example usage for twitter4j FilterQuery follow

List of usage examples for twitter4j FilterQuery follow

Introduction

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

Prototype

null follow

To view the source code for twitter4j FilterQuery follow.

Click Source Link

Usage

From source file:com.tilab.ca.sda.ctw.connector.TwitterReceiver.java

@Override
public void onStart() {
    try {//from w  w w.ja  v a 2 s  .c om
        log.info(String.format("[%s] CALLED ONSTART on Twitter Receiver...", Constants.TW_RECEIVER_LOG_TAG));
        log.debug(String.format("[%s] Init twitterStreamFactory...", Constants.TW_RECEIVER_LOG_TAG));

        TwitterStream twStream = new TwitterStreamFactory(twStreamConf).getInstance();

        log.debug(String.format("[%s] twitterStreamFactory initialized!", Constants.TW_RECEIVER_LOG_TAG));
        log.debug(String.format("[%s] adding status listener..", Constants.TW_RECEIVER_LOG_TAG));

        twStream.addListener(new StatusListener() {

            @Override
            public void onException(Exception e) {
                log.error(String.format("[%s] Exception on twitterStream", Constants.TW_RECEIVER_LOG_TAG), e);
                restart("Error on receiving tweets!", e);
            }

            @Override
            public void onTrackLimitationNotice(int notDelivered) {
                log.warn(String.format(
                        "[%s] WARNING:number of statuses matching keywords but not delivered => %d",
                        Constants.TW_RECEIVER_LOG_TAG, notDelivered));
            }

            @Override
            public void onStatus(Status status) {
                log.debug(String.format("[%s] new status received! storing on spark..",
                        Constants.TW_RECEIVER_LOG_TAG));
                store(status);
            }

            @Override
            public void onStallWarning(StallWarning stallW) {
                log.warn(String.format("[%s] WARNING: Received Stall Warning message: %s",
                        Constants.TW_RECEIVER_LOG_TAG, stallW.getMessage()));
            }

            @Override
            public void onScrubGeo(long arg0, long arg1) {
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice arg0) {
            }
        });

        log.debug(String.format("[%s] Creating filterquery", Constants.TW_RECEIVER_LOG_TAG));
        FilterQuery fq = new FilterQuery();
        if (trackArray != null) {
            log.debug(String.format("[%s] added keys to track", Constants.TW_RECEIVER_LOG_TAG));
            fq.track(trackArray);
        }
        if (locationFilterArray != null) {
            log.info(String.format("[%s] added geolocations to track", Constants.TW_RECEIVER_LOG_TAG));
            fq.locations(locationFilterArray);
        }
        if (user2FollowArray != null) {
            log.debug(String.format("[%s] Added users to track", Constants.TW_RECEIVER_LOG_TAG));
            fq.follow(user2FollowArray);
        }
        twStream.filter(fq);
        log.debug(String.format("[%s] Setting twitterStream..", Constants.TW_RECEIVER_LOG_TAG));

        setTwitterStream(twStream);

        log.info(String.format("[%s] Twitter Stream started", Constants.TW_RECEIVER_LOG_TAG));

    } catch (Throwable t) {
        log.error(String.format("[%s] Error starting twitter stream", Constants.TW_RECEIVER_LOG_TAG), t);
        restart("Error starting twitter stream", t);
    }
}

From source file:me.timothy.twittertoreddit.TwitterToRedditMain.java

License:Open Source License

private void begin() throws InterruptedException {
    loadConfiguration();/*from w w  w . j av  a  2 s  .c  o  m*/
    HttpRestClient rClient = new HttpRestClient();
    rClient.setUserAgent("TwitterToReddit Bot by /u/Tjstretchalot");

    User user = new User(rClient, username, password);
    try {
        user.connect();
    } catch (Exception e) {
        System.err.println("Failed to connect");
        return;
    }

    System.out.println("Succesfully Authenticated to Reddit");
    Thread.sleep(1000);
    System.out.println("..");
    Thread.sleep(1000);
    System.out.println("Authenticating to Twitter..");

    TwitterStream stream = new TwitterStreamFactory().getInstance();
    FilterQuery filter = new FilterQuery();
    filter.follow(new long[] { twitterId });

    TwitterToReddit mBot = new TwitterToReddit(rClient, user, twitterId, subreddit);
    mBot.beginStreaming(stream);

    stream.filter(filter);

    System.out.println("Success! The bot is now active and will post new tweets as well as print out here");
    System.out.println();

}

From source file:org.apache.camel.component.twitter.consumer.streaming.FilterConsumer.java

License:Apache License

private FilterQuery createFilter(TwitterEndpoint te) {
    FilterQuery filterQuery = new FilterQuery();
    String allLocationsString = te.getProperties().getLocations();
    if (allLocationsString != null) {
        String[] locationStrings = allLocationsString.split(";");
        double[][] locations = new double[locationStrings.length][2];
        for (int i = 0; i < locationStrings.length; i++) {
            String[] coords = locationStrings[i].split(",");
            locations[i][0] = Double.valueOf(coords[0]);
            locations[i][1] = Double.valueOf(coords[1]);
        }// w  w w  .j a v a 2  s  . c o m
        filterQuery.locations(locations);
    }

    String keywords = te.getProperties().getKeywords();
    if (keywords != null && keywords.length() > 0) {
        filterQuery.track(keywords.split(","));
    }

    String userIds = te.getProperties().getUserIds();
    if (userIds != null) {
        String[] stringUserIds = userIds.split(",");
        long[] longUserIds = new long[stringUserIds.length];
        for (int i = 0; i < stringUserIds.length; i++) {
            longUserIds[i] = Long.valueOf(stringUserIds[i]);
        }
        filterQuery.follow(longUserIds);
    }

    if (allLocationsString == null && keywords == null && userIds == null) {
        throw new IllegalArgumentException("At least one filter parameter is required");
    }

    return filterQuery;
}

From source file:org.wso2.carbon.inbound.custom.poll.TwitterStreamData.java

License:Open Source License

/**
 * Setting up a connection with Twitter Stream API with the given
 * credentials/*from  www  .j a  v  a2 s. c  o m*/
 *
 * @throws TwitterException
 */
private void setupConnection() throws TwitterException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to setup the connection with the twitter streaming endpoint");
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessSecret);
    StatusListener statusStreamsListener;
    UserStreamListener userStreamListener;
    SiteStreamsListener siteStreamslistener;
    TwitterStream twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    String twitterOperation = properties.getProperty(TwitterConstant.TWITTER_OPERATION);
    if (twitterOperation.equals(TwitterConstant.FILTER_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.LINK_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) {
        statusStreamsListener = new StatusListenerImpl();
        twitterStream.addListener(statusStreamsListener);
    } else if (twitterOperation.equals(TwitterConstant.USER_STREAM_OPERATION)) {
        userStreamListener = new UserStreamListenerImpl();
        twitterStream.addListener(userStreamListener);
    } else if (twitterOperation.equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        siteStreamslistener = new siteStreamsListenerImpl();
        twitterStream.addListener(siteStreamslistener);
    } else {
        handleException("The operation :" + twitterOperation + " not found");
    }

    /* Synchronously retrieves public statuses that match one or more filter predicates.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FILTER_STREAM_OPERATION)) {
        FilterQuery query = new FilterQuery();
        if (languages != null) {
            query.language(languages);
        }
        if (tracks != null) {
            query.track(tracks);
        }
        if (follow != null) {
            query.follow(follow);
        }
        if (filterLevel != null) {
            query.filterLevel(filterLevel);
        }
        query.count(count);
        twitterStream.filter(query);
    }

    /* Returns a small random sample of all public statuses. */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) {

        if (languages != null) {
            if (languages.length == 1) {
                twitterStream.sample(languages[1]);
            } else {
                handleException("A language can be used for the sample operation");
            }
        }
        twitterStream.sample();
    }
    /* Asynchronously retrieves all public statuses.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.firehose(count);
        }
    }
    /*
     User Streams provide a stream of data and events specific to the
     authenticated user.This provides to access the Streams messages for a
     single user.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.USER_STREAM_OPERATION)) {
        if (tracks != null) {
            twitterStream.user(tracks);
        }
        twitterStream.user();
    }
    /*
     * Link Streams provide asynchronously retrieves all statuses containing 'http:' and 'https:'.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.LINK_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.links(count);
        }
    }
    /*
     * User Streams provide a stream of data and events specific to the
     * authenticated user.This provides to access the Streams messages for a
     * single user.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.RETWEET_STREAM_OPERATION)) {
        twitterStream.retweet();
    }
    /*
     * Site Streams allows services, such as web sites or mobile push
     * services, to receive real-time updates for a large number of users.
     * Events may be streamed for any user who has granted OAuth access to
     * your application. Desktop applications or applications with few users
     * should use user streams.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        twitterStream.site(withFollowings, follow);
    }

}

From source file:org.wso2.carbon.inbound.twitter.poll.TwitterStreamData.java

License:Open Source License

/**
 * Setting up a connection with Twitter Stream API with the given
 * credentials/*  w  w  w. j a v a 2s .  c  om*/
 *
 * @throws TwitterException
 */
private void setupConnection() throws TwitterException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to setup the connection with the twitter streaming endpoint");
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setJSONStoreEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessSecret);
    StatusListener statusStreamsListener;
    UserStreamListener userStreamListener;
    SiteStreamsListener siteStreamslistener;
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    String twitterOperation = properties.getProperty(TwitterConstant.TWITTER_OPERATION);
    if (twitterOperation.equals(TwitterConstant.FILTER_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.LINK_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.SAMPLE_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.RETWEET_STREAM_OPERATION)) {
        statusStreamsListener = new StatusListenerImpl();
        twitterStream.addListener(statusStreamsListener);
    } else if (twitterOperation.equals(TwitterConstant.USER_STREAM_OPERATION)) {
        userStreamListener = new UserStreamListenerImpl();
        twitterStream.addListener(userStreamListener);
    } else if (twitterOperation.equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        siteStreamslistener = new siteStreamsListenerImpl();
        twitterStream.addListener(siteStreamslistener);
    } else {
        handleException("The operation :" + twitterOperation + " not found");
    }

    /* Synchronously retrieves public statuses that match one or more filter predicates.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FILTER_STREAM_OPERATION)) {
        FilterQuery query = new FilterQuery();
        if (languages != null) {
            query.language(languages);
        }
        if (tracks != null) {
            query.track(tracks);
        }
        if (follow != null) {
            query.follow(follow);
        }
        if (locations != null) {
            query.locations(locations);
        }
        if (filterLevel != null) {
            query.filterLevel(filterLevel);
        }
        if (follow == null & tracks == null & locations == null) {
            handleException("At least follow, locations, or track must be specified.");
        }
        query.count(count);
        twitterStream.filter(query);
    }

    /* Returns a small random sample of all public statuses. */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) {

        if (languages != null) {
            if (languages.length == 1) {
                twitterStream.sample(languages[1]);
            } else {
                handleException("A language can be used for the sample operation");
            }
        } else {
            twitterStream.sample();
        }
    }
    /* Asynchronously retrieves all public statuses.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.firehose(count);
        }
    }
    /*
     User Streams provide a stream of data and events specific to the
    authenticated user.This provides to access the Streams messages for a
    single user.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.USER_STREAM_OPERATION)) {
        if (tracks != null) {
            twitterStream.user(tracks);
        } else {
            twitterStream.user();
        }
    }
    /*
     * Link Streams provide asynchronously retrieves all statuses containing 'http:' and 'https:'.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.LINK_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.links(count);
        }
    }
    /*
     * User Streams provide a stream of data and events specific to the
    * authenticated user.This provides to access the Streams messages for a
    * single user.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.RETWEET_STREAM_OPERATION)) {
        twitterStream.retweet();
    }
    /*
     * Site Streams allows services, such as web sites or mobile push
    * services, to receive real-time updates for a large number of users.
    * Events may be streamed for any user who has granted OAuth access to
    * your application. Desktop applications or applications with few users
    * should use user streams.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        twitterStream.site(withFollowings, follow);
    }

}

From source file:toninbot.ToninBot.java

/**
 * @param args the command line arguments
 */// ww  w. ja  va2  s  .  c  o m
public static void main(String[] args) {

    AccessToken accessToken = new AccessToken(Credenciales.token, Credenciales.tokenSecret);
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(Credenciales.consumerKey);
    builder.setOAuthConsumerSecret(Credenciales.consumerSecret);

    Configuration configuration = builder.build();
    TwitterStreamFactory twStreamFactory = new TwitterStreamFactory(configuration);
    TwitterStream twitterStream = twStreamFactory.getInstance();
    twitterStream.setOAuthAccessToken(accessToken);

    ToninStatusListener listener = new ToninStatusListener();
    twitterStream.addListener(listener);

    FilterQuery filtre = new FilterQuery();
    filtre.follow(184742273L, 2841338087L);//Allegue y proyectoPSIa1
    //filtre.follow(2841338087L);//proyectoPSIa1

    twitterStream.filter(filtre);
}

From source file:uk.ac.susx.tag.method51.twitter.params.FilterQueryParams.java

License:Apache License

public FilterQuery buildFilterQuery() {

    if (getKeywords().size() == 0 && getFollowIds().size() == 0 && getLocations().size() == 0)
        throw new RuntimeException("No keywords or user ids provided");

    final FilterQuery query = new FilterQuery();

    if (!getLanguages().isEmpty()) {
        LOG.info("Languages: {}", getLanguages());
        query.language(getLanguages().toArray(new String[getLanguages().size()]));
    }// ww  w  . j av a  2  s . c o m

    if (!getKeywords().isEmpty()) {
        LOG.info("Tracking keywords: {}", getKeywords());
        query.track(getKeywords().toArray(new String[getKeywords().size()]));
    }

    if (!getFollowIds().isEmpty()) {
        LOG.info("Tracking ids: {}", getFollowIds());
        query.follow(ArrayUtil.unbox(getFollowIds().toArray(new Long[getFollowIds().size()])));
    }

    if (!getLocations().isEmpty()) {
        LOG.info("Locations co-ords: {}", getLocations());
        query.locations(toArray(getLocations()));
    }

    return query;

}

From source file:wordgame.WordGame.java

public static void initGame(String file) throws FileNotFoundException {
    Scanner s = new Scanner(new File(file)); //open the file
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true) //populate the twitter details with the proper API informatin
            .setOAuthConsumerKey(s.nextLine()).setOAuthConsumerSecret(s.nextLine())
            .setOAuthAccessToken(s.nextLine()).setOAuthAccessTokenSecret(s.nextLine());
    TwitterFactory tf = new TwitterFactory(cb.build());
    t = tf.getInstance();//w  ww .  j a v  a2 s  .c om
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 731852008030916608L }); //Track our tweets
    twitterStream.addListener(new MentionListener()); //Set the listener to our MentionListener class
    twitterStream.filter(filterQuery); //begin listening
}