Example usage for twitter4j Twitter getOAuthAccessToken

List of usage examples for twitter4j Twitter getOAuthAccessToken

Introduction

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

Prototype

AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;

Source Link

Document

Retrieves an access token associated with the supplied request token and sets userId.

Usage

From source file:org.gatein.security.oauth.twitter.TwitterProcessorImpl.java

License:Open Source License

@Override
public InteractionState<TwitterAccessTokenContext> processOAuthInteraction(HttpServletRequest request,
        HttpServletResponse response) throws IOException, OAuthException {
    Twitter twitter = twitterFactory.getInstance();

    HttpSession session = request.getSession();

    //See if we are a callback
    RequestToken requestToken = (RequestToken) session
            .getAttribute(OAuthConstants.ATTRIBUTE_TWITTER_REQUEST_TOKEN);

    try {/*from w w  w.j a v a2  s. c o  m*/
        if (requestToken == null) {
            requestToken = twitter.getOAuthRequestToken(redirectURL);

            // Save requestToken to session, but only temporarily until oauth workflow is finished
            session.setAttribute(OAuthConstants.ATTRIBUTE_TWITTER_REQUEST_TOKEN, requestToken);

            if (log.isTraceEnabled()) {
                log.trace("RequestToken obtained from twitter. Redirecting to Twitter for authorization");
            }

            // Redirect to twitter to perform authentication
            response.sendRedirect(requestToken.getAuthenticationURL());

            return new InteractionState<TwitterAccessTokenContext>(InteractionState.State.AUTH, null);
        } else {
            String verifier = request.getParameter(OAuthConstants.OAUTH_VERIFIER);

            // User denied scope
            if (request.getParameter(OAuthConstants.OAUTH_DENIED) != null) {
                throw new OAuthException(OAuthExceptionCode.USER_DENIED_SCOPE,
                        "User denied scope on Twitter authorization page");
            }

            // Obtain accessToken from twitter
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

            if (log.isTraceEnabled()) {
                log.trace("Twitter accessToken: " + accessToken);
            }

            // Remove requestToken from session. We don't need it anymore
            session.removeAttribute(OAuthConstants.ATTRIBUTE_TWITTER_REQUEST_TOKEN);
            TwitterAccessTokenContext accessTokenContext = new TwitterAccessTokenContext(accessToken.getToken(),
                    accessToken.getTokenSecret());

            return new InteractionState<TwitterAccessTokenContext>(InteractionState.State.FINISH,
                    accessTokenContext);
        }
    } catch (TwitterException twitterException) {
        throw new OAuthException(OAuthExceptionCode.TWITTER_ERROR, twitterException);
    }
}

From source file:org.jetbrains.webdemo.servlet.TwitterServlet.java

License:Apache License

private void tweet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//  w w  w  .  j a v  a  2 s.  com
        Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
        RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
        String verifier = request.getParameter("oauth_verifier");
        twitter.getOAuthAccessToken(requestToken, verifier);

        String status = (String) request.getSession().getAttribute("tweetText");
        request.getSession().removeAttribute("tweetText");
        StatusUpdate statusUpdate = new StatusUpdate(status);

        String level = (String) request.getSession().getAttribute("kotlin-level");
        request.getSession().removeAttribute("level");
        statusUpdate.setMedia(
                new File(CommonSettings.WEBAPP_ROOT_DIRECTORY + "static/images/" + level + "level.gif"));

        twitter.updateStatus(statusUpdate);
        request.getSession().removeAttribute("requestToken");
        response.sendRedirect(request.getContextPath() + "/");
    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

/**
 * posts a Twitter message on behalf of a OAtuh authenticated user by using
 * the retrieved AccessToken and its verifier.
 *
 * @param aConnector/*from   ww  w  .  j av  a2 s.co  m*/
 * @param aToken
 */
