Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

From source file:org.threeriverdev.twitterreporter.TwitterBot.java

License:Apache License

public static void main(String... args) throws Exception {
    FilterQuery query = new FilterQuery();
    List<double[]> locations = new ArrayList<double[]>();

    // Create a grid over the continental US.
    // TODO: Originally (2009ish), these were recommended by Twitter.  Not sure if it's relevant now or not --
    // could we achieve the same results with 1 big block?
    for (double swLat = 25.0; swLat <= 49.0; swLat = swLat + GRIDSIZE) {
        for (double swLon = -125.0; swLon <= -67.0; swLon = swLon + GRIDSIZE) {
            double neLat = swLat + GRIDSIZE;
            double neLon = swLon + GRIDSIZE;

            double[] swLocation = new double[2];
            swLocation[0] = swLon;//  w  ww .j a  v a2 s  .  c o  m
            swLocation[1] = swLat;
            locations.add(swLocation);

            double[] neLocation = new double[2];
            neLocation[0] = neLon;
            neLocation[1] = neLat;
            locations.add(neLocation);
        }
    }

    query.locations(locations.toArray(new double[0][0]));

    try {
        URL url = TwitterBot.class.getResource("/oauth.properties");
        Properties p = new Properties();
        InputStream inStream = url.openStream();
        p.load(inStream);

        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        confBuilder.setOAuthConsumerKey(p.getProperty("consumer.key"));
        confBuilder.setOAuthConsumerSecret(p.getProperty("consumer.secret"));
        confBuilder.setOAuthAccessToken(p.getProperty("access.token"));
        confBuilder.setOAuthAccessTokenSecret(p.getProperty("access.token.secret"));
        Configuration conf = confBuilder.build();

        TwitterStream twitterStream = new TwitterStreamFactory(conf).getInstance();
        twitterStream.addListener(new TweetProcessor());
        twitterStream.filter(query);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

public void getTweetsFromTwitter() {

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

        @Override/*from   w ww  .ja va 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.uma.jmetalsp.application.biobjectivetsp.sparkutil.StreamingConfigurationTSP.java

License:Open Source License

/**
 * Create Twitter configuration//from  ww  w .j  ava2 s.  co m
 * @param consumerKey
 * @param consumerSecret
 * @param accessToken
 * @param accessTokenSecret
 * @param proxyHost
 * @param proxyPort
 * @param twitterFilter
 */
public void initializeTwitter(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret, String proxyHost, int proxyPort, String twitterFilter) {
    this.twitterFilter = twitterFilter;
    ConfigurationBuilder cb = new ConfigurationBuilder();
    if (proxyHost != null) {
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", String.valueOf(proxyPort));
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", String.valueOf(proxyPort));
    }
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
    Configuration twitterConf = cb.build();

    twitterAuth = AuthorizationFactory.getInstance(twitterConf);
}

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;/*  w  w  w .j ava  2s.co  m*/

    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.voiser.zoe.TwitterAgent.java

License:MIT License

/**
 * /*from w  w w  .  ja v a2s . com*/
 */
public TwitterAgent() {
    String consumerKey = System.getenv("zoe_twitter_consumer_key");
    String consumerSecret = System.getenv("zoe_twitter_consumer_secret");
    String accessToken = System.getenv("zoe_twitter_access_token");
    String accessTokenSecret = System.getenv("zoe_twitter_access_token_secret");

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

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

From source file:org.vsepml.storm.twitter.StormTwitterStreamSpout.java

License:Apache License

@Override
public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
    this.collector = spoutOutputCollector;
    queue = new LinkedBlockingQueue<Status>(1000);

    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            queue.offer(status);/*from  ww  w .  j  a  va  2s.  c  o m*/
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

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

        @Override
        public void onStallWarning(StallWarning stallWarning) {
        }

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

    ConfigurationBuilder twitterConf = new ConfigurationBuilder();
    twitterConf.setIncludeEntitiesEnabled(true);
    twitterConf.setUseSSL(true);
    twitterConf.setUserStreamRepliesAllEnabled(true);
    twitterConf.setOAuthAccessToken(accessToken);
    twitterConf.setOAuthAccessTokenSecret(accessTokenSecret);
    twitterConf.setOAuthConsumerKey(consumerKey);
    twitterConf.setOAuthConsumerSecret(consumerSecret);

    twitterStream = new TwitterStreamFactory(twitterConf.build()).getInstance();
    twitterStream.addListener(listener);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.sample();
}

From source file:org.wso2.carbon.connector.twitter.TwitterClientLoader.java

License:Open Source License

public Twitter loadApiClient() throws TwitterException {
    Twitter twitter;/*from   ww  w .  j  a v  a  2  s .  c  o  m*/
    if (messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_KEY) != null
            && messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_SECRET) != null
            && messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN) != null
            && messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN_SECRET) != null) {
        ConfigurationBuilder build = new ConfigurationBuilder();
        build.setJSONStoreEnabled(true);
        build.setOAuthAccessToken(
                messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN).toString());
        build.setOAuthAccessTokenSecret(messageContext
                .getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN_SECRET).toString());
        build.setOAuthConsumerKey(
                messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_KEY).toString());
        build.setOAuthConsumerSecret(
                messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_SECRET).toString());
        twitter = new TwitterFactory(build.build()).getInstance();
        twitter.verifyCredentials();
    } else {
        twitter = new TwitterFactory().getInstance();
    }
    return twitter;
}

