twitter4j.conf.Configuration Java Examples

The following examples show how to use twitter4j.conf.Configuration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TwitterTweetStream.java    From TweetwallFX with MIT License 6 votes vote down vote up
private void activateStream() {
    Configuration configuration = TwitterOAuth.getConfiguration();
    if (null == configuration) {
        return;
    }

    twitterStream = new TwitterStreamFactory(configuration).getInstance();
    twitterStream.addListener(new StatusAdapter() {

        @Override
        public void onStatus(final Status status) {
            TwitterTweet twitterTweet = new TwitterTweet(status);

            if (tweetFilter.test(twitterTweet)) {
                synchronized (TwitterTweetStream.this) {
                    LOG.info("redispatching new received tweet to " + tweetConsumerList);
                    tweetConsumerList.stream().forEach(consumer -> consumer.accept(twitterTweet));
                }
            }
        }
    });
    twitterStream.filter(getFilterQuery(filterQuery));
}
 
Example #2
Source File: TwitterTweeter.java    From TweetwallFX with MIT License 6 votes vote down vote up
protected final void handleRateLimit(final RateLimitStatus rateLimitStatus) {
    LOGGER.info("RateLimit: {}/{} resetting in {}s",
            rateLimitStatus.getRemaining(),
            rateLimitStatus.getLimit(),
            rateLimitStatus.getSecondsUntilReset());

    final TwitterSettings twitterSettings = org.tweetwallfx.config.Configuration.getInstance()
            .getConfigTyped(TwitterSettings.CONFIG_KEY, TwitterSettings.class);

    if (twitterSettings.isIgnoreRateLimit()) {
        return;
    }

    final long delay = 500L + rateLimitStatus.getSecondsUntilReset() * 1000L;

    try {
        Thread.sleep(delay);
    } catch (InterruptedException ex) {
        LOGGER.error("Sleeping for {} interrupted!", delay, ex);
        Thread.currentThread().interrupt();
    }
}
 
Example #3
Source File: TwitterOauthWizard.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
private Configuration getTwitterConfiguration () {
	if (this.twitterConfiguration == null) {
		final ConfigurationBuilder builder = new ConfigurationBuilder();
		builder.setOAuthConsumerKey(TwitterOauth.getConsumerKey());
		builder.setOAuthConsumerSecret(TwitterOauth.getConsumerSecret());
		this.twitterConfiguration = builder.build();
	}
	return this.twitterConfiguration;
}
 
Example #4
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
Observable<Status> observeTwitterStream(Configuration configuration, FilterQuery filterQuery) {
    return Observable.create(emitter -> {
        final TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

        emitter.setCancellable(() -> {
            Schedulers.io().scheduleDirect(() -> twitterStream.cleanUp());
        });

        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                emitter.onNext(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            }

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

            @Override
            public void onStallWarning(StallWarning warning) {
            }

            @Override
            public void onException(Exception ex) {
                emitter.onError(ex);
            }
        };

        twitterStream.addListener(listener);
        twitterStream.filter(filterQuery);
    });
}
 
Example #5
Source File: TwitterStreamTracker.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Configuration task2configuration(CollectionTask task) {
	ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
	configurationBuilder.setDebugEnabled(false)
	        .setJSONStoreEnabled(true)
	        .setOAuthConsumerKey(configProperties.getProperty(CollectorConfigurationProperty.TWITTER_CONSUMER_KEY))
	        .setOAuthConsumerSecret(configProperties.getProperty(CollectorConfigurationProperty.TWITTER_CONSUMER_SECRET))
	        .setOAuthAccessToken(task.getAccessToken())
	        .setOAuthAccessTokenSecret(task.getAccessTokenSecret());
	Configuration configuration = configurationBuilder.build();
	return configuration;
}
 
