Example usage for twitter4j TwitterStreamFactory TwitterStreamFactory

List of usage examples for twitter4j TwitterStreamFactory TwitterStreamFactory

Introduction

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

Prototype

public TwitterStreamFactory(String configTreePath) 

Source Link

Document

Creates a TwitterStreamFactory with a specified config tree.

Usage

From source file:cloudcomputebot.CloudComputeBot.java

License:Open Source License

public static void main(String[] args) {
    TwitterLib.init();/*w  ww . j  a  v  a2s.  c o m*/
    t = TwitterLib.t;
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 4741197613L });
    twitterStream.addListener(new MentionListener());
    twitterStream.filter(filterQuery);
}

From source file:co.cask.cdap.template.etl.realtime.source.TwitterSource.java

License:Apache License

@Override
public void initialize(RealtimeContext context) throws Exception {
    super.initialize(context);

    // Disable chatty logging from twitter4j.
    System.setProperty("twitter4j.loggerFactory", "twitter4j.NullLoggerFactory");

    Schema.Field idField = Schema.Field.of(ID, Schema.of(Schema.Type.LONG));
    Schema.Field msgField = Schema.Field.of(MSG, Schema.of(Schema.Type.STRING));
    Schema.Field langField = Schema.Field.of(LANG, Schema.nullableOf(Schema.of(Schema.Type.STRING)));
    Schema.Field timeField = Schema.Field.of(TIME, Schema.nullableOf(Schema.of(Schema.Type.LONG)));
    Schema.Field favCount = Schema.Field.of(FAVC, Schema.of(Schema.Type.INT));
    Schema.Field rtCount = Schema.Field.of(RTC, Schema.of(Schema.Type.INT));
    Schema.Field sourceField = Schema.Field.of(SRC, Schema.nullableOf(Schema.of(Schema.Type.STRING)));
    Schema.Field geoLatField = Schema.Field.of(GLAT, Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)));
    Schema.Field geoLongField = Schema.Field.of(GLNG, Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)));
    Schema.Field reTweetField = Schema.Field.of(ISRT, Schema.of(Schema.Type.BOOLEAN));
    schema = Schema.recordOf("tweet", idField, msgField, langField, timeField, favCount, rtCount, sourceField,
            geoLatField, geoLongField, reTweetField);

    statusListener = new StatusListener() {
        @Override// ww  w.j  av a  2s  .  c  o m
        public void onStatus(Status status) {
            tweetQ.add(status);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            // No-op
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            // No-op
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            // No-op
        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {
            // No-op
        }

        @Override
        public void onException(Exception e) {
            // No-op
        }
    };

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(false).setOAuthConsumerKey(twitterConfig.consumerKey)
            .setOAuthConsumerSecret(twitterConfig.consumeSecret).setOAuthAccessToken(twitterConfig.accessToken)
            .setOAuthAccessTokenSecret(twitterConfig.accessTokenSecret);

    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    twitterStream.addListener(statusListener);
    twitterStream.sample();
}

From source file:co.cask.hydrator.plugin.realtime.source.TwitterSource.java

License:Apache License

@Override
public void initialize(RealtimeContext context) throws Exception {
    super.initialize(context);

    // Disable chatty logging from twitter4j.
    System.setProperty("twitter4j.loggerFactory", "twitter4j.NullLoggerFactory");

    statusListener = new StatusListener() {
        @Override/*from  w w w.  j ava2  s.c o  m*/
        public void onStatus(Status status) {
            tweetQ.add(status);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            // No-op
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            // No-op
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            // No-op
        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {
            // No-op
        }

        @Override
        public void onException(Exception e) {
            // No-op
        }
    };

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(false).setOAuthConsumerKey(twitterConfig.consumerKey)
            .setOAuthConsumerSecret(twitterConfig.consumeSecret).setOAuthAccessToken(twitterConfig.accessToken)
            .setOAuthAccessTokenSecret(twitterConfig.accessTokenSecret);

    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    twitterStream.addListener(statusListener);
    twitterStream.sample();
}

From source file:ColourUs.Stream.java

public Stream(Configuration config, Trending trending) {
    this.trending = trending;

    TwitterStreamFactory tsf = new TwitterStreamFactory(config);
    twitterStream = tsf.getInstance();//from  w  ww.j  ava 2  s .co  m

    twitterStream.addListener(this);
    filter = new FilterQuery();
    filter.track(new String[] { "I", "you", "he", "she", "them", "they", "us", "our", "her", "him", "they're",
            "I'm", "my", "your", "is", "was", "are", "were" });
}

From source file:com.babatunde.twittergoogle.Utility.java

public void postToGoogle(PlusDomains s, String id, String hashtag) {
    try {//from w  w w  .  j a  v a  2 s . c om
        final PlusDomains serve = s;
        final String circleID = id;
        listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                String msg = status.getUser().getName() + " - " + "@" + status.getUser().getScreenName() + " - "
                        + status.getText();
                System.out.println(msg);
                //Create a list of ACL entries
                if (serve != null && (!circleID.isEmpty() || (circleID != null))) {
                    PlusDomainsAclentryResource resource = new PlusDomainsAclentryResource();
                    resource.setType("domain").setType("circle").setId(circleID);

                    //Get Emails of people in the circle.
                    List<PlusDomainsAclentryResource> aclEntries = new ArrayList<PlusDomainsAclentryResource>();
                    aclEntries.add(resource);

                    Acl acl = new Acl();

                    acl.setItems(aclEntries);
                    acl.setDomainRestricted(true); // Required, this does the domain restriction

                    // Create a new activity object
                    Activity activity = new Activity()
                            .setObject(new Activity.PlusDomainsObject().setOriginalContent(msg)).setAccess(acl);
                    try {
                        // Execute the API request, which calls `activities.insert` for the logged in user
                        activity = serve.activities().insert("me", activity).execute();
                    } catch (IOException ex) {
                        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }

        };
    } catch (Exception e) {
    }

    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    twitterStream.addListener(listener);
    String str[] = { hashtag };
    twitterStream.shutdown();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
    }
    twitterStream.filter(new FilterQuery().track(str));

}

