Example usage for twitter4j Twitter setOAuthConsumer

List of usage examples for twitter4j Twitter setOAuthConsumer

Introduction

In this page you can find the example usage for twitter4j Twitter setOAuthConsumer.

Prototype

void setOAuthConsumer(String consumerKey, String consumerSecret);

Source Link

Document

sets the OAuth consumer key and consumer secret

Usage

From source file:es.upm.oeg.examples.watson.servlets.TwitterAnalysisServlet.java

License:Apache License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from  w w  w  .  j  a v a2s .c  o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String twitterUsername = request.getParameter("twitter_name");
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    env = System.getenv();
    consumer_key = env.get("TWITTER_CONSUMER_KEY");
    consumer_secret = env.get("TWITTER_CONSUMER_SECRET");
    access_token = env.get("TWITTER_ACCESS_TOKEN");
    access_key = env.get("TWITTER_ACCESS_KEY");

    AccessToken accessToken = new AccessToken(access_token, access_key);

    try {
        twitter.setOAuthConsumer(consumer_key, consumer_secret);
        twitter.setOAuthAccessToken(accessToken);

        twitter4j.User a_name = twitter.showUser(twitterUsername);
        int followerCount = a_name.getFollowersCount();
        List<Status> retweets = twitter.getUserTimeline(twitterUsername, new Paging(1, 20)); // get the first twenty tweets
        int retweetCount = 0;
        List<String> langs = new ArrayList<>();
        List<String> translated = new ArrayList<>();

        StringBuilder aggregatedTextBuilder = new StringBuilder();
        String personalityInsights = null;

        for (Status tweet : retweets) {
            String tweetText = tweet.getText();
            try {
                String lang = languageIdentification.getLang(tweetText);
                langs.add(lang);
                String englishText;
                //TODO do the same for french and portuguese
                if (LanguageIdentificationService.ES_ES.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.ES_TO_EN);
                } else if (LanguageIdentificationService.FR_FR.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.FR_TO_EN);
                } else if (LanguageIdentificationService.PT_BR.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.PT_TO_EN);
                } else {
                    englishText = tweetText;
                }
                translated.add(englishText);
                aggregatedTextBuilder.append(englishText);

                personalityInsights = personalityInsightsService.analyse(aggregatedTextBuilder.toString());

            } catch (Exception e) {
                // Log something and return an error message
                logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
                request.setAttribute("error", e.getMessage());
            }

        }

        request.setAttribute("t_name", twitterUsername);
        request.setAttribute("rtweets", retweets);
        request.setAttribute("langs", langs);
        request.setAttribute("translated", translated);
        request.setAttribute("personalityInsights", personalityInsights);
        request.setAttribute("aggregatedText", aggregatedTextBuilder.toString());

        request.getRequestDispatcher("/myTweets.jsp").forward(request, response);
    } catch (TwitterException e) {

        e.printStackTrace();
        if (e.getErrorCode() == 215 || e.getErrorCode() == 32) {
            response.sendRedirect("../index.html?message=errorcode215");
        } else if (e.getErrorCode() == -1 || e.getErrorCode() == 34) {
            response.sendRedirect("../index.html?message=errorcode-1");
        } else {
            response.sendRedirect("../index.html?message=errorcode99");
        }
        //throw new ServletException("Encountered a problem fetching data from Twitter - " + e.getErrorMessage());
    }
}

From source file:Group5.Model.java

public static void Tweet(String inputTweet) throws TwitterException {
    //Your Twitter App's Consumer Key
    String consumerKey = "wK7lQLpl3t8xvIABqpgoJzYYd";

    //Your Twitter App's Consumer Secret
    String consumerSecret = "4M5TgmNfS0EKeaSqna8eHTNaNi970Plq3dynX5gvYsh848j0mj";

    //Your Twitter Access Token
    String accessToken = "829891753473892361-7jkKyXLYc6HOStzCPGjWOnVoAVNU7cd";

    //Your Twitter Access Token Secret
    String accessTokenSecret = "ATidrzRzhVqAamuMbYiskcHBPSisB9MWsCsYYY2Bec4y9";

    //Instantiate a re-usable and thread-safe factory
    TwitterFactory twitterFactory = new TwitterFactory();

    //Instantiate a new Twitter instance
    Twitter twitter = twitterFactory.getInstance();
    //setup OAuth Consumer Credentials
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    //setup OAuth Access Token
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    //Instantiate and initialize a new twitter status update
    StatusUpdate statusUpdate = new StatusUpdate(
            //your tweet or status message
            inputTweet);//w  ww.  j a v  a  2 s  .c o m

    //tweet or update status
    Status status = twitter.updateStatus(statusUpdate);

    //response from twitter server
    System.out.println("status.toString() = " + status.toString());
    System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
    System.out.println("status.getSource() = " + status.getSource());
    System.out.println("status.getText() = " + status.getText());

    System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
    System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
}

From source file:Group5.Model.java

public static List GetTimeline() throws TwitterException {
    //Your Twitter App's Consumer Key
    String consumerKey = "wK7lQLpl3t8xvIABqpgoJzYYd";

    //Your Twitter App's Consumer Secret
    String consumerSecret = "4M5TgmNfS0EKeaSqna8eHTNaNi970Plq3dynX5gvYsh848j0mj";

    //Your Twitter Access Token
    String accessToken = "829891753473892361-7jkKyXLYc6HOStzCPGjWOnVoAVNU7cd";

    //Your Twitter Access Token Secret
    String accessTokenSecret = "ATidrzRzhVqAamuMbYiskcHBPSisB9MWsCsYYY2Bec4y9";

    //Instantiate a re-usable and thread-safe factory
    TwitterFactory twitterFactory = new TwitterFactory();

    //Instantiate a new Twitter instance
    Twitter twitter = twitterFactory.getInstance();
    //setup OAuth Consumer Credentials
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    //setup OAuth Access Token
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    List<Status> statuses = twitter.getHomeTimeline();
    System.out.println("Showing home timeline.");
    for (Status status : statuses) {
        System.out.println(status.getUser().getName() + ":" + status.getText());
    }//from w w  w. j av  a2 s  .c  o m
    return statuses;
}

