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:com.stronquens.amgtwitter.SocketTwitter.java

@OnOpen
public void open(Session session, @PathParam("accesToken") String accesToken,
        @PathParam("accesTokenSecret") String accesTokenSecret) {
    try {//from w w w . j  a  v a  2  s.  com
        configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW")
                .setOAuthAccessToken(accesToken).setOAuthAccessTokenSecret(accesTokenSecret);

        /*String result = gson.toJson(twitter.showUser(twitter.getId()));
        session.getBasicRemote().sendText(result);*/

        TwitterStream twitterStream = new TwitterStreamFactory(configBuilder.build()).getInstance();
        twitterStream.addListener(listener);
        twitterStream.user();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.telefonica.iot.cygnus.sources.TwitterSource.java

License:Open Source License

@Override
public void configure(Context context) {
    consumerKey = context.getString("consumerKey");
    consumerSecret = context.getString("consumerSecret");
    accessToken = context.getString("accessToken");
    accessTokenSecret = context.getString("accessTokenSecret");

    LOGGER.info("Consumer Key:        '" + consumerKey + "'");
    LOGGER.info("Consumer Secret:     '" + consumerSecret + "'");
    LOGGER.info("Access Token:        '" + accessToken + "'");
    LOGGER.info("Access Token Secret: '" + accessTokenSecret + "'");

    String southWestLatitude;/*w  ww . j a  v  a2s .  c  o  m*/
    String southWestLongitude;
    String northEastLatitude;
    String northEastLongitude;
    String keywords;

    //Top-left coordinate
    southWestLatitude = context.getString("south_west_latitude");
    southWestLongitude = context.getString("south_west_longitude");
    LOGGER.info("South-West coordinate: '" + southWestLatitude + " " + southWestLongitude + "'");

    //Bottom-right coordinate
    northEastLatitude = context.getString("north_east_latitude");
    northEastLongitude = context.getString("north_east_longitude");
    LOGGER.info("North-East coordinate: '" + northEastLatitude + " " + northEastLongitude + "'");

    keywords = context.getString("keywords");
    LOGGER.info("Keywords:            '" + keywords + "'");

    if (southWestLatitude != null && southWestLongitude != null && northEastLatitude != null
            && northEastLongitude != null) {
        double latitude1 = Double.parseDouble(southWestLatitude);
        double longitude1 = Double.parseDouble(southWestLongitude);

        double latitude2 = Double.parseDouble(northEastLatitude);
        double longitude2 = Double.parseDouble(northEastLongitude);

        boundingBox = new double[][] { new double[] { longitude1, latitude1 }, // south-west
                new double[] { longitude2, latitude2 } // north-east
        };

        LOGGER.info("Coordinates:         '" + boundingBox[0][0] + " " + boundingBox[0][1] + " "
                + boundingBox[1][0] + " " + boundingBox[1][1] + "'");
        haveFilters = true;
        haveCoordinateFilter = true;
    }

    if (keywords != null) {
        if (keywords.trim().length() != 0) {
            splitKeywords = keywords.split(",");
            for (int i = 0; i < splitKeywords.length; i++) {
                splitKeywords[i] = splitKeywords[i].trim();
            }

            LOGGER.info("keywords:            {}", Arrays.toString(splitKeywords));
            haveFilters = true;
            haveKeywordFilter = true;
        }
    }

    maxBatchSize = context.getInteger("maxBatchSize", maxBatchSize);
    maxBatchDurationMillis = context.getInteger("maxBatchDurationMillis", maxBatchDurationMillis);

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

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

}

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

@Override
public void onStart() {
    try {//from w ww. j av  a 2s .  c o m
        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:com.twasyl.slideshowfx.server.service.TwitterService.java

License:Apache License

@Override
public void start() {
    final Map twitter = this.vertx.sharedData().getMap(SlideshowFXServer.SHARED_DATA_TWITTER);
    final String hashtag = (String) twitter.get(SlideshowFXServer.SHARED_DATA_TWITTER_HASHTAG);

    this.twitterConfiguration = new ConfigurationBuilder().setOAuthConsumerKey("5luxVGxswd42RgTfbF02g")
            .setOAuthConsumerSecret("winWDhMbeJZ4m66gABqpohkclLDixnyeOINuVtPWs").build();

    if (hashtag != null && !hashtag.isEmpty()) {
        this.connect();
        this.accessToken.addListener((value, oldValue, newValue) -> {
            if (newValue != null) {
                FilterQuery query = new FilterQuery();
                query.track(new String[] { hashtag });

                this.twitterStream = new TwitterStreamFactory(this.twitterConfiguration)
                        .getInstance(this.accessToken.get());
                this.twitterStream.addListener(this.buildTwitterStreamListener());
                this.twitterStream.filter(query);
            }/*from  w w  w .  jav a  2s .com*/
        });
    }
}

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.  j  av  a2  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:com.twitter.storm.hashtag2.TwitterSampleSpout.java

License:Apache License

public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<Status>(1000);
    _collector = collector;//from  w  ww  .jav a 2  s.c  o m

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {

            queue.offer(status);
        }

        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        public void onTrackLimitationNotice(int i) {
        }

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

        public void onException(Exception ex) {
        }

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

        }

    };

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    _twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    _twitterStream.addListener(listener);

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

From source file:com.unisa.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.
 */// www. ja  v  a 2 s  .  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, "");
    if (keywordString.trim().length() == 0) {
        keywords = new String[0];
    } else {
        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.waves_rsp.ikb4stream.datasource.twitter.TwitterProducerConnector.java

License:Open Source License

/**
 * Listen tweets from twitter with a bounding box and load them with the data producer object
 *
 * @param dataProducer {@link IDataProducer} contains the data queue
 * @see TwitterProducerConnector#confBuilder
 * @see TwitterProducerConnector#boundingBox
 *//*  w  ww  .ja va2s  . co  m*/
@Override
public void load(IDataProducer dataProducer) {
    Objects.requireNonNull(dataProducer);
    TwitterStream twitterStream = null;
    try {
        TwitterStreamListener streamListener = new TwitterStreamListener(dataProducer);
        twitterStream = new TwitterStreamFactory(confBuilder.build()).getInstance();
        FilterQuery filterQuery = new FilterQuery();
        filterQuery.locations(boundingBox);
        twitterStream.addListener(streamListener);
        twitterStream.filter(filterQuery);
        Thread.currentThread().join();
    } catch (IllegalArgumentException | IllegalStateException err) {
        LOGGER.error("Error loading : " + err.getMessage());
        throw new IllegalStateException(err.getMessage());
    } catch (InterruptedException e) {
        LOGGER.info("Close twitter");
        Thread.currentThread().interrupt();
    } finally {
        if (twitterStream != null) {
            twitterStream.cleanUp();
            twitterStream.shutdown();
        }
        Thread.currentThread().interrupt();
    }
}

From source file:com.wso2.stream.connector.protocol.TwitterPollingConsumer.java

License:Open Source License

/**
 * Setting up a connection with Twitter Stream API with the given credentials
 *///from w  w  w.  j a  va  2  s  . com
private void setupConnection() {
    StatusListener listener = new StatusListenerImpl();

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessSecret);

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

    FilterQuery query = new FilterQuery();
    query.language(new String[] { "en" });
    query.track(filterTags);
    twitterStream.filter(query);
}

From source file:crawler.CETReCrawler.java

License:Apache License

private void estabTwitterConn() {
     OAuthUser OA = new OAuthUser();
     query.track(Settings.baseKeywords);
     twitterStream = new TwitterStreamFactory(OA.build(Settings.ConsumerKey.get(0),
             Settings.ConsumerSecret.get(0), Settings.AccessToken.get(0), Settings.AccessSecret.get(0)))
                     .getInstance();//w  w  w . ja  va 2 s  . c  om

     dataStream = new DataStream();
     twitterStream.addListener(dataStream);
     twitterStream.filter(query);
 }