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:bluevia.OAuth.java

License:Apache License

private String oAuthTwitter(HttpServletRequest req, String step) {
    String oAuthUrl = "/index.jsp";
    Properties prop = new Properties();

    prop.setProperty("oauth.consumerKey", TwitterOAuth.consumer_key);
    prop.setProperty("oauth.consumerSecret", TwitterOAuth.consumer_secret);

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(TwitterOAuth.consumer_key, TwitterOAuth.consumer_secret);
    try {//w w w.  j ava 2 s  .c  o  m

        if (step.compareTo("1") == 0) {

            RequestToken requestToken = twitter
                    .getOAuthRequestToken(Util.getCallbackDomain() + "/oauth?network=twitter&step=2");

            req.getSession().setAttribute("request_key", requestToken.getToken());
            req.getSession().setAttribute("request_secret", requestToken.getTokenSecret());

            oAuthUrl = requestToken.getAuthenticationURL();

        } else {

            String request_key = (String) req.getSession().getAttribute("request_key");
            String request_secret = (String) req.getSession().getAttribute("request_secret");

            String oauth_verifier = req.getParameter("oauth_verifier");

            RequestToken requestToken = new RequestToken(request_key, request_secret);
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);

            UserService userService = UserServiceFactory.getUserService();
            User user = userService.getCurrentUser();

            Util.addNetworkAccount(user.getEmail(), "TwitterAccount", Util.TwitterOAuth.consumer_key,
                    Util.TwitterOAuth.consumer_secret, accessToken.getToken(), accessToken.getTokenSecret());

            req.getSession().removeAttribute("request_key");
            req.getSession().removeAttribute("request_secret");

            oAuthUrl = "/settings.jsp";
        }
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.severe(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        logger.severe(e.getMessage());
    }

    return oAuthUrl;
}

From source file:bluevia.SendSMS.java

License:Apache License

public static void setTwitterStatus(String userEmail, String tweet) {
    if (tweet != null) {
        try {/*  w w w  .  j a va 2  s .c  om*/
            Properties twitterAccount = Util.getNetworkAccount(userEmail, "TwitterAccount");

            if (twitterAccount != null) {
                String consumer_key = twitterAccount.getProperty("TwitterAccount.consumer_key");
                String consumer_secret = twitterAccount.getProperty("TwitterAccount.consumer_secret");
                String access_key = twitterAccount.getProperty("TwitterAccount.access_key");
                String access_secret = twitterAccount.getProperty("TwitterAccount.access_secret");

                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(consumer_key, consumer_secret);
                twitter.setOAuthAccessToken(new AccessToken(access_key, access_secret));

                StatusUpdate status = new StatusUpdate(tweet);
                twitter.updateStatus(status);
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            log.severe(te.getMessage());
        } catch (Exception e) {
            log.severe(String.format("Error sending SMS: %s", e.getMessage()));
        }
    }
}

From source file:br.shura.team.mpsbot.runtime.ConnectedBot.java

License:Open Source License

public void prepare(Function<URL, String> pinEvaluator)
        throws IllegalStateException, MalformedURLException, TwitterException {
    ApiKeys keys = getBot().getApiKeys();

    if (!isPrepared()) {
        Twitter handler = TwitterFactory.getSingleton();

        handler.setOAuthConsumer(keys.getConsumerKey(), keys.getConsumerSecret());

        RequestToken requestToken = handler.getOAuthRequestToken();
        URL url = new URL(requestToken.getAuthorizationURL());

        while (accessToken == null) {
            String pin = pinEvaluator.apply(url);

            try {
                if (pin != null && !pin.isEmpty()) {
                    this.accessToken = handler.getOAuthAccessToken(requestToken, pin);
                    this.handler = handler;
                } else {
                    return;
                }//from  ww w.  ja v a  2  s  .  com
            } catch (TwitterException exception) {
                System.err.println("Could not evaluate OAuth access token:");
                System.err.println(exception);
            }
        }
    }

    getHandler().verifyCredentials();
}

From source file:br.ufba.dcc.tagcloud.util.TwitterProvider.java

public void start(String user, int max) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
    AccessToken oathAccessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    twitter.setOAuthAccessToken(oathAccessToken);
    this.getTweets(twitter, user, max);
}

From source file:ColourUs.OAuth.java

