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() 

Source Link

Document

Creates a TwitterStreamFactory with the root configuration.

Usage

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void mUpdateStream(Token aToken) {
    try {//  w  w w . j  av a  2s . com
        String[] lKeywordArray = new String[mKeywords.size()];
        int lIdx = 0;
        for (String lKeyword : mKeywords.keySet()) {
            lKeywordArray[lIdx] = lKeyword;
            lIdx++;
            if (lIdx >= MAX_STREAM_KEYWORDS_TOTAL) {
                break;
            }
        }
        if (lIdx > mStatsMaxKeywords) {
            mStatsMaxKeywords = lIdx;
        }

        FilterQuery lFilter = new FilterQuery(0, new long[] {}, lKeywordArray);
        // if no TwitterStream object created up to now, create one...
        if (mTwitterStream == null) {
            mTwitterStream = new TwitterStreamFactory().getInstance();
            mTwitterStream.addListener(mTwitterStreamListener);
            mTwitterStream.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret());
            AccessToken lAccessToken = new AccessToken(mSettings.getAccessKey(), mSettings.getAccessSecret());
            mTwitterStream.setOAuthAccessToken(lAccessToken);
        }
        // apply the filter to the stream object
        mTwitterStream.filter(lFilter);
    } catch (Exception lEx) {
        String lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        aToken.setInteger("code", -1);
        aToken.setString("msg", lMsg);
    }
}

From source file:org.nosceon.titanite.examples.TweetEventSource.java

License:Apache License

@Override
protected void onSubscribe(String id) {
    if (stream == null) {
        stream = new TwitterStreamFactory().getInstance();
        stream.addListener(new StatusAdapter() {

            @Override/*from  w  w w  . ja  v a 2  s.co  m*/
            public void onStatus(Status status) {
                GeoLocation location = status.getGeoLocation();
                if (location != null) {
                    send("{ \"lat\" : " + location.getLatitude() + ", \"lng\" : " + location.getLongitude()
                            + " }");
                }
            }

        });
        stream.filter(new FilterQuery().locations(RANGE));
    }
}

From source file:org.richfaces.examples.tweetstream.dataserver.listeners.TweetStreamListener.java

License:Open Source License

public void startTwitterStream() {
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.track(tracks);/*from   w  w w  . jav a2s. c  o m*/

    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(this);
    twitterStream.filter(filterQuery);
}

From source file:org.seasr.meandre.apps.twitter.TwitterToTuple.java

public void run() {
    try {/*from w w w  .  jav a  2s .com*/
        Thread.currentThread().sleep(5000);
        console.info("Start Twitter reader");

        /*
        Twitter tweet = new Twitter("seasrSalad" , "0penNlp");
        Status status = tweet.updateStatus("Hello world2 {\"name\":\"mike\"}");
        User me = status.getUser();
        console.info("user is " + me.getId());
        */

        // twitterStream = new TwitterStream("seasrSalad", "0penNlp", this);

        // this will force an exception if invalid
        TwitterStream tsTmp = new TwitterStreamFactory().getInstance(userName, passwd);
        StatusStream tmp = tsTmp.getSampleStream();
        tmp.close();
        tsTmp.cleanup();

        // if we got this far, we are good to go
        twitterStream = new TwitterStreamFactory().getInstance(userName, passwd);
        twitterStream.setStatusListener(this);

        // for a continuous unfiltered stream:
        twitterStream.sample();

        /*
        int count = 0; // last 100 messages, NOT supported
        int[] follow = new int[0]; // don't follow any specific users
        String[] tags = new String[]{"#apple", "Balloon Boy"};
        twitterStream.filter(count, follow, tags);
        */

        // black forever
        waitForStatus();

    } catch (Exception e) {
        console.info("unable to read twitter " + e.toString());
    } finally {
        if (twitterStream != null)
            twitterStream.cleanup();
    }

    console.info("Stop Twitter service");

    noExceptions = false;
    synchronized (buffer) {
        buffer.notifyAll();
    }

}

From source file:org.socialsketch.tool.rubbish.experiments.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application.//from w  w  w  . jav a  2 s  . c o  m
 *
 * @param args
 */
public static void main(String[] args) throws TwitterException {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        @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();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.sample();
    //twitterStream.
}

From source file:org.socialsketch.tool.rubbish.twitterstream.PrintFilterStream.java

License:Apache License

/**
 * Main entry of this application.// ww  w.  j av a  2  s . com
 *
 * @param args follow(comma separated user ids) track(comma separated filter terms)
 * @throws twitter4j.TwitterException
 */
public static void main(String[] args) throws TwitterException {
    //        if (args.length < 1) {
    //            System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
    //            System.exit(-1);
    //        }

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        @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();
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);

    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();

    //        for (String arg : args) {
    //            if (isNumericalArgument(arg)) {
    //                for (String id : arg.split(",")) {
    //                    follow.add(Long.parseLong(id));
    //                }
    //            } else {
    //                track.addAll(Arrays.asList(arg.split(",")));
    //            }
    //        }
    track.add("void setup draw");
    track.add("void size");

    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }

    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));
}

