Example usage for twitter4j TwitterStreamFactory getInstance

List of usage examples for twitter4j TwitterStreamFactory getInstance

Introduction

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

Prototype

public TwitterStream getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:com.tweetmyhome.TweetMyHome.java

public TweetMyHome() throws TweetMyHomeException, IOException, TweetStringException {

    Log.setLogger(new MyCustomLogger());
    p = new TweetMyHomeProperties();
    if (!p.isFirstTimeCreated()) {
        if (p.getValueByKey(Key.debuggin).equalsIgnoreCase("true")) {
            Log.set(Log.LEVEL_DEBUG);/*from ww w.jav  a 2  s.  c om*/
            Log.set(Log.LEVEL_TRACE);
        } else {
            Log.set(Log.LEVEL_INFO);
        }
    } else {
        File file = new File(TweetMyHomeProperties.FILE_NAME);
        info(String.format("Properties file created at: %s", file.getAbsolutePath()));
        info(String.format("Please edit '%s' to correct aplication function", TweetMyHomeProperties.FILE_NAME));
        info("Exiting aplication...");
        System.exit(0);
    }
    tweetCount = new TweetMensajeCount(COUNT_FILE);
    tmh_device_xml = XMLFilesManager.getTweetMyHomeDevices();
    if (tmh_device_xml == null) {
        throw new TweetMyHomeException(
                "Fail to read [" + XMLFilesManager.TWEET_MY_HOME_DEVICES_XML_FILE + "] file");
    }
    tmh_dic_xml = XMLFilesManager.getTweetMyHomeDictionaryCommand();
    if (tmh_dic_xml == null) {
        throw new TweetMyHomeException(
                "Fail to read [" + XMLFilesManager.TWEET_MY_HOME_DICTIONARY_XML_FILE + "] file");
    }
    tweetDictionary = new TweetStringDictionary(tmh_dic_xml);
    trace("XML Files already Readed [" + XMLFilesManager.TWEET_MY_HOME_DEVICES_XML_FILE + ","
            + XMLFilesManager.TWEET_MY_HOME_DICTIONARY_XML_FILE + "]");

    if (!NetUtil.isConnectedToInternet() && INTERNET_REQUIRED_DEV) {
        throw new TweetMyHomeException("Not Connected to Internet");
    }
    trace("Internet conecction detected");
    trace("Trying to connect to DBMS...");
    db = new TweetMyHomeDatabase(p);
    if (!db.connect()) {
        throw new TweetMyHomeException("Not Connected to DBMS");
    }
    trace("Connected to DBMS");
    db.addTweetMyHomeDevices(tmh_device_xml);

    if (RASPBERRY_ON_BOARD) {
        if (p.getValueByKey(Key.arduinoIOBridge).equalsIgnoreCase("true")) {
            throw new TweetMyHomeException("Arduino not supported...");
        } else {
            iob = new RaspberryPiGPIO(tmh_device_xml);
        }
        if (iob != null) {
            iob.addIODeviceListener(this);
            iob.connect();
            trace("GPIO Link established");
            com = new Comunity(false, iob);
            sec = new Security(false, iob);
            //sect = new SecurityThreshhold(sec);
            trace("Security , Security threshold & Comunity initiated");
        }
    } else {
        warn("Raspberry PI GPIO omited. APP prob. won't work well");
    }
    sect = new SecurityThreshhold(sec);
    trace("Setting Twitter OAuth parameters...");
    ConfigurationBuilder cb1 = new ConfigurationBuilder();
    cb1.setDebugEnabled(false).setOAuthConsumerKey("RaTG5hw5OwhQQugghtLthG0ug")
            .setOAuthConsumerSecret("brJ0vcrdGnCHMTxDCmKoThPpJubD6e2xol5WjdO9bBa19nzkXp")
            .setOAuthAccessToken("3236804811-V6MOxfbox4jVylx6pDjkR9UrEpuPzZyOwkaVIWp")
            .setOAuthAccessTokenSecret("33HvizelxmGN700a7pLa6YBKv0l2uTMLoJK593MlXellg");
    ConfigurationBuilder cb2 = new ConfigurationBuilder();
    cb2.setDebugEnabled(false).setOAuthConsumerKey("RaTG5hw5OwhQQugghtLthG0ug")
            .setOAuthConsumerSecret("brJ0vcrdGnCHMTxDCmKoThPpJubD6e2xol5WjdO9bBa19nzkXp")
            .setOAuthAccessToken("3236804811-V6MOxfbox4jVylx6pDjkR9UrEpuPzZyOwkaVIWp")
            .setOAuthAccessTokenSecret("33HvizelxmGN700a7pLa6YBKv0l2uTMLoJK593MlXellg");
    TwitterFactory tf = new TwitterFactory(cb1.build());
    TwitterStreamFactory sf = new TwitterStreamFactory(cb2.build());

    trace("Connecting to Twitter STREAM API...");
    tws = sf.getInstance();
    tws.addListener(this);
    tws.user();
    trace("Connecting to Twitter REST API...");
    tw = tf.getInstance();
    debug("Contructor fi");
    /*----------------NEEDED WORK TO DO-------------------*/

    // integrityCheckSuperAdmin();

}