private void tweet(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg = aToken.getString("message");
    try {
        // to send tweet we need an authenticated user
        Twitter lTwitter = (Twitter) aConnector.getVar(TWITTER_VAR);
        RequestToken lReqToken = (RequestToken) aConnector.getVar(OAUTH_REQUEST_TOKEN);
        String lVerifier = aConnector.getString(OAUTH_VERIFIER);

        if (lTwitter == null) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "Not yet authenticated against Twitter!");
        } else if (lReqToken == null) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "No Access Token available!");
        } else if (lVerifier == null) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "No Access Verifier available!");
        } else if (lMsg == null || lMsg.length() <= 0) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "No message passed for tweet.");
        } else {
            AccessToken lAccessToken = lTwitter.getOAuthAccessToken(lReqToken, lVerifier);
            lTwitter.setOAuthAccessToken(lAccessToken);

            lTwitter.updateStatus(lMsg);
            lMsg = "Twitter status successfully updated for user '" + lTwitter.getScreenName() + "'.";
            lResponse.setString("msg", lMsg);
            if (mLog.isInfoEnabled()) {
                mLog.info(lMsg);
            }
        }
    } catch (Exception lEx) {
        lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.kawalpemilukada.login.callbackTwit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* www .  j  ava2  s.co 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 {
    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    String rurl = request.getParameter("rurl");
    try {
        twitter.getOAuthAccessToken(requestToken, verifier);
        request.getSession().removeAttribute("requestToken");
    } catch (TwitterException e) {
    }
    request.getSession().setAttribute("twitter", twitter);
    String errorMsg = "Data Anda belum terverifikasi.";
    Dashboard dashboard = CommonServices.getDashboard(CommonServices.setParentId("2015", "0"));
    Dashboard dashboard2014 = CommonServices.getDashboard(CommonServices.setParentId("2014", "0"));
    request.getSession().removeAttribute("tahun");
    UserData user = null;
    try {
        User u = twitter.showUser(twitter.getId());
        user = ofy().load().type(UserData.class).id("twit" + CommonServices.getVal(twitter.getId())).now();
        if (user == null) {
            user = new UserData("twit" + CommonServices.getVal(twitter.getId()));
            user.imgurl = u.getBiggerProfileImageURLHttps().replace("http://", "https://");
            user.nama = CommonServices.getVal(u.getName());
            user.link = "https://twitter.com/" + CommonServices.getVal(twitter.getScreenName());
            user.email = "";
            user.type = "twit";
            user.userlevel = 100;
            user.terverifikasi = "Y";
            ofy().save().entity(user).now();
            dashboard.users = CommonServices.getuserSize() + "";
            ofy().save().entity(dashboard).now();
            dashboard2014.users = dashboard.users + "";
            ofy().save().entity(dashboard2014).now();
        } else {
            user.lastlogin = CommonServices.JakartaTime();
            user.type = "twit";
            user.imgurl = u.getBiggerProfileImageURL().replace("http://", "https://");
            if (user.type.equalsIgnoreCase("twit")
                    && user.nama.equalsIgnoreCase(CommonServices.getVal(u.getName()))) {
                if (user.terverifikasi.equalsIgnoreCase("Y")) {
                    errorMsg = "";
                }
            } else {
                user.nama = CommonServices.getVal(u.getName());
                user.terverifikasi = "N";
            }
            ofy().save().entity(user).now();
        }
        Gson gson = new Gson();
        request.getSession().setAttribute("UserData", JSONValue.parse(gson.toJson(user)));
    } catch (Exception e) {
        errorMsg = "callbackTwit [processRequest] ==> " + e.toString();
    }
    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Kawal Pemilu Kepala Daerah</title>");
        out.println("<script src=\"/bower_components/jquery/dist/jquery.min.js\"></script>");
        out.println("<script src=\"/dist/js/vendor.js\"></script>");
        out.println("</head>");
        out.println("<body>Sedang Login...");
        out.println("<script>");
        out.println("if (!jQuery.browser.mobile) {");
        out.println("try{window.opener.inviteCallback(" + gson.toJson(user) + "," + gson.toJson(dashboard)
                + ",'" + errorMsg + "');}catch(e){window.location='/'}");
        out.println("self.close();");
        out.println("}else{window.location='/#" + rurl + "'}");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
    }

}

From source file:org.keycloak.social.twitter.TwitterProvider.java

License:Open Source License

@Override
public SocialUser processCallback(SocialProviderConfig config, AuthCallback callback)
        throws SocialProviderException {
    if (callback.getQueryParam("denied") != null) {
        throw new SocialAccessDeniedException();
    }//  w w  w.j a va  2 s.  c o m

    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(config.getKey(), config.getSecret());

        String token = callback.getQueryParam("oauth_token");
        String verifier = callback.getQueryParam("oauth_verifier");

        RequestToken requestToken = new RequestToken((String) callback.getAttribute("token"),
                (String) callback.getAttribute("tokenSecret"));

        twitter.getOAuthAccessToken(requestToken, verifier);
        twitter4j.User twitterUser = twitter.verifyCredentials();

        SocialUser user = new SocialUser(Long.toString(twitterUser.getId()), twitterUser.getScreenName());
        user.setName(twitterUser.getName());

        return user;
    } catch (Exception e) {
        throw new SocialProviderException(e);
    }
}

From source file:org.luwrain.app.twitter.Auth.java