From source file:org.wso2.carbon.identity.authenticator.twitter.TwitterAuthenticator.java

License:Open Source License

/**
 * Initiate the authentication request//from ww  w .  jav a2s. com
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
    String apiKey = authenticatorProperties.get(TwitterAuthenticatorConstants.TWITTER_API_KEY);
    String apiSecret = authenticatorProperties.get(TwitterAuthenticatorConstants.TWITTER_API_SECRET);
    configurationBuilder.setIncludeEmailEnabled(true);
    Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
    twitter.setOAuthConsumer(apiKey, apiSecret);
    try {
        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
                context.getCallerSessionKey(), context.getContextIdentifier());
        String callbackURL = getCallbackUrl(authenticatorProperties);
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        String subStr = queryParams
                .substring(queryParams.indexOf(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="));
        String sessionDK = subStr
                .substring(subStr.indexOf(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="),
                        subStr.indexOf("&"))
                .replace((TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="), "");
        request.getSession().setAttribute(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY, sessionDK);
        request.getSession().setAttribute(TwitterAuthenticatorConstants.TWITTER_REQUEST_TOKEN, requestToken);
        request.getSession().setAttribute(TwitterAuthenticatorConstants.AUTHENTICATOR_NAME.toLowerCase(),
                twitter);
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        log.error("Exception while sending to the Twitter login page.", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    } catch (IOException e) {
        log.error("Exception while sending to the Twitter login page.", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.inbound.custom.poll.TwitterStreamData.java

License:Open Source License

/**
 * Setting up a connection with Twitter Stream API with the given
 * credentials//from  w  ww  . ja  v a2  s  .co m
 *
 * @throws TwitterException
 */
private void setupConnection() throws TwitterException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to setup the connection with the twitter streaming endpoint");
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessSecret);
    StatusListener statusStreamsListener;
    UserStreamListener userStreamListener;
    SiteStreamsListener siteStreamslistener;
    TwitterStream twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    String twitterOperation = properties.getProperty(TwitterConstant.TWITTER_OPERATION);
    if (twitterOperation.equals(TwitterConstant.FILTER_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.LINK_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) {
        statusStreamsListener = new StatusListenerImpl();
        twitterStream.addListener(statusStreamsListener);
    } else if (twitterOperation.equals(TwitterConstant.USER_STREAM_OPERATION)) {
        userStreamListener = new UserStreamListenerImpl();
        twitterStream.addListener(userStreamListener);
    } else if (twitterOperation.equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        siteStreamslistener = new siteStreamsListenerImpl();
        twitterStream.addListener(siteStreamslistener);
    } else {
        handleException("The operation :" + twitterOperation + " not found");
    }

    /* Synchronously retrieves public statuses that match one or more filter predicates.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FILTER_STREAM_OPERATION)) {
        FilterQuery query = new FilterQuery();
        if (languages != null) {
            query.language(languages);
        }
        if (tracks != null) {
            query.track(tracks);
        }
        if (follow != null) {
            query.follow(follow);
        }
        if (filterLevel != null) {
            query.filterLevel(filterLevel);
        }
        query.count(count);
        twitterStream.filter(query);
    }

    /* Returns a small random sample of all public statuses. */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) {

        if (languages != null) {
            if (languages.length == 1) {
                twitterStream.sample(languages[1]);
            } else {
                handleException("A language can be used for the sample operation");
            }
        }
        twitterStream.sample();
    }
    /* Asynchronously retrieves all public statuses.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.firehose(count);
        }
    }
    /*
     User Streams provide a stream of data and events specific to the
     authenticated user.This provides to access the Streams messages for a
     single user.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.USER_STREAM_OPERATION)) {
        if (tracks != null) {
            twitterStream.user(tracks);
        }
        twitterStream.user();
    }
    /*
     * Link Streams provide asynchronously retrieves all statuses containing 'http:' and 'https:'.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.LINK_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.links(count);
        }
    }
    /*
     * User Streams provide a stream of data and events specific to the
     * authenticated user.This provides to access the Streams messages for a
     * single user.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.RETWEET_STREAM_OPERATION)) {
        twitterStream.retweet();
    }
    /*
     * Site Streams allows services, such as web sites or mobile push
     * services, to receive real-time updates for a large number of users.
     * Events may be streamed for any user who has granted OAuth access to
     * your application. Desktop applications or applications with few users
     * should use user streams.
     */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        twitterStream.site(withFollowings, follow);
    }

}

