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:com.metadot.book.connectr.server.servlets.LoginTwitterServlet.java

License:Apache License

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Twitter twitter = new TwitterFactory().getInstance();
    // get auth info from system properties
    String key = AuthenticationProvider.getProp("twitter-consumer-key");
    String secret = AuthenticationProvider.getProp("twitter-consumer-secret");

    if (key == null || secret == null) {
        response.setContentType("text/html");
        response.getWriter().print(AppLib.INFONOTFOUND);
        return;/*w  w  w .j  a  va 2  s  .c  om*/
    }

    try {
        twitter.setOAuthConsumer(key, secret);
        String callbackURL = buildCallBackURL(request, AuthenticationProvider.TWITTER);
        RequestToken token = twitter.getOAuthRequestToken(callbackURL);
        request.getSession().setAttribute("requestToken", token);
        String loginURL = token.getAuthenticationURL() + "&force_login=true";
        log.info("Redirecting to: " + loginURL);
        response.sendRedirect(loginURL);

    } catch (TwitterException e) {
        response.setContentType("text/html");
        response.getWriter().print("<p>" + e.getMessage() + "</p>");
        response.getWriter().print(AppLib.INFONOTFOUND);
        return;
        // e.printStackTrace();
    }

}

From source file:com.practicando.controllers.adapters.LoginTwitterAdapter.java

@Override
public String login(HttpServletRequest request) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer("t2UVo2VHdoQx4QoP9GdysJzoA", "9D7wrEtAr2ffPJisbd68iUPQZohp0KW6Xh3fIUhPs2RGq3K477");
    request.getSession().setAttribute("twitter", twitter);
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/login-twitter-callback");
    RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
    request.getSession().setAttribute("requestToken", requestToken);
    return requestToken.getAuthenticationURL();

}

From source file:com.redhat.middleware.jdg.TwitterDemoClient.java

License:Open Source License

protected void authorize() throws TwitterException, IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*from   w  ww . j av  a 2s .c  o  m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        logger.info("Open the following URL and grant access to your account:");
        logger.info(requestToken.getAuthorizationURL());
        logger.info("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }

            this.accessToken = accessToken.getToken();
            this.accessTokenSecret = accessToken.getTokenSecret();
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                logger.info("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
}

From source file:com.robertszkutak.androidexamples.twitterexample.AndroidTwitterExample.java

License:Open Source License

public boolean isAuthenticated() {
    if (token == null || secret == null || token == "" || secret == "") {
        debug = "";
        debugStatus.setText(debug);//from ww  w  .  j  a  v  a2s .  c o  m
        return false;
    } else {
        AccessToken a = new AccessToken(token, secret);
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);

        try {
            twitter.getAccountSettings();
            return true;
        } catch (TwitterException e) {
            debug += "\n\n" + e.getMessage();
            debugStatus.setText(debug);
            return false;
        }
    }
}

From source file:com.robertszkutak.androidexamples.twitterexample.AndroidTwitterExample.java

License:Open Source License

public void sendTweetToTwitter(String msg) throws Exception {
    AccessToken a = new AccessToken(token, secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);/*from   w ww  .j  a  va2 s.c  om*/
    twitter.updateStatus(msg);
}

From source file:com.rsinghal.cep.sample.facebook.StreamCollector1.java

License:Apache License

public void start() {

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

    long[] userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {/*  www  . j ava2 s .  c o m*/
            String screenName = StringUtils.substringAfter(trackTerms.get(i), "@");
            logger.info("Fetching user ID for - " + screenName);
            userIdsToTrack[i] = twitter.showUser(screenName).getId();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    twitter = null;

    twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.addListener(listener2);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, userIdsToTrack, trackTerms.toArray(new String[trackTerms.size()])));

    System.out.println("start() ...");
    /*   // Create an appropriately sized blocking queue
       BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
               
       // create the endpoint
       DefaultStreamingEndpoint endpoint = createEndpoint();
       System.out.println("endpoint created ...");
            
       endpoint.stallWarnings(false);
            
       // create an authentication
       Authentication auth = new OAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            
       // Create a new BasicClient. By default gzip is enabled.
       client = new ClientBuilder().name("sampleExampleClient")
    .hosts(Constants.STREAM_HOST).endpoint(endpoint)
    .authentication(auth)
    .processor(new StringDelimitedProcessor(queue)).build();
       System.out.println("client created ...");
            
       // Create an executor service which will spawn threads to do the actual
       // work of parsing the incoming messages and
       // calling the listeners on each message
       ExecutorService service = Executors
    .newFixedThreadPool(this.numberOfProcessingThreads);
            
       // Wrap our BasicClient with the twitter4j client
       Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(client,
    queue, Lists.newArrayList(listener2), service);
            
       // Establish a connection
       t4jClient.connect();
               
       System.out.println("connection established ...");
            
       for (int threads = 0; threads < this.numberOfProcessingThreads; threads++) {
          // This must be called once per processing thread
          t4jClient.process();
          System.out.println("thread " + threads + " started ...");
            
       }*/
}