From source file:com.cask.twitter.TweetStream.java

License:Apache License

@Override
public void initialize(FlowletContext context) {
    statusListener = new StatusListener() {
        @Override/*from   www . j  a  va  2s .  c o m*/
        public void onStatus(Status status) {
            for (HashtagEntity hash : status.getHashtagEntities()) {
                tweetQ.add(hash.getText());
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

        }

        @Override
        public void onTrackLimitationNotice(int i) {

        }

        @Override
        public void onScrubGeo(long l, long l2) {

        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {

        }

        @Override
        public void onException(Exception e) {
            LOG.error(e.getMessage());
        }
    };

    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(false)
            //Provide Twitter Credentials through Runtime Arguments.
            .setOAuthConsumerKey(context.getRuntimeArguments().get("ConsumerKey"))
            .setOAuthConsumerSecret(context.getRuntimeArguments().get("ConsumerSecret"))
            .setOAuthAccessToken(context.getRuntimeArguments().get("AccessToken"))
            .setOAuthAccessTokenSecret(context.getRuntimeArguments().get("AccessTokenSecret"));

    tStream = new TwitterStreamFactory(cb.build()).getInstance();
    //For testing, we can disable Twitter Stream and use testStream to send sample hashTags.
    if (!context.getRuntimeArguments().containsKey("disableLiveStream")) {
        tStream.addListener(statusListener);
        tStream.sample();
    }
}

From source file:com.chimpler.example.TwitterStatusProducer.java

License:Apache License

public synchronized void startSample(String username, String password) {
    if (twitterStream != null) {
        return;//w w w .  jav  a2s.  c o m
    }
    TwitterStreamFactory factory = new TwitterStreamFactory(
            new ConfigurationBuilder().setUser(username).setPassword(password).build());
    twitterStream = factory.getInstance();
    twitterStream.addListener(new StatusAdapter() {
        public void onStatus(Status status) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "OK");
            map.put("createdAt", status.getCreatedAt().toString());
            map.put("username", status.getUser().getName());
            map.put("profileImageUrl", status.getUser().getMiniProfileImageURL());
            map.put("text", status.getText());
            cometTwitterService.publishMessage(map, Long.toString(status.getId()));
        }

        @Override
        public void onException(Exception ex) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "ERR");
            map.put("text", ex.getMessage());
            cometTwitterService.publishMessage(map, "-1");
            stopSample();
        }
    });
    logger.log(Level.INFO, "Starting listening to twitter sample");
    twitterStream.sample();
}

From source file:com.cloudera.flume.source.TwitterSource.java

License:Apache License

/**
 * The initialization method for the Source. The context contains all the
 * Flume configuration info, and can be used to retrieve any configuration
 * values necessary to set up the Source.
 *///from   w w w.  j  a  v a  2s.c  o m
@Override
public void configure(Context context) {
    consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY_KEY);
    consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET_KEY);
    accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN_KEY);
    accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET_KEY);

    String keywordString = context.getString(TwitterSourceConstants.KEYWORDS_KEY, "");
    keywords = keywordString.split(",");
    for (int i = 0; i < keywords.length; i++) {
        keywords[i] = keywords[i].trim();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
}

From source file:com.daiv.android.twitter.utils.Utils.java

License:Apache License

public static TwitterStream getStreamingTwitter(Context context, AppSettings settings) {
    settings = AppSettings.getInstance(context);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(AppSettings.TWITTER_CONSUMER_KEY)
            .setOAuthConsumerSecret(AppSettings.TWITTER_CONSUMER_SECRET)
            .setOAuthAccessToken(settings.authenticationToken)
            .setOAuthAccessTokenSecret(settings.authenticationTokenSecret);
    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    return tf.getInstance();
}

From source file:com.datatorrent.contrib.twitter.TwitterSampleInput.java

License:Open Source License

@Override
public void setup(OperatorContext context) {
    operatorThread = Thread.currentThread();

    if (feedMultiplier != 1) {
        logger.info("Load set to be {}% of the entire twitter feed", feedMultiplier);
    }/* ww  w . j  ava  2s  .  co m*/

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(debug).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    ts = new TwitterStreamFactory(cb.build()).getInstance();
}