Example #6
Source File: TwitterInstance.java    From android-opensource-library-56 with Apache License 2.0 5 votes vote down vote up
public static Twitter getTwitterInstance(Context context) {
    if (INSTANCE == null) {
        Settings settings = Settings.getInstance(context);
        ConfigurationBuilder cbuilder = new ConfigurationBuilder();
        cbuilder.setOAuthConsumerKey(Settings.CONSUMER_KEY);
        cbuilder.setOAuthConsumerSecret(Settings.CONSUMER_SECRET);
        cbuilder.setOAuthAccessToken(settings.getAccessToken());
        cbuilder.setOAuthAccessTokenSecret(settings.getAccessTokenSecret());
        Configuration c = cbuilder.build();
        TwitterFactory twitterFactory = new TwitterFactory(c);
        INSTANCE = twitterFactory.getInstance();
    }
    return INSTANCE;
}
 
Example #7
Source File: Twitter4jSampleActivity.java    From android-opensource-library-56 with Apache License 2.0 5 votes vote down vote up
private void startOAuth() {
    new Thread() {
        public void run() {
            ConfigurationBuilder cbuilder = new ConfigurationBuilder();
            cbuilder.setOAuthConsumerKey(Settings.CONSUMER_KEY);
            cbuilder.setOAuthConsumerSecret(Settings.CONSUMER_SECRET);
            Configuration conf = cbuilder.build();
            mOauth = new OAuthAuthorization(conf);
            String authUrl = null;
            try {
                RequestToken requestToken = mOauth
                        .getOAuthRequestToken(null);
                authUrl = requestToken.getAuthorizationURL();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(authUrl));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        };
    }.start();
    setContentView(R.layout.login);

    findViewById(R.id.login).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // ピンコード処理を書く
            EditText editText = (EditText) findViewById(R.id.pincode);
            getOAuthAccessToken(editText.getText().toString());
        }
    });
}
 
Example #8
Source File: Twitt4droid.java    From twitt4droid with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the current twitter4j configuration with consumer and access tokens pre-initialized. You
 * can use this method to build a Twitter objects.
 * 
 * @param context the application context.
 * @return an Configuration object.
 */
private static Configuration getCurrentConfig(Context context) {
    SharedPreferences preferences = Resources.getPreferences(context);
    return new ConfigurationBuilder()
            .setOAuthConsumerKey(Resources.getMetaData(context, context.getString(R.string.twitt4droid_consumer_key_metadata), null))
            .setOAuthConsumerSecret(Resources.getMetaData(context, context.getString(R.string.twitt4droid_consumer_secret_metadata), null))
            .setOAuthAccessToken(preferences.getString(context.getString(R.string.twitt4droid_oauth_token_key), null))
            .setOAuthAccessTokenSecret(preferences.getString(context.getString(R.string.twitt4droid_oauth_secret_key), null))
            .build();
}
 
Example #9
Source File: TwitterApi.java    From SmileEssence with MIT License 5 votes vote down vote up
public static Configuration getConf(String consumerKey, String consumerSecret) {
    ConfigurationBuilder conf = new ConfigurationBuilder();
    conf.setOAuthConsumerKey(consumerKey);
    conf.setOAuthConsumerSecret(consumerSecret);
    conf.setDebugEnabled(true);
    return conf.build();
}
 
Example #10
Source File: SoomlaTwitter.java    From android-profile with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void configure(Map<String, String> providerParams) {
    autoLogin = false;

    if (providerParams != null) {
        twitterConsumerKey = providerParams.get("consumerKey");
        twitterConsumerSecret = providerParams.get("consumerSecret");

        // extract autoLogin
        String autoLoginStr = providerParams.get("autoLogin");
        autoLogin = autoLoginStr != null && Boolean.parseBoolean(autoLoginStr);
    }

    SoomlaUtils.LogDebug(TAG, String.format(
                "ConsumerKey:%s ConsumerSecret:%s",
                twitterConsumerKey, twitterConsumerSecret));

    if (TextUtils.isEmpty(twitterConsumerKey) || TextUtils.isEmpty(twitterConsumerSecret)) {
        SoomlaUtils.LogError(TAG, "You must provide the Consumer Key and Secret in the SoomlaProfile initialization parameters");
        isInitialized = false;
    }
    else {
        isInitialized = true;
    }

    oauthCallbackURL = "oauth://soomla_twitter" + twitterConsumerKey;

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(twitterConsumerKey);
    configurationBuilder.setOAuthConsumerSecret(twitterConsumerSecret);
    Configuration configuration = configurationBuilder.build();
    twitter = new AsyncTwitterFactory(configuration).getInstance();

    if (!actionsListenerAdded) {
        SoomlaUtils.LogWarning(TAG, "added action listener");
        twitter.addListener(actionsListener);
        actionsListenerAdded = true;
    }
}
 
