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:PrintUserStream.java

License:Apache License

public PrintUserStream() {
    twitterStream = new TwitterStreamFactory().getInstance();

}

From source file:StreamEmoContentTime.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    startup();/*from w w w  .j  av  a  2  s  .c  o m*/
    final JSONParser parser = new JSONParser();

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    RawStreamListener listener = new RawStreamListener() {
        @Override
        public void onMessage(String rawJSON) {
            //System.out.println(rawJSON);
            try {
                JSONObject json = (JSONObject) new JSONParser().parse(rawJSON);
                String lang = (String) json.get("lang");
                if (lang.equals("en")) {
                    String text = (String) json.get("text");

                    String time = (String) json.get("created_at");
                    int emoscore = scoreTweet(text);

                    try {
                        Statement stmt = c.createStatement();
                        String sql = "INSERT INTO tbl2(time, score, text) " + "VALUES ('" + time + "','"
                                + emoscore + "','" + text.replaceAll("'", "''") + "')";
                        System.out.println("Score: " + emoscore + "\t" + text);
                        stmt.executeUpdate(sql);
                        stmt.close();
                        //c.commit();
                    } catch (Exception e) {
                        System.err.println(e.getClass().getName() + ": " + e.getMessage());
                        System.exit(0);
                    }

                }

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //System.out.println(rawJSON);
        }

        @Override
        public void onException(Exception ex) {

            ex.printStackTrace();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.sample();
}

From source file:GetEmoContent.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    startup();//from w w  w .j  av  a 2s . c  o m
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            if (status.getLang().equals("en"))
            //if(status.getText().toLowerCase().contains("trump")|| status.getText().toLowerCase().contains("drumpf"))
            {

                int score = scoreTweet(status.getText());

                System.out
                        .println("score: " + score + " language " + status.getLang() + " " + status.getText());

                //add this to the database
                try {
                    Statement stmt = c.createStatement();
                    String sql = "INSERT INTO tbl1(f1, f2) " + "VALUES ('\""
                            + status.getText().replaceAll("'", "''") + "\"', '" + score + "')";

                    stmt.executeUpdate(sql);
                    stmt.close();
                    //c.commit();
                } catch (Exception e) {
                    System.err.println(e.getClass().getName() + ": " + e.getMessage());
                    System.exit(0);
                }
            }
        }

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

From source file:ar.com.zauber.commons.social.twitter.impl.streaming.TweetFetcher.java

License:Apache License

/**
 * Creates the {@link TwitterStream}//from  w w w. ja  v a 2  s. c om
 * 
 * @param user
 * @param password
 * @return
 */
private TwitterStream createStream(final String user, final String password) {
    final TwitterStream stream = new TwitterStreamFactory().getInstance(new BasicAuthorization(user, password));

    stream.addListener(new StatusListener() {
        @Override
        public void onStatus(final Status status) {
            try {
                T t = transformer.transform(status);
                closure.execute(t);
            } catch (Throwable ex) {
                logger.error("Exception en onStatus", ex);
            }

        }

        @Override
        public void onException(final Exception e) {
            logger.error("Exception on TwitterStream", e);
        }

        @Override
        public void onTrackLimitationNotice(final int numberOfLimitedStatuses) {
            logger.warn("onTrackLimitationNotice: Number of limited " + "statuses: {}",
                    numberOfLimitedStatuses);
        }

        @Override
        public void onDeletionNotice(final StatusDeletionNotice statusDeletionNotice) {
            logger.warn("statusDeletionNotice: {}", statusDeletionNotice);
        }

        @Override
        public void onScrubGeo(final long userId, final long upToStatusId) {
            logger.warn("scrubGeo: {} {}", userId, upToStatusId);
        }
    });

    stream.addConnectionLifeCycleListener(new ConnectionLifeCycleListener() {
        @Override
        public void onDisconnect() {
            logger.warn("Disconnected from Twitter!");
        }

        @Override
        public void onConnect() {
        }

        @Override
        public void onCleanUp() {
        }
    });

    return stream;
}

From source file:at.aictopic1.twitter.AICStream.java

public void startStream() {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(getListener());

    twitterStream.filter(getQuery());

}

From source file:at.aictopic1.twitter.AICStream.java

public void stopStream() {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.shutdown();
}

From source file:ca.blackperl.WordFilterStreamBuilder.java

License:Apache License

public void main() {
    // create the twitter search listener
    PhraseListener listener = new PhraseListener(args);

    // Connect to twitter.
    final TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    // The listener to the twitter connection
    twitterStream.addListener(listener);

    // Build a search configuration
    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));
            }//w w w. j a  v a 2s .  c o  m
        } else {
            track.addAll(Arrays.asList(arg.split(",")));
        }
    }
    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 the listener methods continuously.

    // pass the search configuration to the twitter library to start the search
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));

    // Create a timer
    final Timer timer = new Timer();

    // Create a task to run every minute, starting in one minute.
    TimerTask summaryTask = new SummaryTask(listener, timer, twitterStream);
    timer.schedule(summaryTask, TimeToRunInSeconds * 1000, TimeToRunInSeconds * 1000);
}

