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:com.mothsoft.integration.twitter.TwitterServiceImpl.java

License:Apache License

public AccessToken getAccessToken(final RequestToken requestToken, final String verificationCode) {
    final Twitter twitter = factory.getInstance();
    try {/*  ww w.  j  a v  a 2 s .co m*/
        return twitter.getOAuthAccessToken(requestToken, verificationCode);
    } catch (TwitterException e) {
        throw this.wrapException(e);
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww  w.j av  a2  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 {
    response.setContentType("text/html;charset=UTF-8");

    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    System.out.println("TwitterCallbackServlet:requestToken:" + requestToken);
    String verifier = request.getParameter("oauth_verifier");

    try {
        twitter.getOAuthAccessToken(requestToken, verifier);
        request.getSession().removeAttribute("requestToken");
    } catch (Exception e) {
        throw new ServletException(e);
    }

    response.sendRedirect("search.jsp");
}

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

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from w  ww .  j  ava 2 s  .c o  m
 * @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 = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    try {
        twitter.getOAuthAccessToken(requestToken, verifier);
    } catch (TwitterException ex) {
        Logger.getLogger(CallbackServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    request.getSession().removeAttribute("requestToken");
    response.sendRedirect(request.getContextPath() + "/");
    processRequest(request, response);
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w w. ja v  a2  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 {
    response.setContentType("text/html;charset=UTF-8");

    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    System.out.println("TwitterCallbackServlet:requestToken:" + requestToken);
    String verifier = request.getParameter("oauth_verifier");

    try {
        twitter.getOAuthAccessToken(requestToken, verifier);
        request.getSession().removeAttribute("requestToken");
    } catch (Exception e) {
        throw new ServletException(e);
    }
    response.sendRedirect("welcome.jsp");
}

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

@Override
public void verificarLogin(HttpServletRequest request) throws TwitterException {
    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");

    twitter.getOAuthAccessToken(requestToken, verifier);
    request.getSession().removeAttribute("requestToken");
}

From source file:com.puestodequipe.mvc.testing.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/* w  ww  .j  a  va2s. c o m*/
 */
public static void main(String[] args) {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        prop.setProperty("oauth.consumerKey", "mOpD2GQXUsc0tMKZHOvGJg");
        prop.setProperty("oauth.consumerSecret", "LnGRxSHrlzHDWC3R9aeTPDYmlr7LGXm7diNi6WZX3k");
        os = new FileOutputStream("twitter4j.properties");
        prop.store(os, "twitter4j.properties");

    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        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 (null == accessToken) {
            System.out.println("Open the following URL and grant access to your account:");
            System.out.println(requestToken.getAuthorizationURL());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            }
            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 (401 == te.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());

        try {
            prop.setProperty("oauth.accessToken", accessToken.getToken());
            prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, "twitter4j.properties");
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.exit(-1);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get accessToken: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

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 ava 2 s .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();
            }

            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.rhymestore.twitter.AccessTokenGenerator.java

License:Open Source License

/**
 * Interactive {@link AccessToken} generation.
 * // ww  w  .j  a va  2  s . co  m
 * @param args No args are required.
 * @throws Exception If the token cannot be generated.
 */
public static void main(final String... args) throws Exception {
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken requestToken = twitter.getOAuthRequestToken();

    // Ask for the PIN
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    AccessToken accessToken = null;

    System.out.print("Open the following URL and grant access to your account: ");
    System.out.println(requestToken.getAuthorizationURL());
    System.out.print("Enter the PIN: ");

    accessToken = twitter.getOAuthAccessToken(requestToken, br.readLine());

    System.out.println("AccessToken Key: " + accessToken.getToken());
    System.out.println("AccessToken Secret: " + accessToken.getTokenSecret());
}

From source file:com.stronquens.amgtwitter.ControllerOAuth.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww  w  .  j  av a2s .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, TwitterException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Parametros del request
        HttpSession sesion = request.getSession();
        String verifier = request.getParameter("verifier");
        String op = request.getParameter("op");

        // Definimos variables
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        Twitter OAuthTwitter = null;
        String url = null;

        // Devolemos la url generada          
        if ((verifier == null || verifier == "") && "url".equalsIgnoreCase(op)) {
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                    .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
            OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
            sesion.setAttribute("twitter", OAuthTwitter);
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                sesion.setAttribute("requestToken", requestToken);
                url = requestToken.getAuthenticationURL();
                out.println("{\"url\":\"" + url + "\"}");
            } catch (TwitterException ex) {
            }
        }

        // Devolvemos el acces token generado
        if (verifier != null && verifier.length() > 0) {
            OAuthTwitter = (Twitter) sesion.getAttribute("twitter");
            requestToken = (RequestToken) sesion.getAttribute("requestToken");
            accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, verifier);
            sesion.setAttribute("accesToken", accessToken);
            sesion.removeAttribute("twitter");
            sesion.removeAttribute("requestToken");
            out.println("{\"token\":\"" + accessToken.getToken() + "\",\"secret\":\""
                    + accessToken.getTokenSecret() + "\"}");
        }

    }
}

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;/*from   ww  w  .j av  a2  s. co  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);
}