Example #11
Source File: TwitterOAuth.java    From TweetwallFX with MIT License 5 votes vote down vote up
public static Configuration getConfiguration() {
    synchronized (TwitterOAuth.class) {
        if (INITIATED.compareAndSet(false, true)) {
            configuration = createConfiguration();
        }
    }

    return configuration;
}
 
Example #12
Source File: TwitterTweeter.java    From TweetwallFX with MIT License 5 votes vote down vote up
private void queryNext(final Query query) {
    numberOfPages--;
    if (null == query) {
        statuses = null;
    } else {
        Configuration configuration = TwitterOAuth.getConfiguration();
        if (null == configuration) {
            queryResult = null;
            statuses = null;
            return;
        }
        final Twitter twitter = new TwitterFactory(configuration).getInstance();

        try {
            LOGGER.trace("Querying next page: " + query);
            queryResult = twitter.search(query);
            if (null != queryResult) {
                handleRateLimit(queryResult.getRateLimitStatus());
                statuses = queryResult.getTweets().iterator();
            }
        } catch (TwitterException ex) {
            LOGGER.trace("Querying next page failed: " + query, ex);
            LOGGER.error("Error getting QueryResult for " + query, ex);
            queryResult = null;
            statuses = null;
        }
    }
}
 
Example #13
Source File: TwitterSourceConnectorConfig.java    From kafka-connect-twitter with Apache License 2.0 5 votes vote down vote up
public Configuration configuration() {
  Properties properties = new Properties();
  /*
    Grab all of the key/values that have a key that starts with twitter. This will strip 'twitter.' from beginning of
    each key. This aligns with what the twitter4j framework is expecting.
   */
  properties.putAll(this.originalsWithPrefix("twitter."));
  return new PropertyConfiguration(properties);
}
 
Example #14
Source File: LoginResource.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Build the configuration that twitter4j will use.
 *
 * @return
 */
private final Configuration buildTwitterConfiguration() {
  if ((twitterConsumerKey == null)
      || (twitterConsumerSecret == null)
      || (twitterConsumerKey.equals("CHANGE_ME"))
      || (twitterConsumerSecret.equals("CHANGE_ME"))) {
    return null;
  }

  return new ConfigurationBuilder()
      .setOAuthConsumerKey(twitterConsumerKey)
      .setOAuthConsumerSecret(twitterConsumerSecret)
      .build();
}
 
Example #15
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
Observable<Status> observeTwitterStream(Configuration configuration, FilterQuery filterQuery) {
    return Observable.create(emitter -> {
        final TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

        emitter.setCancellable(() -> {
            Schedulers.io().scheduleDirect(() -> twitterStream.cleanUp());
        });

        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                emitter.onNext(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            }

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

            @Override
            public void onStallWarning(StallWarning warning) {
            }

            @Override
            public void onException(Exception ex) {
                emitter.onError(ex);
            }
        };

        twitterStream.addListener(listener);
        twitterStream.filter(filterQuery);
    });
}
 
Example #16
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
private Observable<StockUpdate> createTweetStockUpdateObservable(Configuration configuration, String[] trackingKeywords, FilterQuery filterQuery) {
    return observeTwitterStream(configuration, filterQuery)
            .sample(2700, TimeUnit.MILLISECONDS)
            .map(StockUpdate::create)
            .filter(containsAnyOfKeywords(trackingKeywords))
            .flatMapMaybe(skipTweetsThatDoNotContainKeywords(trackingKeywords));
}
 
Example #17
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
Observable<Status> observeTwitterStream(Configuration configuration, FilterQuery filterQuery) {
    return Observable.create(emitter -> {
        final TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

        emitter.setCancellable(() -> {
            Schedulers.io().scheduleDirect(() -> twitterStream.cleanUp());
        });

        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                emitter.onNext(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            }

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

            @Override
            public void onStallWarning(StallWarning warning) {
            }

            @Override
            public void onException(Exception ex) {
                emitter.onError(ex);
            }
        };

        twitterStream.addListener(listener);
        twitterStream.filter(filterQuery);
    });
}
 