From source file:info.maslowis.twitterripper.twitter.OAuthTwitter.java

License:Open Source License

/**
 * Displays authorization URL and gets PIN for connection to twitter under authorized user
 *//*from ww  w.j a  v a2 s .  c  om*/
public void authorization() throws IOException {
    try {
        Twitter twitter = TwitterFactory.getSingleton();
        twitter.setOAuthConsumer(consumerKey, consumerKeySecret);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Authorization URL:").reset());
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.CYAN).a(requestToken.getAuthorizationURL()));
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.RED).a("Enter PIN please:").reset());
        String pin = reader.readLine();
        twitter.getOAuthAccessToken(requestToken, pin);
    } catch (TwitterException e) {
        logger.error("Authorization fail! Please try to run application again and enter PIN.");
        exit(1);
    }
}

From source file:javatwiter4j.NewJFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    String tweet = "";
    tweet = jTextField1.getText();/*from www.jav  a2s  .  co  m*/
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(apiKey, apiSecretKey);
        AccessToken accessTokenn = new AccessToken(accessToken, accessTokenSecret);
        twitter.setOAuthAccessToken(accessTokenn);
        twitter.updateStatus(tweet);
    } catch (Exception ex) {
        jLabel1.setText("Son Tweet: Gnderilemedi");
    }
    jLabel1.setText("Son Tweet: Gnderildi");
}

From source file:jp.co.tweetmap.util.TwitterUtils.java

License:Apache License

/**
 * Gets the Twitter instance. Access token is automatically set if it is saved.
 *
 * @param context {@link Context}, not {@code null}.
 * @return Twitter instance./*from  w ww . j av  a 2  s  .  c o  m*/
 */
public static Twitter getTwitterInstance(Context context) {
    String consumerKey = context.getString(R.string.twitter_consumer_key);
    String consumerSecret = context.getString(R.string.twitter_consumer_secret_key);

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    if (hasAccessToken(context)) {
        twitter.setOAuthAccessToken(loadAccessToken(context));
    }
    return twitter;
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.MainApp.java

License:Open Source License

@Override
public void init() throws Exception {
    // DI/* www  . ja v a  2s  .  co  m*/
    Injector injector = Guice.createInjector();
    injector.injectMembers(this);

    // Twitter?ConsumerKey/ConsumerSecret?
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(TwitterAPIKey.getConsumerKey(), TwitterAPIKey.getConsumerSecret());
    AccessToken accessToken = repository.load();
    if (accessToken != null) {
        twitter.setOAuthAccessToken(accessToken);
    }
}

From source file:mineTwit.Main.java

License:Open Source License

private void authenticateTwitter(AccessToken accessToken, Twitter twitter, String loadKey, String loadSecret) {
    //getLogger().info("[authenticateTwitter][DEBUG]APItoken is " + loadKey);
    //getLogger().info("[authenticateTwitter][DEBUG]APIsecret is " + loadSecret);
    twitter.setOAuthConsumer(loadKey, loadSecret);
    twitter.setOAuthAccessToken(accessToken);
}

From source file:net.bluemix.droneselfie.TwitterUtilities.java

License:Open Source License

private String tweet(String pictureId, String message) {
    String output = null;//from  w ww.ja  v a  2 s  .  c o  m
    if (message == null)
        return null;
    if (message.equalsIgnoreCase(""))
        return null;

    try {
        String consumerKey = ConfigUtilities.getSingleton().getTwitterConsumerKey();
        String consumerSecret = ConfigUtilities.getSingleton().getTwitterConsumerSecret();
        String accessToken = ConfigUtilities.getSingleton().getTwitterAccessToken();
        String accessTokenSecret = ConfigUtilities.getSingleton().getTwitterAccessTokenSecret();

        TwitterFactory twitterFactory = new TwitterFactory();
        Twitter twitter = twitterFactory.getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

        StatusUpdate statusUpdate = new StatusUpdate(message);

        AttachmentInputStream data = DatabaseUtilities.getSingleton().getDB().getAttachment(pictureId,
                pictureId);
        statusUpdate.setMedia("picture", data);

        Status status = twitter.updateStatus(statusUpdate);
        if (status == null)
            return null;
        output = "https://twitter.com/bluedroneselfie/status/" + String.valueOf(status.getId());

        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return output;
}

From source file:net.bluemix.newsaggregator.TwitterUtilities.java

License:Open Source License

private String tweet(String message) {
    String output = null;//from   w  w w.ja v  a 2 s .  co  m
    if (message == null)
        return null;
    if (message.equalsIgnoreCase(""))
        return null;

    try {
        String consumerKey = ConfigUtilities.getSingleton().getTwitterConsumerKey();
        String consumerSecret = ConfigUtilities.getSingleton().getTwitterConsumerSecret();
        String accessToken = ConfigUtilities.getSingleton().getTwitterAccessToken();
        String accessTokenSecret = ConfigUtilities.getSingleton().getTwitterAccessTokenSecret();

        TwitterFactory twitterFactory = new TwitterFactory();
        Twitter twitter = twitterFactory.getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

        StatusUpdate statusUpdate = new StatusUpdate(message);

        Status status = twitter.updateStatus(statusUpdate);
        if (status == null)
            return null;
        output = "https://twitter.com/BluemixInfo/status/" + String.valueOf(status.getId());

        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return output;
}