From source file:de.fhb.twitalyse.spout.TwitterStreamSpout.java

License:Open Source License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    this.collector = collector;

    // enable JSONStore
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);//from w ww .j  a v a 2 s .  c om

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

    AccessToken givenAccessToken = new AccessToken(TOKEN, TOKEN_SECRET);
    twitterStream.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECURE);
    twitterStream.setOAuthAccessToken(givenAccessToken);
    twitterStream.addListener(this);
    twitterStream.sample();
}

From source file:edu.uci.ics.asterix.external.util.TwitterUtil.java

License:Apache License

public static TwitterStream getTwitterStream(Map<String, String> configuration) {
    ConfigurationBuilder cb = getAuthConfiguration(configuration);
    TwitterStreamFactory factory = new TwitterStreamFactory(cb.build());
    return factory.getInstance();
}

From source file:my.twittergui.TwitterUI.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    String text;/*from   ww w. ja va 2 s . co m*/
    text = jTextField1.getText();
    //jTextArea1.append(text+"\n");
    jTextArea1.append("Searching for: ");
    String[] strarray = text.split(" ");
    for (int i = 0; i < strarray.length; i++) {
        jTextArea1.append(strarray[i] + "\n");
    }

    File filed = null;
    filed = new File("C:\\Results");
    if (!filed.exists()) {
        filed.mkdir();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("")
            .setOAuthAccessTokenSecret("");

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {

            try {

                int fileno = 0;
                String strI = Integer.toString(fileno);
                String fname = "C:\\results\\DataCol" + strI + ".csv";
                File file = new File(fname);
                FileWriter bw = new FileWriter(file, true);

                if (file.length() == 0) {
                    bw.write("\"Screen Name\", text, \"created at\", geolocation, Retweet? \r\n");
                    bw.flush();
                }
                while (file.length() > 10485760) {
                    fileno += 1;
                    strI = Integer.toString(fileno);
                    fname = "DataCol" + strI + ".txt";
                    file = new File(fname);
                    bw = new FileWriter(file, true);
                    bw.write("\"Screen Name\", \"text\", \"created_at\", \"geolocation\" \r\n");
                    bw.flush();

                }

                // if(!status.isRetweet()){
                bw.write("\r\n");
                bw.write("\"" + status.getUser().getScreenName() + "\",");
                String tweettxt = status.getText();
                tweettxt = tweettxt.replace("\n", "");
                tweettxt = tweettxt.replace(",", "");
                tweettxt = tweettxt.replace("\"", "");
                bw.write("\"" + tweettxt + "\",");

                bw.write("\"" + status.getCreatedAt() + "\",");
                if (status.getGeoLocation() != null) {
                    bw.write("\"" + status.getGeoLocation() + "\"");
                } else
                    bw.write("N/A,");
                if (status.isRetweet())
                    bw.write("Yes");
                else
                    bw.write("No");

                bw.flush();

                bw.close();
                //System.out.print("\n");
                String str = "@" + status.getUser().getScreenName() + "  " + status.getText() + " "
                        + status.getCreatedAt() + " ";
                if (status.getGeoLocation() != null)
                    str += status.getGeoLocation();
                //System.out.print(str);
                jTextArea1.append(str + "\n");
                // }

                bw.close();
            } catch (IOException e) {
                //System.out.print("EXCEPTION");
                e.printStackTrace();
            }

        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onStallWarning(StallWarning stall) {
        }

        public void onScrubGeo(long a, long b) {
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };
    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    TwitterStream twitterStream = tf.getInstance();
    twitterStream.addListener(listener);
    // Filter
    FilterQuery filtre = new FilterQuery();
    Scanner in = new Scanner(System.in);

    filtre.track(strarray);
    twitterStream.filter(filtre);

}

From source file:OAuth.MyOwnTwitterFactory.java

License:Open Source License

public TwitterStream createOneTwitterStreamInstance(AccessToken accessToken) {
    TwitterStream twitterStream;//from  w w  w  . j  ava 2s .c o m
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(APIkeys.getTwitterAPIKey());
    builder.setOAuthConsumerSecret(APIkeys.getTwitterAPISecret());
    System.out.println("AT: " + accessToken.getToken());
    System.out.println("ATS: " + accessToken.getTokenSecret());
    builder.setOAuthAccessToken(accessToken.getToken());
    builder.setOAuthAccessTokenSecret(accessToken.getTokenSecret());
    builder.setJSONStoreEnabled(true);
    //        builder.setOAuthAccessToken("31805620-QQy8TFFDKRxWyOUVnY08UcxT5bzrFhRWUa0A3lEW3");
    //        builder.setOAuthAccessTokenSecret("iJuCkdgrfIpGn5odyF2evMSvAsovreeEV6cZU5ihVVI7j");
    Configuration configuration = builder.build();
    TwitterStreamFactory factory = new TwitterStreamFactory(configuration);
    twitterStream = factory.getInstance();

    return twitterStream;
}

From source file:OAuth.MyOwnTwitterFactory.java

License:Open Source License

public TwitterStream createOneTwitterStreamInstanceFromApp(String APIKey, String APIKeySecret,
        String accessToken, String accessTokenSecret) {
    TwitterStream twitterStream;/*w ww  . j  a v  a  2 s . c o m*/
    ConfigurationBuilder builder = new ConfigurationBuilder();
    if (!Admin.isTest()) {
        builder.setOAuthConsumerKey(APIKey);
        builder.setOAuthConsumerSecret(APIKeySecret);
        builder.setOAuthAccessToken(accessToken);
        builder.setOAuthAccessTokenSecret(accessTokenSecret);
        builder.setJSONStoreEnabled(true);
    } else {
        builder.setOAuthConsumerKey("KNjw1QTK1hJKx8LpK6X6rg");
        builder.setOAuthConsumerSecret("ikX9blowuh3FqFAkIg5LQi5voLOV413EWzPsDl77uU");
        builder.setOAuthAccessToken("31805620-QQy8TFFDKRxWyOUVnY08UcxT5bzrFhRWUa0A3lEW3");
        builder.setOAuthAccessTokenSecret("iJuCkdgrfIpGn5odyF2evMSvAsovreeEV6cZU5ihVVI7j");
        builder.setJSONStoreEnabled(true);
    }
    Configuration configuration = builder.build();
    TwitterStreamFactory factory = new TwitterStreamFactory(configuration);
    twitterStream = factory.getInstance();

    return twitterStream;
}

From source file:org.twitter.sample.main.Stream.java

public void getTweetsFromTwitter() {

    StatusListener listener = new StatusListener() {
        private boolean logQueueFull = true;

        @Override/*from w  w w .j  av a  2 s  .co  m*/
        public void onException(Exception e) {
            log.error(e);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice notice) {
        }

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

        @Override
        public void onStatus(Status status) {
            db.insert(status);
        }

        @Override
        public void onTrackLimitationNotice(int notice) {
            log.warn("*** TRACK LIMITATION REACHED: " + notice + " ***");
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            log.warn("*** STALL WARNING: " + arg0);
        }
    };

    ConfigurationBuilder twitterConfig = new ConfigurationBuilder();
    twitterConfig.setDebugEnabled(false);
    twitterConfig.setOAuthAccessTokenSecret(access_token_secret);
    twitterConfig.setOAuthAccessToken(access_token);
    twitterConfig.setOAuthConsumerKey(consumer_key);
    twitterConfig.setOAuthConsumerSecret(consumer_secret);
    twitterConfig.setJSONStoreEnabled(true);

    TwitterStreamFactory fact = new TwitterStreamFactory(twitterConfig.build());
    this.twitterStream = fact.getInstance();
    this.twitterStream.addListener(listener);
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.language(new String[] { "en" });
    this.twitterStream.filter(filterQuery);
    this.twitterStream.sample();

}

From source file:org.umd.assignment.spout.TwitterSampleSpout.java

License:Apache License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<String>(1000);
    _collector = collector;/*www  .jav  a  2 s.com*/

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {
            queue.offer(status.getText());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        @Override
        public void onTrackLimitationNotice(int i) {
        }

        @Override
        public void onScrubGeo(long l, long l1) {
        }

        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    TwitterStreamFactory fact = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build());

    _twitterStream = fact.getInstance();

    _twitterStream.addListener(listener);
    _twitterStream.setOAuthConsumer(consumerKey, consumerSecret);

    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    _twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {
        _twitterStream.sample();
    } else {
        FilterQuery query = new FilterQuery().track(keyWords);
        _twitterStream.filter(query);
    }

}