Example #18
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
private Observable<StockUpdate> createTweetStockUpdateObservable(Configuration configuration, String[] trackingKeywords, FilterQuery filterQuery) {
    return observeTwitterStream(configuration, filterQuery)
            .sample(2700, TimeUnit.MILLISECONDS)
            .map(StockUpdate::create)
            .filter(containsAnyOfKeywords(trackingKeywords))
            .flatMapMaybe(skipTweetsThatDoNotContainKeywords(trackingKeywords));
}
 
Example #19
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
Observable<Status> observeTwitterStream(Configuration configuration, FilterQuery filterQuery) {
    return Observable.create(emitter -> {
        final TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

        emitter.setCancellable(() -> {
            Schedulers.io().scheduleDirect(() -> twitterStream.cleanUp());
        });

        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                emitter.onNext(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            }

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

            @Override
            public void onStallWarning(StallWarning warning) {
            }

            @Override
            public void onException(Exception ex) {
                emitter.onError(ex);
            }
        };

        twitterStream.addListener(listener);
        twitterStream.filter(filterQuery);
    });
}
 
Example #20
Source File: TwitterOAuth.java    From TweetwallFX with MIT License 4 votes vote down vote up
private static Configuration createConfiguration() {
    final org.tweetwallfx.config.Configuration tweetWallFxConfig = org.tweetwallfx.config.Configuration.getInstance();
    final TwitterSettings twitterSettings = org.tweetwallfx.config.Configuration.getInstance()
            .getConfigTyped(TwitterSettings.CONFIG_KEY, TwitterSettings.class);

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setDebugEnabled(twitterSettings.isDebugEnabled());
    builder.setTweetModeExtended(twitterSettings.isExtendedMode());

    TwitterSettings.OAuth twitterOAuthSettings = twitterSettings.getOauth();
    builder.setOAuthConsumerKey(twitterOAuthSettings.getConsumerKey());
    builder.setOAuthConsumerSecret(twitterOAuthSettings.getConsumerSecret());
    builder.setOAuthAccessToken(twitterOAuthSettings.getAccessToken());
    builder.setOAuthAccessTokenSecret(twitterOAuthSettings.getAccessTokenSecret());

    // optional proxy settings
    tweetWallFxConfig.getConfigTypedOptional(ConnectionSettings.CONFIG_KEY, ConnectionSettings.class)
            .map(ConnectionSettings::getProxy)
            .filter(proxy -> Objects.nonNull(proxy.getHost()) && !proxy.getHost().isEmpty())
            .ifPresent(proxy -> {
                builder.setHttpProxyHost(proxy.getHost());
                builder.setHttpProxyPort(proxy.getPort());
                builder.setHttpProxyUser(proxy.getUser());
                builder.setHttpProxyPassword(proxy.getPassword());
            });

    Configuration conf = builder.build();

    // check Configuration
    if (conf.getOAuthConsumerKey() != null && !conf.getOAuthConsumerKey().isEmpty()
            && conf.getOAuthConsumerSecret() != null && !conf.getOAuthConsumerSecret().isEmpty()
            && conf.getOAuthAccessToken() != null && !conf.getOAuthAccessToken().isEmpty()
            && conf.getOAuthAccessTokenSecret() != null && !conf.getOAuthAccessTokenSecret().isEmpty()) {
        Twitter twitter = new TwitterFactory(conf).getInstance();
        try {
            User user = twitter.verifyCredentials();
            LOGGER.info("User " + user.getName() + " validated");
        } catch (TwitterException ex) {
            EXCEPTION.set(ex);
            //  statusCode=400, message=Bad Authentication data -> wrong token
            //  statusCode=401, message=Could not authenticate you ->wrong consumerkey
            int statusCode = ex.getStatusCode();
            LOGGER.error("Error statusCode=" + statusCode + " " + (statusCode > 0 ? ex.getErrorMessage() : ex.getMessage()));
            conf = null;
        }
    } else {
        EXCEPTION.set(new IllegalStateException("Missing credentials!"));
    }

    return conf;
}
 