private void reauthorize() throws Exception {
    // In case we lose the A_SECRET
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(C_KEY, C_SECRET);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*from  w ww  .j ava 2s .  co  m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        System.out.println("Open the following URL and grant access to your account:");
        System.out.println(requestToken.getAuthorizationURL());
        System.out.print("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()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    show((int) twitter.verifyCredentials().getId(), accessToken);
}

From source file:com.adobe.acs.commons.twitter.impl.TwitterAdapterFactory.java

License:Apache License

private TwitterClient createTwitterClient(com.day.cq.wcm.webservicesupport.Configuration config) {
    Resource oauthConfig = config.getContentResource().listChildren().next();
    ValueMap oauthProps = ResourceUtil.getValueMap(oauthConfig);
    String consumerKey = oauthProps.get("oauth.client.id", String.class);
    String consumerSecret = oauthProps.get("oauth.client.secret", String.class);

    if (consumerKey != null && consumerSecret != null) {
        Twitter t = factory.getInstance();
        log.debug("Creating client for key {}.", consumerKey);
        t.setOAuthConsumer(consumerKey, consumerSecret);
        try {/*from   www . ja  v  a2s. c om*/
            t.getOAuth2Token();
            return new TwitterClientImpl(t, config);
        } catch (TwitterException e) {
            log.error("Unable to create Twitter client.", e);
            return null;
        }
    } else {
        log.warn("Key or Secret missing for configuration {}", config.getPath());
    }

    return null;
}

From source file:com.allenzheng.twittersyn.utility.impl.TwitterAPIImpl.java

License:Apache License

    public String getAuthorisationUrl() throws TwitterException{
      Properties prop = loadProperties();
      //from  w  ww  .  j av  a 2  s. co  m
         Twitter twitter = new TwitterFactory().getInstance();
         twitter.setOAuthConsumer(prop.getProperty("twitter.consumerkey"), 
               prop.getProperty("twitter.consumersecret"));
         try {
            RequestToken requestToken;
            if (callbackUrl == null) {
               requestToken = twitter.getOAuthRequestToken();
            } else {
               requestToken = twitter
                     .getOAuthRequestToken(callbackUrl);
            }
            String authorisationUrl = requestToken
                  .getAuthorizationURL();
//            session.setAttribute(ATTR_TWITTER, twitter);
//            session.setAttribute(ATTR_REQUEST_TOKEN, requestToken);

            logger.debug("Redirecting user to " + authorisationUrl);
//            response.sendRedirect(authorisationUrl);
            return authorisationUrl;
         } catch (TwitterException e) {
            logger.error("Sign in with Twitter failed - "
                  + e.getMessage());
            e.printStackTrace();
            throw new TwitterException(e);
         }
      
      
   }

From source file:com.amazonbird.announce.AnnouncerMgrImpl.java

License:Open Source License

public boolean announcerIsvalid(Announcer announcer) {
    try {/*from w w  w  .ja v  a2  s .co  m*/
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
        twitter.setOAuthAccessToken(
                new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));

    } catch (Exception ex) {
        return false;
    }
    return true;

}

From source file:com.anshul.LoginServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/*from   ww  w  .ja  va2  s  .  c o m*/
        Twitter twitter = new TwitterFactory().getInstance();

        try {
            twitter.setOAuthConsumer("dyHSJLTZhh2eSSw2RVpqMIKyJ",
                    "jW22uPPA54DOMNicfFJWzf4jB7nKHbdi7L6VuPFlfWEPAOt5Ai");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

        StringBuffer callbackURL = req.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/home");

        RequestToken requestToken;
        requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        String token = requestToken.getToken();
        String tokenSecret = requestToken.getTokenSecret();

        HttpSession session = req.getSession();
        session.setAttribute("twitter", twitter);
        String authUrl = requestToken.getAuthorizationURL();
        //        session.setAttribute("authUrl", authUrl);
        req.setAttribute("authUrl", authUrl);
        RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
        rd.forward(req, resp);
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.appspot.bitlyminous.command.authentication.AbstractAuthenticationCommand.java

License:Apache License

/**
 * Execute twitter o auth.//  www.  j a  v  a2  s. c  om
 * 
 * @param req the req
 * @param resp the resp
 * @param callbackUrl the callback url
 * 
 * @return true, if successful
 * 
 * @throws Exception the exception
 */
protected boolean executeTwitterOAuth(HttpServletRequest req, HttpServletResponse resp, String callbackUrl)
        throws Exception {
    HttpSession session = req.getSession(true);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ApplicationConstants.TWITTER_CONSUMER_KEY,
            ApplicationConstants.TWITTER_CONSUMER_SECRET);
    if (session.getAttribute(ParameterNames.REQUEST_TOKEN_PARAM) == null
            || session.getAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM) == null) {
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
        session.setAttribute(ParameterNames.REQUEST_TOKEN_PARAM, requestToken.getToken());
        session.setAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM, requestToken.getTokenSecret());
        resp.sendRedirect(requestToken.getAuthenticationURL());
        return false;
    } else {
        AccessToken accessToken = twitter.getOAuthAccessToken(
                new RequestToken((String) session.getAttribute(ParameterNames.REQUEST_TOKEN_PARAM),
                        (String) session.getAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM)),
                req.getParameter(ParameterNames.OAUTH_VERIFIER));
        session.removeAttribute(ParameterNames.REQUEST_TOKEN_PARAM);
        session.removeAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM);
        User user = userService.getUserByScreenName(accessToken.getScreenName());
        if (user == null) {
            user = new User();
            user.setScreenName(accessToken.getScreenName());
        }
        user.setTwitterToken(new Text(accessToken.getToken()));
        user.setTwitterSecret(new Text(accessToken.getTokenSecret()));
        session.setAttribute(ParameterNames.SESSION_USER, user);
        return true;
    }
}