From source file:cc.twittertools.stream.GatherStatusStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    PatternLayout layoutStandard = new PatternLayout();
    layoutStandard.setConversionPattern("[%p] %d %c %M - %m%n");

    PatternLayout layoutSimple = new PatternLayout();
    layoutSimple.setConversionPattern("%m%n");

    // Filter for the statuses: we only want INFO messages
    LevelRangeFilter filter = new LevelRangeFilter();
    filter.setLevelMax(Level.INFO);
    filter.setLevelMin(Level.INFO);
    filter.setAcceptOnMatch(true);//from w w  w.ja va 2 s.  co m
    filter.activateOptions();

    TimeBasedRollingPolicy statusesRollingPolicy = new TimeBasedRollingPolicy();
    statusesRollingPolicy.setFileNamePattern("statuses.log" + HOUR_ROLL);
    statusesRollingPolicy.activateOptions();

    RollingFileAppender statusesAppender = new RollingFileAppender();
    statusesAppender.setRollingPolicy(statusesRollingPolicy);
    statusesAppender.addFilter(filter);
    statusesAppender.setLayout(layoutSimple);
    statusesAppender.activateOptions();

    TimeBasedRollingPolicy warningsRollingPolicy = new TimeBasedRollingPolicy();
    warningsRollingPolicy.setFileNamePattern("warnings.log" + HOUR_ROLL);
    warningsRollingPolicy.activateOptions();

    RollingFileAppender warningsAppender = new RollingFileAppender();
    warningsAppender.setRollingPolicy(statusesRollingPolicy);
    warningsAppender.setThreshold(Level.WARN);
    warningsAppender.setLayout(layoutStandard);
    warningsAppender.activateOptions();

    ConsoleAppender consoleAppender = new ConsoleAppender();
    consoleAppender.setThreshold(Level.WARN);
    consoleAppender.setLayout(layoutStandard);
    consoleAppender.activateOptions();

    // configures the root logger
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.removeAllAppenders();
    rootLogger.addAppender(consoleAppender);
    rootLogger.addAppender(statusesAppender);
    rootLogger.addAppender(warningsAppender);

    // creates a custom logger and log messages
    final Logger logger = Logger.getLogger(GatherStatusStream.class);

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    RawStreamListener rawListener = new RawStreamListener() {

        @Override
        public void onMessage(String rawString) {
            cnt++;
            logger.info(rawString);
            if (cnt % 100 == 0) {
                System.out.println(cnt + " messages received.");
            }
        }

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

    };

    twitterStream.addListener(rawListener);
    FilterQuery fq = new FilterQuery();
    /* double locations[][]={{112.0,-44.0},{155.0,-10.5}}; 
     fq.locations(locations);*/
    long ids[] = { 87818409, 16675569 };
    fq.follow(ids);
    twitterStream.filter(fq);
    //twitterStream.sample();
}

From source file:com.accumulobook.designs.graph.TwitterGraph.java

License:Apache License

public static void ingest(final String[] args, final BatchWriter writer, int seconds) throws Exception {

    String token = args[0];//  w w w  . jav a2 s . c o m
    String tokenSecret = args[1];
    String consumerKey = args[2];
    String consumerSecret = args[3];

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(new TGStatusListener(writer));

    AccessToken accessToken = new AccessToken(token, tokenSecret);

    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.setOAuthAccessToken(accessToken);

    System.out.println("processing twitter stream ...");
    twitterStream.sample();

    Thread.sleep(seconds * 1000);

    System.out.println("shutting down twitter stream.");
    twitterStream.shutdown();

    writer.flush();
}

From source file:com.dittdesign.twittersentimentfetcher.TwitterSentimentFetcher.java

public TwitterSentimentFetcher() {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

}