Example usage for twitter4j.conf ConfigurationBuilder setOAuthAccessToken

List of usage examples for twitter4j.conf ConfigurationBuilder setOAuthAccessToken

Introduction

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

Prototype

public ConfigurationBuilder setOAuthAccessToken(String oAuthAccessToken) 

Source Link

Usage

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;/*from  ww  w .j a v a 2s  . c  om*/
    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.tweet.HelperMethods.java

License:Apache License

public static void postToTwitter(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);/*from w  w  w .j  av a2  s  .  co m*/
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {
                Calendar cal = Calendar.getInstance();

                twitter.updateStatus(message + "\n@" + cal.getTime().toString());
            } catch (TwitterException e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.tweet.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);//  w w  w. j  av a  2 s  .  c  o  m
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    //final File file = new File(imageUrl);

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {

                if (StaticData.graphFile.exists()) {
                    Calendar cal = Calendar.getInstance();

                    StatusUpdate status = new StatusUpdate(message + "\n@" + cal.getTime().toString());
                    status.setMedia(StaticData.graphFile);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

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.
 */// w ww  .j a v a  2  s.com
@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.vuze.client.plugins.twitter.TwitterPlugin.java

License:Open Source License

private TwitterResult sendTweet(String status) {
    TwitterResult twitter_result;//from  ww  w .  j a v a  2s  .com

    log.log("Updating status: " + status);

    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();

        //cb.setSource( "Vuze" );

        // Twitter twitter = new TwitterFactory( cb.build()).getInstance( twitter_user.getValue(), new String( twitter_password.getValue()));

        Status result;

        Twitter twitter = null;

        try {
            if (access_token == null) {

                throw (new Exception("Please configure your account settings in the plugin options"));
            }

            cb.setOAuthAccessToken(access_token.getToken())
                    .setOAuthAccessTokenSecret(access_token.getTokenSecret()).setOAuthConsumerKey(CONSUMER_KEY)
                    .setOAuthConsumerSecret(CONSUMER_SECRET);

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

            result = twitter.updateStatus(status);

        } catch (Throwable e) {

            // hack for old clients that don't have correct trust store

            if (twitter != null && (e instanceof TwitterException)
                    && ((TwitterException) e).getStatusCode() == -1) {

                String truststore_name = FileUtil.getUserFile(SESecurityManager.SSL_CERTS).getAbsolutePath();

                File target = new File(truststore_name);

                if (!target.exists() || target.length() < 2 * 1024) {

                    File cacerts = new File(
                            new File(new File(System.getProperty("java.home"), "lib"), "security"), "cacerts");

                    if (cacerts.exists()) {

                        FileUtil.copyFile(cacerts, target);
                    }
                }

                // this merely acts to trigger a load of the keystore

                plugin_interface.getUtilities().getSecurityManager()
                        .installServerCertificate(new URL("https://twitter.com/"));

                result = twitter.updateStatus(status);

            } else {

                throw (e);
            }
        }

        log.log("Status updated to '" + result.getText() + "'");

        twitter_result = new TwitterResult();

    } catch (TwitterException e) {

        int status_code = e.getStatusCode();

        if (status_code == 401) {

            log.logAlert(LoggerChannel.LT_ERROR, "Twitter status update failed: id or password incorrect");

            twitter_result = new TwitterResult("Authentication failed: ID or password incorrect", false);

        } else if (status_code == 403) {

            log.logAlert(LoggerChannel.LT_ERROR,
                    "Twitter status update failed: duplicate tweet rejected by the server");

            twitter_result = new TwitterResult("Tweet has already been sent!", false);

        } else if (status_code >= 500 && status_code < 600) {

            log.logAlert(LoggerChannel.LT_ERROR,
                    "Twitter status update failed: Twitter is down or being upgraded");

            twitter_result = new TwitterResult("Tweet servers unavailable - try again later", true);

        } else {

            log.logAlert("Twitter status update failed", e);

            twitter_result = new TwitterResult(Debug.getNestedExceptionMessage(e), false);
        }
    } catch (Throwable e) {

        log.logAlert("Twitter status update failed", e);

        twitter_result = new TwitterResult(Debug.getNestedExceptionMessage(e), false);
    }

    return (twitter_result);
}

From source file:com.yfiton.notifiers.twitter.TwitterNotifier.java

License:Apache License

public TwitterNotifier() throws NotificationException {
    super(CLIENT_ID, SECRET_ID, PromptReceiver.class, TwitterWebEngineListener.class);

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setGZIPEnabled(true).setDebugEnabled(true).setOAuthConsumerKey(getClientId())
            .setOAuthConsumerSecret(getClientSecret());

    com.yfiton.notifiers.twitter.AccessToken accessToken = getAccessToken();

    if (accessToken != null) {
        configurationBuilder.setOAuthAccessToken(accessToken.getAccessToken());
        configurationBuilder.setOAuthAccessTokenSecret(accessToken.getAccessTokenSecret());
    }//  w w w .java 2  s. c  o m

    twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
}

From source file:crawler.TwitterFeed.java

/**
 *
 *//*from   www.  j  av  a  2 s .co  m*/
public void get_tweets() throws SQLException {
    CSVReader cr = new CSVReader();
    ArrayList<String> names = new ArrayList<>();
    Map<String, String> name_ticker;
    names = cr.get_company_names(tickers);
    System.out.println(names);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("WNSycI2GS33ZAwHJ9Fb4A");
    cb.setOAuthConsumerSecret("BBWeSThT3ZV2g9c5BDuUduDyNAWyzouMI0XjQy7KUc");
    cb.setOAuthAccessToken("1852271029-SLfE061bImfcRxWQZpy1pAgpEkfFhg3757Q9JRf");
    cb.setOAuthAccessTokenSecret("1uPSfYPbaENtXFYWsryBIAHnUsmG3pT6lGH0NzxTCGW7O");
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    for (String s : names) {
        String[] temp;
        if (s.contains(",")) {
            temp = s.split(",");
        } else {
            temp = s.split(" ");
        }

        System.out.println(
                "--------------------------------------------------------------------------------------"
                        + temp[0]);
        Query query = new Query("#" + temp[0]);
        query.lang("en");
        int numberOfTweets = 500;
        long lastID = Long.MAX_VALUE;
        ArrayList<Status> tweets = new ArrayList<>();
        while (tweets.size() < numberOfTweets) {
            if (numberOfTweets - tweets.size() > 100) {
                query.setCount(100);
            } else {
                query.setCount(numberOfTweets - tweets.size());
            }
            try {
                QueryResult result = twitter.search(query);
                tweets.addAll(result.getTweets());
                System.out.println("Gathered " + tweets.size() + " tweets");
                for (Status t : tweets) {
                    if (t.getId() < lastID) {
                        lastID = t.getId();
                    }
                }

            } catch (TwitterException te) {
                System.out.println("Couldn't connect: " + te);
            }
            query.setMaxId(lastID - 1);
        }
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CrawledData", "root", "");
        for (int i = 0; i < tweets.size(); i++) {
            Status t = (Status) tweets.get(i);

            //GeoLocation loc = t.getGeoLocation();
            String user = t.getUser().getScreenName();
            String msg = t.getText();
            String time = t.getCreatedAt().toString();
            //if (loc!=null) {
            //    Double lat = t.getGeoLocation().getLatitude();
            //    Double lon = t.getGeoLocation().getLongitude();
            //    System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);
            //} 
            //else{ 
            System.out.println(i + " USER: " + user + " wrote: " + msg + " at: " + time);
            //}
            try {
                Class.forName("com.mysql.jdbc.Driver");

                PreparedStatement ps = con
                        .prepareStatement("INSERT IGNORE INTO TwitterFeed VALUES (?,?,?,?,?)");
                ps.setString(1, s);
                ps.setString(2, cr.get_ticker_from_company(s));
                ps.setString(3, user);
                ps.setString(4, msg);
                ps.setString(5, time);

                int k = ps.executeUpdate();
                if (k <= 0) {
                    System.out.println("Entry Unsuccessful");
                } else {
                    System.out.println("Entry Successful");
                }

            } catch (ClassNotFoundException | SQLException e) {
                System.out.println(e);
            }

        }
        con.close();
    }
}

From source file:datasite.DataSite.java

public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/* w  w  w.  j a v  a 2s  .  co  m*/
    cb.setOAuthConsumerKey("ConsumerKey");
    cb.setOAuthConsumerSecret("ConsumerSecret");
    cb.setOAuthAccessToken("AccessToken");
    cb.setOAuthAccessTokenSecret("AccessTokenSecret");

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

    StatusListener listener;
    listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();

            try (PrintWriter out = new PrintWriter(
                    new BufferedWriter(new FileWriter("tweet_input\\tweets.txt", true))))

            {
                //out.println(username);

                String content = status.getText();
                out.println(content + "\n");
                //System.out.append( content +"\n");

            } catch (IOException ex) {
                Logger.getLogger(DataSite.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

    FilterQuery fq = new FilterQuery();

    String keywords[] = { "africa" };

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
    //twitterStream.();
}

From source file:datasite.SortedUnique.java

public static void main(String[] args) {
    ConfigurationBuilder confb = new ConfigurationBuilder();
    confb.setDebugEnabled(true);/*from   w w  w.  j  ava  2s.  c  om*/
    confb.setOAuthConsumerKey("Consumer Key");
    confb.setOAuthConsumerSecret("Consumer Secret");
    confb.setOAuthAccessToken("Access Token");
    confb.setOAuthAccessTokenSecret("Access Token Secret");

    TwitterStream twitterStream = new TwitterStreamFactory(confb.build()).getInstance();

    StatusListener listener;
    listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {

            PrintStream out = null;
            try {
                User user = status.getUser();
                // gets Username

                String username = status.getUser().getScreenName();
                String content = status.getText();
                Set<String> userWrds = new HashSet<String>(); // HashSet implements Set
                Scanner sc = new Scanner(content + user);
                while (sc.hasNext()) {
                    String word = sc.next();
                    userWrds.add(word);

                }
                out = new PrintStream(new FileOutputStream("tweet_output\\unique.txt", true));
                Iterator<String> iter = userWrds.iterator();
                for (int i = 1; i <= 1 && iter.hasNext(); i++)
                    //System.out.println(iter.next());
                    out.println(userWrds.size());
            } catch (FileNotFoundException ex) {
                Logger.getLogger(SortedUnique.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                out.close();
            }

        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "africa" };

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
    //twitterStream.();
}

From source file:de.binfalse.jatter.JatterTools.java

License:Open Source License

/**
 * Gets the twitter instance.//w  w w.j ava  2s . c o  m
 *
 * @param conf
 *          the conf
 * @return the twitter instance
 */
public static Twitter getTwitterInstance(Config conf) {
    if (twitter == null) {
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        confBuilder.setOAuthConsumerKey(conf.getTwitterConsumerKey());
        confBuilder.setOAuthConsumerSecret(conf.getTwitterConsumerSecret());
        confBuilder.setOAuthAccessToken(conf.getTwitterAccesstoken());
        confBuilder.setOAuthAccessTokenSecret(conf.getTwitterAccesstokenSecret());
        twitter = new TwitterFactory(confBuilder.build()).getInstance();
    }
    return twitter;
}