Example #21
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    log(this.toString());

    RxJavaPlugins.setErrorHandler(ErrorHandler.get());

    ButterKnife.bind(this);

    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    stockDataAdapter = new StockDataAdapter();
    recyclerView.setAdapter(stockDataAdapter);

    Observable.just("Please use this app responsibly!")
            .subscribe(s -> helloText.setText(s));

    YahooService yahooService = new RetrofitYahooServiceFactory().create();

    final Configuration configuration = new ConfigurationBuilder()
            .setDebugEnabled(BuildConfig.DEBUG)
            .setOAuthConsumerKey("tTlvwBfqduVadKKEwMXDCmzA4")
            .setOAuthConsumerSecret("FiIOveHm9jLAtf0YSopWROeOFo3OA9VBM2CAuKwZ8AoL1gl4AK")
            .setOAuthAccessToken("195655474-QY8neLxXxqOsF8PGM8MYLsYGyQxQZA73S4qp0Sc2")
            .setOAuthAccessTokenSecret("lIiock0OTkR4TflFPb9pSMjLL8pN9JKIYKBhWMWwtxyMa")
            .build();


    final Settings settings = Settings.get(this.getApplicationContext());

    Observable.merge(
            settings.getMonitoredSymbols()
                    .switchMap(symbols -> {
                        String query = createQuery(symbols);
                        String env = "store://datatables.org/alltableswithkeys";
                        return createFinancialStockUpdateObservable(yahooService, query, env);
                    }),
            settings.getMonitoredKeywords()
                    .switchMap(keywords -> {
                                if (keywords.isEmpty()) {
                                    return Observable.never();
                                }

                                String[] trackingKeywords = keywords.toArray(new String[0]);
                                final FilterQuery filterQuery = new FilterQuery()
                                        .track(trackingKeywords)
                                        .language("en");
                                return createTweetStockUpdateObservable(configuration, trackingKeywords, filterQuery);
                            }
                    )
    )
            .groupBy(stockUpdate -> stockUpdate.getStockSymbol())
            .flatMap(groupObservable -> groupObservable.distinctUntilChanged())
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribeOn(Schedulers.io())
            .doOnError(ErrorHandler.get())
            .compose(addUiErrorHandling())
            .compose(addLocalItemPersistenceHandling(this))
            .doOnNext(update -> log(update))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(stockUpdate -> {
                Log.d("APP", "New update " + stockUpdate.getStockSymbol());
                noDataAvailableView.setVisibility(View.GONE);
                stockDataAdapter.add(stockUpdate);
                recyclerView.smoothScrollToPosition(0);
            }, error -> {
                if (stockDataAdapter.getItemCount() == 0) {
                    noDataAvailableView.setVisibility(View.VISIBLE);
                }
            });

    demo2();

}
 
Example #22
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 4 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        log(this.toString());

        RxJavaPlugins.setErrorHandler(ErrorHandler.get());

        ButterKnife.bind(this);

        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        stockDataAdapter = new StockDataAdapter();
        recyclerView.setAdapter(stockDataAdapter);

        Observable.just("Please use this app responsibly!")
                .subscribe(s -> helloText.setText(s));

        YahooService yahooService = new RetrofitYahooServiceFactory().create();

        String query = "select * from yahoo.finance.quote where symbol in ('YHOO','GOOG','MSFT')";
        String env = "store://datatables.org/alltableswithkeys";

        final Configuration configuration = new ConfigurationBuilder()
                .setDebugEnabled(BuildConfig.DEBUG)
                .setOAuthConsumerKey("tTlvwBfqduVadKKEwMXDCmzA4")
                .setOAuthConsumerSecret("FiIOveHm9jLAtf0YSopWROeOFo3OA9VBM2CAuKwZ8AoL1gl4AK")
                .setOAuthAccessToken("195655474-QY8neLxXxqOsF8PGM8MYLsYGyQxQZA73S4qp0Sc2")
                .setOAuthAccessTokenSecret("lIiock0OTkR4TflFPb9pSMjLL8pN9JKIYKBhWMWwtxyMa")
                .build();

        final String[] trackingKeywords = {"Yahoo", "Google", "Microsoft"};
        final FilterQuery filterQuery = new FilterQuery()
                .track(trackingKeywords)
                .language("en");


        Observable.merge(
                createFinancialStockUpdateObservable(yahooService, query, env),
                createTweetStockUpdateObservable(configuration, trackingKeywords, filterQuery)
        )
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .doOnError(ErrorHandler.get())
                .compose(addUiErrorHandling())
                .compose(addLocalItemPersistenceHandling(this))
                .doOnNext(update -> log(update))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(stockUpdate -> {
                    Log.d("APP", "New update " + stockUpdate.getStockSymbol());
                    noDataAvailableView.setVisibility(View.GONE);
                    stockDataAdapter.add(stockUpdate);
                    recyclerView.smoothScrollToPosition(0);
                }, error -> {
                    if (stockDataAdapter.getItemCount() == 0) {
                        noDataAvailableView.setVisibility(View.VISIBLE);
                    }
                });