From source file:org.wso2.carbon.inbound.twitter.poll.TwitterStreamData.java

License:Open Source License

/**
 * Setting up a connection with Twitter Stream API with the given
 * credentials// ww  w . ja va 2  s.  c  om
 *
 * @throws TwitterException
 */
private void setupConnection() throws TwitterException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to setup the connection with the twitter streaming endpoint");
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setJSONStoreEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessSecret);
    StatusListener statusStreamsListener;
    UserStreamListener userStreamListener;
    SiteStreamsListener siteStreamslistener;
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    String twitterOperation = properties.getProperty(TwitterConstant.TWITTER_OPERATION);
    if (twitterOperation.equals(TwitterConstant.FILTER_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.LINK_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.SAMPLE_STREAM_OPERATION)
            || twitterOperation.equals(TwitterConstant.RETWEET_STREAM_OPERATION)) {
        statusStreamsListener = new StatusListenerImpl();
        twitterStream.addListener(statusStreamsListener);
    } else if (twitterOperation.equals(TwitterConstant.USER_STREAM_OPERATION)) {
        userStreamListener = new UserStreamListenerImpl();
        twitterStream.addListener(userStreamListener);
    } else if (twitterOperation.equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        siteStreamslistener = new siteStreamsListenerImpl();
        twitterStream.addListener(siteStreamslistener);
    } else {
        handleException("The operation :" + twitterOperation + " not found");
    }

    /* Synchronously retrieves public statuses that match one or more filter predicates.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FILTER_STREAM_OPERATION)) {
        FilterQuery query = new FilterQuery();
        if (languages != null) {
            query.language(languages);
        }
        if (tracks != null) {
            query.track(tracks);
        }
        if (follow != null) {
            query.follow(follow);
        }
        if (locations != null) {
            query.locations(locations);
        }
        if (filterLevel != null) {
            query.filterLevel(filterLevel);
        }
        if (follow == null & tracks == null & locations == null) {
            handleException("At least follow, locations, or track must be specified.");
        }
        query.count(count);
        twitterStream.filter(query);
    }

    /* Returns a small random sample of all public statuses. */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SAMPLE_STREAM_OPERATION)) {

        if (languages != null) {
            if (languages.length == 1) {
                twitterStream.sample(languages[1]);
            } else {
                handleException("A language can be used for the sample operation");
            }
        } else {
            twitterStream.sample();
        }
    }
    /* Asynchronously retrieves all public statuses.*/
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.FIREHOSE_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.firehose(count);
        }
    }
    /*
     User Streams provide a stream of data and events specific to the
    authenticated user.This provides to access the Streams messages for a
    single user.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.USER_STREAM_OPERATION)) {
        if (tracks != null) {
            twitterStream.user(tracks);
        } else {
            twitterStream.user();
        }
    }
    /*
     * Link Streams provide asynchronously retrieves all statuses containing 'http:' and 'https:'.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.LINK_STREAM_OPERATION)) {
        if (countParam != null) {
            twitterStream.links(count);
        }
    }
    /*
     * User Streams provide a stream of data and events specific to the
    * authenticated user.This provides to access the Streams messages for a
    * single user.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.RETWEET_STREAM_OPERATION)) {
        twitterStream.retweet();
    }
    /*
     * Site Streams allows services, such as web sites or mobile push
    * services, to receive real-time updates for a large number of users.
    * Events may be streamed for any user who has granted OAuth access to
    * your application. Desktop applications or applications with few users
    * should use user streams.
    */
    if ((properties.getProperty(TwitterConstant.TWITTER_OPERATION))
            .equals(TwitterConstant.SITE_STREAM_OPERATION)) {
        twitterStream.site(withFollowings, follow);
    }

}