Example usage for twitter4j.auth RequestToken getAuthenticationURL

List of usage examples for twitter4j.auth RequestToken getAuthenticationURL

Introduction

In this page you can find the example usage for twitter4j.auth RequestToken getAuthenticationURL.

Prototype

public String getAuthenticationURL() 

Source Link

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 {/*from  w w  w .j  a v a  2  s . c om*/

        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:com.arihant15.ActionServlet.java

@RequestMapping("/login.arihant15")
public void doLogin(HttpServletRequest req, HttpServletResponse res) {
    try {/*from  w ww  .jav a  2  s.co m*/
        ConfigurationBuilder configuration = new ConfigurationBuilder();
        configuration.setOAuthConsumerKey(ConsumerKey);
        configuration.setOAuthConsumerSecret(ConsumerSecret);
        TwitterFactory twitterfactory = new TwitterFactory(configuration.build());
        Twitter twitter = twitterfactory.getInstance();
        req.getSession().setAttribute("t", twitter);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        req.getSession().setAttribute("rToken", requestToken);
        res.sendRedirect(requestToken.getAuthenticationURL());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Get the authorization URL and send it back in a sticky broadcast.
 *///w w  w .j  a  v a2 s . c o m
private void processGetAuthURL() {

    //create a RequestToken to use to create the request URL 
    // token will be used later to decode result from twitter.com
    // and needs to be saved to static variable in MSTwitter
    RequestToken reqToken = null;
    Twitter twitter4j = null;
    String url = null;
    int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL; // be optimistic 

    try {
        twitter4j = new TwitterFactory().getInstance();
        twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
    } catch (IllegalStateException e) {
        // No network access or token already available
        resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
        Log.e(MSTwitter.TAG, e.toString());
    }

    // get the token
    if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) {
        try {
            reqToken = twitter4j.getOAuthRequestToken(MSTwitter.CALLBACK_URL);
        } catch (TwitterException e) {
            int tErrorNum = MSTwitter.getTwitterErrorNum(e, this);
            // No network access 
            resultCode = tErrorNum;
            Log.e(MSTwitter.TAG, e.getExceptionCode() + ": " + e.getMessage());
        } catch (IllegalStateException e) {
            // No network access or token already available
            resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_TOKEN_ALREADY_AVALIABLE;
            Log.e(MSTwitter.TAG, e.toString());
        }
    }

    // if we got the request token then use it to get the url
    if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) {
        url = reqToken.getAuthenticationURL();
        // save the request token
        MSTwitter.smReqToken = reqToken;
    }

    // broadcast the results
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MSTwitter.INTENT_BROADCAST_MSTWITTER);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_SERVICE_TASK,
            MSTwitterService.MST_SERVICE_TASK_GET_AUTH_URL);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_AUTHURL_RESULT, resultCode);
    if (url != null) {
        broadcastIntent.putExtra(MSTwitterService.MST_KEY_AUTHURL_RESULT_URL, url);
    }
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_TEXT, mText);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_IMAGE_PATH, mImagePath);
    sendStickyBroadcast(broadcastIntent);
}

From source file:com.jeanchampemont.wtfdyum.web.MainController.java

License:Apache License

@RequestMapping(value = "/signin", method = RequestMethod.GET)
public RedirectView signin(final HttpServletRequest request) throws WTFDYUMException {
    if (authenticationService.isAuthenticated()) {
        return new RedirectView("/user", true);
    }/*from  w  w w. j a  v  a  2 s .c o  m*/

    if (maxMembers > 0 && principalService.countMembers() >= maxMembers) {
        throw new WTFDYUMException(WTFDYUMExceptionType.MEMBER_LIMIT_EXCEEDED);
    }

    final RequestToken requestToken = twitterService.signin("/signin/callback");

    request.getSession().setAttribute(SESSION_REQUEST_TOKEN, requestToken);

    return new RedirectView(requestToken.getAuthenticationURL());
}

From source file:com.marpies.ane.twitter.LoginActivity.java

License:Apache License

/**
 *
 *
 * Private API// w  w w  .ja  v  a  2 s .c o m
 *
 *
 */

private TwitterAdapter getOAuthRequestTokenListener(final boolean forceLogin) {
    return new TwitterAdapter() {
        @Override
        public void gotOAuthRequestToken(RequestToken token) {
            TwitterAPI.setRequestToken(token);
            StringBuilder urlBuilder = new StringBuilder(token.getAuthenticationURL());
            if (forceLogin) {
                urlBuilder.append("&force_login=true");
            }
            /* Launch browser */
            LoginActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlBuilder.toString())));
        }

        @Override
        public void onException(TwitterException te, TwitterMethod method) {
            if (method == TwitterMethod.OAUTH_REQUEST_TOKEN) {
                AIR.log("Request token exception " + te.getMessage());
                AIR.dispatchEvent(AIRTwitterEvent.LOGIN_ERROR, StringUtils.removeLineBreaks(te.getMessage()));
            }
            finish();
        }
    };
}

From source file:com.michaelstark.twitteroauth.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * Begins the OAuth authentication mechanism.
 *
 * @param request servlet request/*from ww w  . ja  va 2 s  .  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ConfigurationBuilder builder = new ConfigurationBuilder();

    builder.setOAuthConsumerKey("<consumer key goes here>")
            .setOAuthConsumerSecret("<consumer secret goes here>");

    Twitter twitter = new TwitterFactory(builder.build()).getInstance();

    HttpSession session = request.getSession(true);

    // Get the callback URL.
    String callbackUrl = String.format("http://%s:%d%s/oauth_callback", request.getServerName(),
            request.getServerPort(), request.getContextPath());

    try {
        // Get the request token.
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);

        // Store the request token for later use.
        session.setAttribute("requestToken", requestToken);

        // Save the Twitter client for later.
        session.setAttribute("twitterClient", twitter);

        // Redirect to Twitter authentication page.
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        logger.log(Level.SEVERE, "Could not login via Twitter: ", e);

        // Failure. Go back to home. Maybe add an error message.
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.mycompany.dovetune.SignIn.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww w . ja  v a  2  s  .c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Djgh7AmnNzxmv7fXzqlsdj8RB")
            .setOAuthConsumerSecret("Mnj40YllwKBBZvOkndnrmxl1TaNvcnS0x40PFhhDnMHysgzHum");

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

    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        System.out.println("TwitterLoginServlet:callbackURL:" + callbackURL);

        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/Callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        System.out.println("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:com.mycompany.twitterdemo.SignIn.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* w ww  . j a va2s. c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    request.getSession().setAttribute("twitter", twitter);
    System.out.println("key:" + twitter.getConfiguration().getOAuthConsumerKey());
    System.out.println("secret: " + twitter.getConfiguration().getOAuthConsumerSecret());
    try {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
    processRequest(request, response);
}

From source file:com.mycompany.twittersearch.SignIn.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w w  .jav a  2 s.  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("");

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

    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        System.out.println("TwitterLoginServlet:callbackURL:" + callbackURL);

        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/Callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        System.out.println("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }

}

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();

}