//        cachingExample();
        timingExample2();

    }
 
Example #23
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 4 votes vote down vote up
private void twitter() {
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println(status.getUser().getName() + " : " + status.getText());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

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

        @Override
        public void onStallWarning(StallWarning warning) {
        }

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

    final Configuration configuration = new ConfigurationBuilder()
            .setDebugEnabled(BuildConfig.DEBUG)
            .setOAuthConsumerKey("tTlvwBfqduVadKKEwMXDCmzA4")
            .setOAuthConsumerSecret("FiIOveHm9jLAtf0YSopWROeOFo3OA9VBM2CAuKwZ8AoL1gl4AK")
            .setOAuthAccessToken("195655474-QY8neLxXxqOsF8PGM8MYLsYGyQxQZA73S4qp0Sc2")
            .setOAuthAccessTokenSecret("lIiock0OTkR4TflFPb9pSMjLL8pN9JKIYKBhWMWwtxyMa")
            .build();

    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();
    twitterStream.addListener(listener);
    twitterStream.filter();
    twitterStream.filter(
            new FilterQuery()
                    .track("Yahoo", "Google", "Microsoft")
                    .language("en")
    );
}
 
Example #24
Source File: TwitterStreamTracker.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
public TwitterStreamTracker(TwitterCollectionTask task) throws ParseException{

		logger.info("Waiting to aquire Jedis connection for collection " + task.getCollectionCode());
		this.query = task2query(task);
		Configuration config = task2configuration(task);
		this.publisherJedis = JedisPublisher.newInstance();
		logger.info("Jedis connection acquired for collection " + task.getCollectionCode());

		String channelName = configProperties.getProperty(CollectorConfigurationProperty.COLLECTOR_CHANNEL) + "." + task.getCollectionCode();
		LoadShedder shedder = new LoadShedder(
				Integer.parseInt(configProperties.getProperty(CollectorConfigurationProperty.PERSISTER_LOAD_LIMIT)),
				Integer.parseInt(configProperties.getProperty(CollectorConfigurationProperty.PERSISTER_LOAD_CHECK_INTERVAL_MINUTES)), 
				true,channelName);
		TwitterStatusListener listener = new TwitterStatusListener(task, channelName);
		listener.addFilter(new ShedderFilter(channelName, shedder));
		if ("strict".equals(task.getGeoR())) {
			listener.addFilter(new StrictLocationFilter(task));
			logger.info("Added StrictLocationFilter for collection = " + task.getCollectionCode() + ", BBox: " + task.getGeoLocation());
		}
		
		// Added by koushik
		if (task.isToFollowAvailable()) {
			listener.addFilter(new FollowFilter(task));
			logger.info("Added FollowFilter for collection = " + task.getCollectionCode() + ", toFollow: " + task.getToFollow());
		}
		
		if (task.isToTrackAvailable() && (task.isGeoLocationAvailable() || task.isToFollowAvailable())) {
			// New default behavior: filter tweets received from geolocation and/or followed users using tracked keywords
			// Note: this override the default and old behavior of ORing the filter conditions by Twitter
			listener.addFilter(new TrackFilter(task));
			logger.info("Added TrackFilter for collection = " + task.getCollectionCode() + ", toTrack: " + task.getToTrack());
		}
		listener.addPublisher(publisherJedis);
		long threhold = Long.parseLong(configProperties.getProperty(CollectorConfigurationProperty.COLLECTOR_REDIS_COUNTER_UPDATE_THRESHOLD));
		String cacheKey = task.getCollectionCode();
		listener.addPublisher(new StatusPublisher(cacheKey, threhold));

		twitterStream = new TwitterStreamFactory(config).getInstance();
		twitterStream.addListener(listener);
		twitterStream.addConnectionLifeCycleListener(listener);
	}
 