From source file:org.wso2.cep.uima.demo.TwitterStreamer.java

License:Open Source License

/***
 * Method to start the streaming of Tweets
 * @param handler//from   ww w  . j  a v a  2s  .  com
 */
public void startStream(StatusHandler handler) {

    buildConfiguration();
    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    twitterStream = tf.getInstance();
    twitterStream.addListener(handler);
    createFilter();

    if (filter == null) {
        throw new NullPointerException("Filter Not Set");
    }
    twitterStream.filter(filter);
}

From source file:SentimentAnalyses.PrintSampleStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {

    final PrintSampleStream pr = new PrintSampleStream();

    try {/*from w  w w .  j a v a 2s  .  co  m*/
        pr.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Em3WTI7jc90HcvKzPkTLQ")
            .setOAuthConsumerSecret("vg4p6rOF32bmffqRR8m0jAUClrxvtGiMB5PrSr3Zsw")
            .setOAuthAccessToken("1681973072-1q0zI0VPjHD3ttNuaBOL94frzCI9sXInxAcDK0w")
            .setOAuthAccessTokenSecret("ZRLkOyjmhHBkU1iNyEVNyIgIBsKrl0DUDKOcOMneYFYEM");
    cb.setJSONStoreEnabled(true);

    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    TwitterStream twitterStream = tf.getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            //System.out.println(status);
            String str = DataObjectFactory.getRawJSON(status);
            try {
                //JSONObject nnstr = new JSONObject(newstr);
                DBObject dbObject = (DBObject) JSON.parse(str);
                //                    System.out.println(dbObject);
                pr.collection.insert(dbObject);
                //System.out.println(dbObject);
                pr.count++;
                if (pr.count % 1000 == 0)
                    System.out.println(pr.count);
                if (pr.count > 100000) {
                    pr.mongo.close();
                    System.exit(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

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

    String[] trackArray;
    String[] Track = { "Malaysia Airlines", "Flight MH370", "Boeing-777", "Kuala Lumpur", "Bei jing" };
    //trackArray[0] = "Obama";
    //trackArray[1] = "Romney";

    FilterQuery filter = new FilterQuery();
    filter.track(Track);
    String[] lang = { "en" };
    filter.language(lang);
    twitterStream.filter(filter);
    //pr.mongo.close();
}