From source file:org.todoke.countstream.Main.java

License:Apache License

public static void main(String[] args) {
    if (args.length != 1) {
        System.out.println("usage: java org.todoke.hashcount.Main [comma separated terms to track]");
        System.exit(-1);/*from  w  w w .  j av  a  2s .com*/
    }
    logger.info("terms to track: " + args[0]);
    String[] terms = args[0].split(",");
    FilterQuery query = new FilterQuery().track(terms);
    TwitterStream stream = new TwitterStreamFactory().getInstance();
    StringBuffer path = new StringBuffer(args[0].length());
    for (String term : terms) {
        if (0 != path.length()) {
            path.append("-");
        }
        path.append(term.replaceAll("#", ""));
    }
    Callback callback = new Callback(terms);
    Counter counter = new Counter(callback);

    stream.addListener(counter);
    stream.filter(query);
}

From source file:org.unimonk.flume.source.twitter.TwitterSource.java

License:Apache License

@Override
public void start() {

    final ChannelProcessor channel = getChannelProcessor();

    StatusListener listener = new StatusListener() {
        @Override/*from   www.j av  a2 s. c om*/
        public void onStatus(Status status) {

            Tweet tweet = new Tweet();
            tweet.setId(status.getId());
            tweet.setUserId(status.getUser().getId());
            tweet.setLatitude(status.getGeoLocation().getLatitude());
            tweet.setLongitude(status.getGeoLocation().getLongitude());
            tweet.setText(status.getText());
            tweet.setCreatedAt(new Timestamp(status.getCreatedAt().getTime()));

            Event event = EventBuilder.withBody(tweet.toString(), Charsets.UTF_8);
            sourceCounter.incrementAppendReceivedCount();
            try {
                channel.processEvent(event);
                sourceCounter.incrementEventAcceptedCount();
            } catch (ChannelException ex) {
                logger.error("In Twitter source {} : Unable to process event due to exception {}.", getName(),
                        ex);

            }
        }

        // This listener will ignore everything except for new tweets
        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }

        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }
    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { consumerKey, accessToken });

    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keywords.length == 0) {
        logger.debug("Starting up Twitter sampling...");
        twitterStream.sample();
    } else {
        logger.debug("Starting up Twitter filtering...");
        FilterQuery query = new FilterQuery().track(keywords);
        twitterStream.filter(query);
    }
    this.sourceCounter.start();
    super.start();
}

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

License:BSD License

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

    Options opts = new Options(sCOMMON_OPTS + ",p=port:,track:,sample,json,sanitize",
            SerializeOpts.getOptionDefs());
    opts.parse(args);/* w w  w.ja v a2 s.c o  m*/
    mSerializeOpts = this.getSerializeOpts(opts);
    final boolean bJson = opts.hasOpt("json");
    final boolean bSanitize = opts.hasOpt("sanitize");

    args = opts.getRemainingArgs();

    final OutputPort port = mShell.getEnv().getOutputPort(opts.getOptStringRequired("port"), true);

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            try {
                if (bJson) {
                    String json = DataObjectFactory.getRawJSON(status);

                    PrintWriter writer = port.asPrintWriter(mSerializeOpts);
                    writer.println(json);
                    writer.close();

                } else {
                    TwitterWriter mWriter = new TwitterWriter(port.asXMLStreamWriter(mSerializeOpts),
                            bSanitize);
                    mWriter.startDocument();
                    mWriter.startElement(TwitterWriter.kTWITTER_NS, "twitter");
                    mWriter.writeDefaultNamespace();
                    mWriter.write("status", status);
                    mWriter.endElement();
                    mWriter.endDocument();
                    mWriter.closeWriter();
                    port.writeSequenceTerminator(mSerializeOpts);
                }

            } catch (Exception e) {
                onException(e);
            }

        }

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

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

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

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

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }

    };

    try {

        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
        twitterStream.addListener(listener);

        // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.

        // FilterQuery filter = new FilterQuery().track(Util.toStringArray(args));

        // twitterStream.filter(filter);
        if (opts.hasOpt("sample"))
            twitterStream.sample();
        else
            twitterStream.filter(new FilterQuery().track(opts.getOptStringRequired("track").split(",")));

    } finally {

    }
    return 0;

}

From source file:paxchecker.check.TwitterStreamer.java

public static void runTwitterStream(Twitter twitter, String[] handles) {
    if (isStreamingTwitter()) {
        return;/*  w  w w .jav a 2 s .c  o  m*/
    }
    System.out.println(Arrays.toString(handles));
    myStream = new TwitterStreamFactory().getInstance(twitter.getAuthorization());
    myStream.addListener(listener);
    myStream.user(handles);
}