Example #25
Source File: PublicObjectFactory.java    From hbc with Apache License 2.0 4 votes vote down vote up
public PublicObjectFactory(Configuration conf) {
  super(conf);
}
 
Example #26
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 4 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        log(this.toString());

        RxJavaPlugins.setErrorHandler(ErrorHandler.get());

        ButterKnife.bind(this);

        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        stockDataAdapter = new StockDataAdapter();
        recyclerView.setAdapter(stockDataAdapter);

        Observable.just("Please use this app responsibly!")
                .subscribe(s -> helloText.setText(s));

        YahooService yahooService = new RetrofitYahooServiceFactory().create();

        String query = "select * from yahoo.finance.quote where symbol in ('YHOO','AAPL','GOOG','MSFT')";
        String env = "store://datatables.org/alltableswithkeys";

        final Configuration configuration = new ConfigurationBuilder()
                .setDebugEnabled(BuildConfig.DEBUG)
                .setOAuthConsumerKey("tTlvwBfqduVadKKEwMXDCmzA4")
                .setOAuthConsumerSecret("FiIOveHm9jLAtf0YSopWROeOFo3OA9VBM2CAuKwZ8AoL1gl4AK")
                .setOAuthAccessToken("195655474-QY8neLxXxqOsF8PGM8MYLsYGyQxQZA73S4qp0Sc2")
                .setOAuthAccessTokenSecret("lIiock0OTkR4TflFPb9pSMjLL8pN9JKIYKBhWMWwtxyMa")
                .build();

        final FilterQuery filterQuery = new FilterQuery()
                .track("Yahoo", "Google", "Microsoft")
                .language("en");


        Observable.merge(
                Observable.interval(0, 5, TimeUnit.SECONDS)
                        .flatMap(
                                i -> yahooService.yqlQuery(query, env)
                                        .toObservable()
                        )
                        .map(r -> r.getQuery().getResults().getQuote())
                        .flatMap(Observable::fromIterable)
                        .map(StockUpdate::create),
                observeTwitterStream(configuration, filterQuery)
                        .sample(2700, TimeUnit.MILLISECONDS)
                        .map(StockUpdate::create)
        )
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .doOnError(ErrorHandler.get())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(error -> {
                    Toast.makeText(this, "We couldn't reach internet - falling back to local data",
                            Toast.LENGTH_SHORT)
                            .show();
                })
                .observeOn(Schedulers.io())
                .doOnNext(this::saveStockUpdate)
                .onExceptionResumeNext(
                        v2(StorIOFactory.get(this)
                                .get()
                                .listOfObjects(StockUpdate.class)
                                .withQuery(Query.builder()
                                        .table(StockUpdateTable.TABLE)
                                        .orderBy("date DESC")
                                        .limit(50)
                                        .build())
                                .prepare()
                                .asRxObservable())
                                .take(1)
                                .flatMap(Observable::fromIterable)
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(stockUpdate -> {
                    Log.d("APP", "New update " + stockUpdate.getStockSymbol());
                    noDataAvailableView.setVisibility(View.GONE);
                    stockDataAdapter.add(stockUpdate);
                    recyclerView.smoothScrollToPosition(0);
                }, error -> {
                    if (stockDataAdapter.getItemCount() == 0) {
                        noDataAvailableView.setVisibility(View.VISIBLE);
                    }
                });

//        demo0();
//        demo3();

    }