License:Open Source License

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("You must provide consumer key and consumer secret");
        return;//w  w  w. j a v a2s  .  c  o m
    }
    Twitter twitter = null;
    try {
        ConfigurationLuwrain conf = new ConfigurationLuwrain(args[0], args[1], null, null);
        twitter = new TwitterFactory(conf).getInstance();
        final RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        AccessToken accessToken = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (accessToken == null) {
            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 available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
            try {
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                }
            } catch (TwitterException te) {
                if (te.getStatusCode() == 401) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        } //while();
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());
    } catch (IllegalStateException e) {
        if (!twitter.getAuthorization().isEnabled())
            System.out.println("OAuth consumer key/secret is not set.");
        else
            e.printStackTrace();
    } catch (TwitterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.n52.twitter.TwitterAccessTokenRetriever.java

License:Open Source License

public static void main(String args[]) throws Exception {
    String[] props = readProperties();
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(props[0], props[1]);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//from  ww  w.ja  v  a  2s  .  co  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();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                LOGGER.error("Unable to get the access token.");
            } else {
                LOGGER.error(te.getErrorMessage(), te);
            }
        }
    }
    storeAccessToken(accessToken.getToken(), accessToken.getTokenSecret());
}

From source file:org.orcid.core.manager.impl.OrcidSocialManagerImpl.java

License:Open Source License

/**
 * Get the twitter AccessToken// w  w  w.  j av  a 2  s. c  o m
 * 
 * @return The twitter AccessToken
 * */
private AccessToken getOAuthAccessToken(String orcid, String pin) throws Exception {
    RequestToken requestToken = getTwitterRequestToken(orcid);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(twitterKey, twitterSecret);
    return twitter.getOAuthAccessToken(requestToken, pin);
}

From source file:org.osframework.maven.plugins.twitter.AbstractTwitterMojo.java

License:Apache License

protected void loadAccessToken(final Twitter twitter) throws TwitterException {
    // Check for stored access token
    File tokenStore = new File(getWorkDirectory(), "auth");
    if (tokenStore.canRead()) {
        Properties p = new Properties();
        InputStream in = null;/*from w  ww  .  j  av  a 2 s  .  c  o m*/
        try {
            in = new FileInputStream(tokenStore);
            p.load(in);
        } catch (IOException ignore) {
        } finally {
            IOUtil.close(in);
        }
        authToken = new AccessToken(p.getProperty(OAUTH_ACCESS_TOKEN),
                p.getProperty(OAUTH_ACCESS_TOKEN_SECRET));
    }
    // Get access token via user authorization
    else {
        RequestToken requestToken = twitter.getOAuthRequestToken();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == authToken) {
            getLog().info("Open the following URL and grant access to your account:");
            getLog().info(requestToken.getAuthorizationURL());
            System.out.print("Enter the PIN (if available) or just hit enter. [PIN]: ");
            try {
                String pin = br.readLine();
                authToken = (0 < pin.length()) ? twitter.getOAuthAccessToken(requestToken, pin)
                        : twitter.getOAuthAccessToken();
            } catch (IOException ioe) {
                getLog().error("Could not read authorization PIN from input");
                throw new TwitterException(ioe);
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    getLog().error("Could not acquire access token");
                }
                throw te;
            }
        }
    }
}

From source file:org.picketlink.extensions.core.social.twitter.TwitterAuthenticationMechanism.java

License:Open Source License

@Override
protected Principal doAuthenticate(UserCredential credential, AuthenticationResult result)
        throws AuthenticationException {
    TwitterCredential oAuthCredential = (TwitterCredential) credential;

    HttpServletRequest request = oAuthCredential.getRequest();
    HttpServletResponse response = oAuthCredential.getResponse();
    HttpSession session = request.getSession();

    Principal principal = null;/*from  ww w.  j  a  v  a  2  s.  c  o m*/
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(clientID, clientSecret);

    //See if we are a callback
    RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    if (requestToken != null) {
        String verifier = request.getParameter("oauth_verifier");
        try {
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            session.setAttribute("accessToken", accessToken);
            session.removeAttribute("requestToken");
        } catch (TwitterException e) {
            throw new AuthenticationException(e);
        }

        try {
            principal = new TwitterPrincipal(twitter.verifyCredentials());
            checkUserInStore((TwitterPrincipal) principal);
        } catch (TwitterException e) {
            throw new AuthenticationException(e);
        }
        return principal;
    }
    try {
        requestToken = twitter.getOAuthRequestToken(returnURL);
        session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (Exception e) {
        throw new AuthenticationException(e);
    }
    return principal;
}