From source file:com.rsinghal.cep.sample.twitter.StreamCollector1.java

License:Apache License

public void start() {

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

    long[] userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {//from   ww  w  .j  a  v a 2  s  .  c  o m
            String screenName = StringUtils.substringAfter(trackTerms.get(i), "@");
            logger.info("Fetching user ID for - " + screenName);
            userIdsToTrack[i] = twitter.showUser(screenName).getId();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    twitter = null;
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    twitterStream.addListener(listener2);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, userIdsToTrack, trackTerms.toArray(new String[trackTerms.size()])));

    System.out.println("start() ...");
    /*   // Create an appropriately sized blocking queue
       BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
               
       // create the endpoint
       DefaultStreamingEndpoint endpoint = createEndpoint();
       System.out.println("endpoint created ...");
            
       endpoint.stallWarnings(false);
            
       // create an authentication
       Authentication auth = new OAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            
       // Create a new BasicClient. By default gzip is enabled.
       client = new ClientBuilder().name("sampleExampleClient")
    .hosts(Constants.STREAM_HOST).endpoint(endpoint)
    .authentication(auth)
    .processor(new StringDelimitedProcessor(queue)).build();
       System.out.println("client created ...");
            
       // Create an executor service which will spawn threads to do the actual
       // work of parsing the incoming messages and
       // calling the listeners on each message
       ExecutorService service = Executors
    .newFixedThreadPool(this.numberOfProcessingThreads);
            
       // Wrap our BasicClient with the twitter4j client
       Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(client,
    queue, Lists.newArrayList(listener2), service);
            
       // Establish a connection
       t4jClient.connect();
               
       System.out.println("connection established ...");
            
       for (int threads = 0; threads < this.numberOfProcessingThreads; threads++) {
          // This must be called once per processing thread
          t4jClient.process();
          System.out.println("thread " + threads + " started ...");
            
       }*/
}

From source file:com.stepinmobile.fantasticbutton.api.ButtonHandle.java

License:Apache License

/**
 * Method post tweet./*from  ww  w. j  a  va2 s .c om*/
 */
private void postTweet() {
    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(twitterHandle.getToken(), twitterHandle.getSecret());
    twitter.setOAuthConsumer(twitterAppId, twitterAppSecret);
    twitter.setOAuthAccessToken(accessToken);

    Status status = null;
    try {
        status = twitter.updateStatus(tweetToBeTweeted);
    } catch (TwitterException e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.temenos.interaction.example.mashup.twitter.OAuthRequestor.java

License:Open Source License

public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*  w w  w.j  a  va  2  s.c  o m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Open the following URL and grant access to your account:");
            LOGGER.debug(requestToken.getAuthorizationURL());
            LOGGER.debug("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        }

        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode() && LOGGER.isInfoEnabled()) {
                LOGGER.info("Unable to get the access token.");
            } else {
                LOGGER.error("Error writing the object.", te);
            }
        }
    }
    // persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId(), accessToken);

    // Tweet!      
    //      Status status = twitter.updateStatus(args[0]);
    //      System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:com.temenos.interaction.example.mashup.twitter.Twitter4JConsumer.java

License:Open Source License

/**
 * @param otherUser/*from   w w  w .java2s  . c o m*/
 * @return
 */
public Collection<Tweet> requestTweetsByUser(String otherUser) {
    List<Tweet> tweets = new ArrayList<Tweet>();
    try {
        // The factory instance is re-useable and thread safe.
        Twitter twitter = new TwitterFactory().getInstance();
        AccessToken accessToken = loadAccessToken(1);
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(accessToken);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Fetching latest 100 tweets for [" + otherUser + "]");
        }
        // First param of Paging() is the page number, second is the number per page (this is capped around 200 I think.
        Paging paging = new Paging(1, 100);
        List<Status> statuses = twitter.getUserTimeline(otherUser, paging);
        for (Status status : statuses) {
            tweets.add(new Tweet(otherUser, status.getText(),
                    (status.getGeoLocation() != null
                            ? status.getGeoLocation().getLatitude() + ","
                                    + status.getGeoLocation().getLongitude()
                            : "")));
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(
                        status.getUser().getName() + "(" + status.getGeoLocation() + "):" + status.getText());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error on requestTweetsByUser", e);
        throw new TwitterMashupException(e);
    }
    return tweets;
}