Java Code Examples for twitter4j.conf.ConfigurationBuilder#setOAuthConsumerKey()

The following examples show how to use twitter4j.conf.ConfigurationBuilder#setOAuthConsumerKey() . 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: PlayConfigurationView.java    From beatoraja with GNU General Public License v3.0 6 votes vote down vote up
@FXML
public void startTwitterAuth() {
	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setOAuthConsumerKey(txtTwitterConsumerKey.getText());
	cb.setOAuthConsumerSecret(txtTwitterConsumerSecret.getText());
	cb.setOAuthAccessToken(null);
	cb.setOAuthAccessTokenSecret(null);
	TwitterFactory twitterfactory = new TwitterFactory(cb.build());
	Twitter twitter = twitterfactory.getInstance();
	try {
		requestToken = twitter.getOAuthRequestToken();
		Desktop desktop = Desktop.getDesktop();
		URI uri = new URI(requestToken.getAuthorizationURL());
		desktop.browse(uri);
		player.setTwitterConsumerKey(txtTwitterConsumerKey.getText());
		player.setTwitterConsumerSecret(txtTwitterConsumerSecret.getText());
		player.setTwitterAccessToken("");
		player.setTwitterAccessTokenSecret("");
		txtTwitterPIN.setDisable(false);
		twitterPINButton.setDisable(false);
		txtTwitterAuthenticated.setVisible(false);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: PlayConfigurationView.java    From beatoraja with GNU General Public License v3.0 6 votes vote down vote up
@FXML
public void startPINAuth() {
	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setOAuthConsumerKey(player.getTwitterConsumerKey());
	cb.setOAuthConsumerSecret(player.getTwitterConsumerSecret());
	cb.setOAuthAccessToken(null);
	cb.setOAuthAccessTokenSecret(null);
	TwitterFactory twitterfactory = new TwitterFactory(cb.build());
	Twitter twitter = twitterfactory.getInstance();
	try {
		AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, txtTwitterPIN.getText());
		player.setTwitterAccessToken(accessToken.getToken());
		player.setTwitterAccessTokenSecret(accessToken.getTokenSecret());
		commit();
		update(config);
	} catch (TwitterException e) {
		e.printStackTrace();
	}
}
 
Example 3
Source File: Twitter.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public void connect() throws TwitterException {
	initProperties();
	ConfigurationBuilder config = new ConfigurationBuilder();
	config.setOAuthConsumerKey(getOauthKey());
	config.setOAuthConsumerSecret(getOauthSecret());
	config.setOAuthAccessToken(getToken());
	config.setOAuthAccessTokenSecret(getTokenSecret());
	twitter4j.Twitter twitter = new TwitterFactory(config.build()).getInstance();
	User user = twitter.verifyCredentials();
	if (!this.userName.equals(user.getScreenName())) {
		this.userName = user.getScreenName();
		saveProperties(null);
	}
	//AccessToken accessToken = new AccessToken(getToken(), getTokenSecret());
	//twitter4j.Twitter twitter = new TwitterFactory().getInstance(accessToken);
	//twitter4j.Twitter twitter = new TwitterFactory().getInstance(getOauthKey(), getOauthSecret(), accessToken);
	//twitter4j.Twitter twitter = new TwitterFactory().getInstance(getUsername(), getPassword());
	setConnection(twitter);
}
 
Example 4
Source File: NotificationResource.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
@PostConstruct
public void init() {
  try {
    File log = new File(logFile);
    File parentDir = log.getParentFile();
    if (!parentDir.exists()) {
      parentDir.mkdirs();
    }

    FileHandler fh = new FileHandler(logFile);
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);

    File fbLog = new File(fallbackLogFile);
    File fbParentDir = fbLog.getParentFile();
    if (!fbParentDir.exists()) {
      fbParentDir.mkdirs();
    }

    FileHandler fbFh = new FileHandler(fallbackLogFile);
    fbLogger.addHandler(fbFh);
    SimpleFormatter fbFormatter = new SimpleFormatter();
    fbFh.setFormatter(fbFormatter);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setTweetModeExtended(true);
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumeSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(acessSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
  } catch (Exception e) {
    throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
  }
}
 
Example 5
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 6
Source File: TwitterReader.java    From swcv with MIT License 5 votes vote down vote up
public static Twitter getTwitterInstance()
{
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(false);
    cb.setOAuthConsumerKey(TwitterCredentials.CONSUMER_KEY);
    cb.setOAuthConsumerSecret(TwitterCredentials.CONSUMER_SECRET);
    cb.setOAuthAccessToken(TwitterCredentials.ACCESS_TOKEN);
    cb.setOAuthAccessTokenSecret(TwitterCredentials.ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    return tf.getInstance();
}
 
Example 7
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 8
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 9
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 10
Source File: TwitterProducer.java    From lsiem with Apache License 2.0 4 votes vote down vote up
private void start(Context context) {

/** Producer properties **/
Properties props = new Properties();
props.put("metadata.broker.list", context.getString(TwitterSourceConstant.BROKER_LIST));
props.put("serializer.class", context.getString(TwitterSourceConstant.SERIALIZER));
props.put("request.required.acks", context.getString(TwitterSourceConstant.REQUIRED_ACKS));

ProducerConfig config = new ProducerConfig(props);

final Producer<String, String> producer = new Producer<String, String>(config);

/** Twitter properties **/
consumerKey = context.getString(TwitterSourceConstant.CONSUMER_KEY_KEY);
consumerSecret = context.getString(TwitterSourceConstant.CONSUMER_SECRET_KEY);
accessToken = context.getString(TwitterSourceConstant.ACCESS_TOKEN_KEY);
accessTokenSecret = context.getString(TwitterSourceConstant.ACCESS_TOKEN_SECRET_KEY);

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();
final Map<String, String> headers = new HashMap<String, String>();

/** Twitter listener **/
StatusListener listener = new StatusListener() {
	// The onStatus method is executed every time a new tweet comes
	// in.
	public void onStatus(Status status) {
	    // The EventBuilder is used to build an event using the
	    // the raw JSON of a tweet
	    logger.info(status.getUser().getScreenName() + ": " + status.getText()); //delete uncomment sign
	    
	    KeyedMessage<String, String> data = new KeyedMessage<String, String>(context.getString(TwitterSourceConstant.KAFKA_TOPIC)
										 , DataObjectFactory.getRawJSON(status));
	    producer.send(data);
	    
	}
	    
	public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
	
	public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
	
	public void onScrubGeo(long userId, long upToStatusId) {}
	
	public void onException(Exception ex) {
	    logger.info("Shutting down Twitter sample stream...");
	    //twitterStream.shutdown();
	}
	
	public void onStallWarning(StallWarning warning) {}
    };

/** Bind the listener **/
twitterStream.addListener(listener);
/** GOGOGO **/
twitterStream.sample();   
   }
 
Example 11
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 12
Source File: TwitterSpout.java    From StormTweetsSentimentD3Viz with Apache License 2.0 4 votes vote down vote up
@Override
public final void open(final Map conf, final TopologyContext context,
                 final SpoutOutputCollector collector) {
	this._queue = new LinkedBlockingQueue<>(1000);
	this._outputCollector = collector;

	final StatusListener statusListener = new StatusListener() {
		@Override
		public void onStatus(final Status status) {
			_queue.offer(status);
		}

		@Override
		public void onDeletionNotice(final StatusDeletionNotice sdn) {
		}

		@Override
		public void onTrackLimitationNotice(final int i) {
		}

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

		@Override
		public void onStallWarning(final StallWarning stallWarning) {
		}

		@Override
		public void onException(final Exception e) {
		}
	};
	//Twitter stream authentication setup
	final Properties properties = new Properties();
	try {
		properties.load(TwitterSpout.class.getClassLoader()
				                .getResourceAsStream(Constants.CONFIG_PROPERTIES_FILE));
	} catch (final IOException ioException) {
		//Should not occur. If it does, we cant continue. So exiting the program!
		LOGGER.error(ioException.getMessage(), ioException);
		System.exit(1);
	}

	final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
	configurationBuilder.setIncludeEntitiesEnabled(true);

	configurationBuilder.setOAuthAccessToken(properties.getProperty(Constants.OAUTH_ACCESS_TOKEN));
	configurationBuilder.setOAuthAccessTokenSecret(properties.getProperty(Constants.OAUTH_ACCESS_TOKEN_SECRET));
	configurationBuilder.setOAuthConsumerKey(properties.getProperty(Constants.OAUTH_CONSUMER_KEY));
	configurationBuilder.setOAuthConsumerSecret(properties.getProperty(Constants.OAUTH_CONSUMER_SECRET));
	this._twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
	this._twitterStream.addListener(statusListener);

	//Our usecase computes the sentiments of States of USA based on tweets.
	//So we will apply filter with US bounding box so that we get tweets specific to US only.
	final FilterQuery filterQuery = new FilterQuery();

	//Bounding Box for United States.
	//For more info on how to get these coordinates, check:
	//http://www.quora.com/Geography/What-is-the-longitude-and-latitude-of-a-bounding-box-around-the-continental-United-States
	final double[][] boundingBoxOfUS = {{-124.848974, 24.396308},
			                                   {-66.885444, 49.384358}};
	filterQuery.locations(boundingBoxOfUS);
	this._twitterStream.filter(filterQuery);
}
 
Example 13
Source File: TwitterSource.java    From fiware-cygnus with GNU Affero General Public License v3.0 4 votes vote down vote up
@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;
    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();

}
 
Example 14
Source File: TwitterSpout.java    From StormTweetsSentimentAnalysis with Apache License 2.0 4 votes vote down vote up
@Override
public final void open(final Map conf, final TopologyContext context,
                 final SpoutOutputCollector collector) {
	this._queue = new LinkedBlockingQueue<>(1000);
	this._outputCollector = collector;

	final StatusListener statusListener = new StatusListener() {
		@Override
		public void onStatus(final Status status) {
			_queue.offer(status);
		}

		@Override
		public void onDeletionNotice(final StatusDeletionNotice sdn) {
		}

		@Override
		public void onTrackLimitationNotice(final int i) {
		}

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

		@Override
		public void onStallWarning(final StallWarning stallWarning) {
		}

		@Override
		public void onException(final Exception e) {
		}
	};
	//Twitter stream authentication setup
	final Properties properties = new Properties();
	try {
		properties.load(TwitterSpout.class.getClassLoader()
				                .getResourceAsStream(Constants.CONFIG_PROPERTIES_FILE));
	} catch (final IOException ioException) {
		//Should not occur. If it does, we cant continue. So exiting the program!
		LOGGER.error(ioException.getMessage(), ioException);
		System.exit(1);
	}

	final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
	configurationBuilder.setIncludeEntitiesEnabled(true);

	configurationBuilder.setOAuthAccessToken(properties.getProperty(Constants.OAUTH_ACCESS_TOKEN));
	configurationBuilder.setOAuthAccessTokenSecret(properties.getProperty(Constants.OAUTH_ACCESS_TOKEN_SECRET));
	configurationBuilder.setOAuthConsumerKey(properties.getProperty(Constants.OAUTH_CONSUMER_KEY));
	configurationBuilder.setOAuthConsumerSecret(properties.getProperty(Constants.OAUTH_CONSUMER_SECRET));
	this._twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
	this._twitterStream.addListener(statusListener);

	//Our usecase computes the sentiments of States of USA based on tweets.
	//So we will apply filter with US bounding box so that we get tweets specific to US only.
	final FilterQuery filterQuery = new FilterQuery();

	//Bounding Box for United States.
	//For more info on how to get these coordinates, check:
	//http://www.quora.com/Geography/What-is-the-longitude-and-latitude-of-a-bounding-box-around-the-continental-United-States
	final double[][] boundingBoxOfUS = {{-124.848974, 24.396308},
			                                   {-66.885444, 49.384358}};
	filterQuery.locations(boundingBoxOfUS);
	this._twitterStream.filter(filterQuery);
}