List of usage examples for twitter4j Twitter getOAuthAccessToken
AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;
From source file:se.aceone.housenews.UpdateStatus.java
License:Apache License
private static void handleAccessToken(Twitter twitter) throws IOException, FileNotFoundException, ClassNotFoundException, TwitterException, URISyntaxException { AccessToken accessToken = null;// w w w.j a v a2 s. c om File settingsDir = new File(System.getenv("HOMEPATH"), ".housenews"); File accessTokenFile = new File(settingsDir, "accessToken"); if (settingsDir.isDirectory() && accessTokenFile.isFile()) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(accessTokenFile)); accessToken = (AccessToken) ois.readObject(); ois.close(); } else { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Open the following URL and grant access to your account:"); 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()); String authorizationURL = requestToken.getAuthorizationURL(); System.out.println(authorizationURL); java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) { System.err.println("Desktop doesn't support the browse action (fatal)"); System.exit(1); } URI uri = new URI(authorizationURL); desktop.browse(uri); System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } if (!settingsDir.isDirectory()) { settingsDir.mkdirs(); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(accessTokenFile)); oos.writeObject(accessToken); oos.close(); } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); twitter.setOAuthAccessToken(accessToken); }
From source file:Servlet.CallbackServlet.java
License:Apache License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request//from ww w .j a va2s.co m * @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"); String verifier = request.getParameter("oauth_verifier"); try { twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute("requestToken"); String twitterIDString = Long.toString(twitter.getId()); twitter4j.User user = twitter.showUser(twitter.getId()); Model.User loggedUser = DBAdmin.getTwitterUser(twitterIDString); if (loggedUser == null) { String username = user.getName().replaceAll(" ", ""); if (DBAdmin.isUsernameTaken(username)) { int i = 1; while (DBAdmin.isUsernameTaken(username + i)) { i++; } username += i; } DBAdmin.registerTwitter(twitterIDString, username, "null", "", "player", user.getName(), "unaffliated"); DirectoryAdmin.prepNewUserDirectory(request, username); loggedUser = DBAdmin.getTwitterUser(twitterIDString); } request.getSession().setAttribute("loggedUser", loggedUser); } catch (IllegalStateException | TwitterException ex) { throw new ServletException(ex); } response.sendRedirect("main"); }
From source file:spammerwadgets.AutoOAuthAccess.java
License:Apache License
public static void main(String[] args) { File file = new File(fileName); Properties prop = new Properties(); InputStream is = null;// w w w . ja v a2s . c o m OutputStream os = null; prop.setProperty("oauth.consumerKey", "E7uuluwC0ZsAFbV9pHimQ"); prop.setProperty("oauth.consumerSecret", "c7amwRvOgb4icJArTRfgU8m2G64mbpVioqgmPDT4Yg"); prop.setProperty("username", "AdrienneccDusti"); prop.setProperty("password", "SIRENSSUBROUTINE"); try { if (file.exists()) { is = new FileInputStream(file); prop.load(is); } if (args.length < 4) { if (null == prop.getProperty("oauth.consumerKey") && null == prop.getProperty("oauth.consumerSecret") && null == prop.getProperty("username") && null == prop.getProperty("password")) { // consumer key/secret are not set in twitter4j.properties System.out.println( "Usage: java twitter4j.examples.oauth.AutoOAuthAccess [consumer key] [consumer secret][username] [password]"); System.exit(-1); } } else { prop.setProperty("oauth.consumerKey", args[0]); prop.setProperty("oauth.consumerSecret", args[1]); prop.setProperty("username", args[2]); prop.setProperty("password", args[3]); os = new FileOutputStream(fileName); prop.store(os, fileName); } } catch (IOException ioe) { ioe.printStackTrace(); System.exit(-1); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (os != null) { 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; while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); String url = requestToken.getAuthorizationURL(); System.out.println(url); /* BufferedReader urlbr = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String strTemp = ""; while(null != (strTemp = urlbr.readLine())){ System.out.println(strTemp); } 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(); */ // Alternatively, we will generate the POST request automatically // Firstly, we parse the webpage of the authotizationURL Document doc = Jsoup.connect(url).get(); Element form = doc.getElementById("oauth_form"); System.out.println(form.toString()); String action = form.attr("action"); String authenticity_token = form.select("input[name=authenticity_token]").attr("value"); String oauth_token = form.select("input[name=oauth_token]").attr("value"); // Then submit the authentication webpage Document doc2 = Jsoup.connect(action).data("authenticity_token", authenticity_token) .data("oauth_token", oauth_token) .data("session[username_or_email]", prop.getProperty("username")) .data("session[password]", prop.getProperty("password")).post(); System.out.println(doc2.toString()); Element oauth_pin = doc2.getElementsByTag("code").first(); String pin = oauth_pin.text(); 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, fileName); os.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(-1); } finally { if (os != null) { 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:spammerwadgets.AutoOAuthAccessFromFile.java
License:Apache License
AccessToken getAccessToken(String username, String password) throws TwitterException, IOException { AccessToken accessToken = null;// w w w. ja v a 2 s . com //ConfigurationBuilder cb = new ConfigurationBuilder(); //cb.setUseSSL(true); 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()); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); String url = requestToken.getAuthorizationURL(); System.out.println(url); // Alternatively, we will generate the POST request automatically // Firstly, we parse the webpage of the authotizationURL Document authDoc = Jsoup.connect(url).get(); Element form = authDoc.getElementById("oauth_form"); System.out.println(form.toString()); String action = form.attr("action"); String authenticity_token = form.select("input[name=authenticity_token]").attr("value"); String oauth_token = form.select("input[name=oauth_token]").attr("value"); // Then submit the authentication webpage Document tokenDoc = Jsoup.connect(action).data("authenticity_token", authenticity_token) .data("oauth_token", oauth_token).data("session[username_or_email]", username) .data("session[password]", password).post(); // System.out.println(doc2.toString()); Element oauth_pin = tokenDoc.getElementsByTag("code").first(); if (oauth_pin == null) { System.out.println("Something wrong!!!!!!!"); return null; } String pin = oauth_pin.text(); 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("Username: " + username); System.out.println("Password: " + password); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); return accessToken; }
From source file:tkwatch.GetAccessTokens.java
License:Open Source License
public static void main(String args[]) throws Exception { // The factory instance is re-usable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); // Assumes consumer key and consumer secret are already stored in // properties file. // twitter.setOAuthConsumer(Constants.CONSUMER_KEY, // Constants.CONSUMER_SECRET); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from ww w. jav a2 s .c o 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(); } } } // Print out the access tokens for future reference. System.out.println("Access tokens for " + twitter.verifyCredentials().getId()); System.out.println("oauth.accessToken=" + accessToken.getToken()); System.out.println("oauth.accessTokenSecret=" + accessToken.getTokenSecret()); }
From source file:tkwatch.Utilities.java
License:Open Source License
/** * The Twitter OAuth authorization process requires access tokens. Twitter4j * stores them in <code>twitter4j.properties</code>. Invoke this routine to * obtain them; then add the appropriate lines in the properties file. (You * will need to write your own <code>main()</code> to do this. This routine * isn't actually called from the <strong>TKWatch+</strong> routine. * Documentation for <code>twitter4j.properties</code> is available <a * href="http://twitter4j.org/en/configuration.html">here</a>. * <p>/*w w w . j a v a 2s . c o m*/ * Adapted from Yusuke Yamamoto, <a * href="http://twitter4j.org/en/code-examples.html">OAuth support</a>, * April 18, 2011. */ @SuppressWarnings("null") public static final void getAccessTokens() { // The factory instance is re-usable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); // Assumes consumer key and consumer secret are already stored in // properties file. // twitter.setOAuthConsumer(Constants.CONSUMER_KEY, // Constants.CONSUMER_SECRET); RequestToken requestToken = null; try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e1) { e1.printStackTrace(); } 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()); System.out.print("Cut and paste the pin:"); String pin = ""; try { pin = br.readLine(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } 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(); } } } // Print out the access tokens for future reference. The ones we got are // in the // <code>twitter4j.properties</code> file. try { System.out.println("Access tokens for " + twitter.verifyCredentials().getId()); } catch (TwitterException e) { System.out.println(e.getMessage()); e.printStackTrace(); } System.out.println("Store in twitter4j.properties as oauth.accessToken=" + accessToken.getToken()); System.out.println( "Store in twitter4j.properties as oauth.accessTokenSecret=" + accessToken.getTokenSecret()); }
From source file:twitter.sample.GetAccessToken.java
License:Apache License
/** * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret] * * @param args message//from ww w . ja v a 2 s. com */ 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); } if (args.length < 2) { if (null == prop.getProperty("oauth.consumerKey") && null == prop.getProperty("oauth.consumerSecret")) { // consumer key/secret are not set in twitter4j-bak.properties System.out.println( "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]"); System.exit(-1); } } else { prop.setProperty("oauth.consumerKey", args[0]); prop.setProperty("oauth.consumerSecret", args[1]); os = new FileOutputStream("twitter4j.properties"); prop.store(os, "twitter4j.properties"); } } catch (IOException ioe) { ioe.printStackTrace(); System.exit(-1); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (os != null) { 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 (UnsupportedOperationException ignore) { } 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 (os != null) { 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:twitter.UpdateStatus.java
License:Apache License
public boolean execute(String statusMessage) throws IOException { try {//w w w . j a v a2 s . c om Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); LOG.info("Got request token."); LOG.info("Request token: " + requestToken.getToken()); LOG.info("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; while (null == accessToken) { try { URI uri = new URI(requestToken.getAuthorizationURL()); Desktop.getDesktop().browse(uri); } catch (IOException e) { LOG.error(e); } catch (URISyntaxException e) { LOG.error(e); } JFrame frame = new JFrame("Twitter PIN verification"); // prompt the user to enter their name String pin = JOptionPane.showInputDialog(frame, "Enter the PIN"); if (pin == null) return false; try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { LOG.error("Unable to get the access token."); } else { LOG.error(te); } } } LOG.info("Got access token."); LOG.info("Access token: " + accessToken.getToken()); LOG.info("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { return false; } } twitter.updateStatus(statusMessage); } catch (TwitterException te) { LOG.error(te); return false; } return true; }
From source file:twitterplugin.TwitterLoginDialog.java
License:Open Source License
/** * Create Gui/*from w w w . ja v a 2s .c o m*/ */ private void createGui() { setTitle(mLocalizer.msg("login", "Login")); UiUtilities.registerForClosing(this); PanelBuilder content = new PanelBuilder( new FormLayout("5dlu, pref:grow(0.5), 3dlu, 100dlu, fill:pref:grow(0.5), 5dlu")); CellConstraints cc = new CellConstraints(); final Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret()); try { mRequestToken = twitter.getOAuthRequestToken(); mAuthorizationUrl = mRequestToken.getAuthorizationURL(); } catch (TwitterException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } content.appendRow("3dlu"); content.appendRow("pref"); mLabelBrowser = new JLabel("1. " + mLocalizer.msg("step1", "Open authentication page on Twitter")); content.add(mLabelBrowser, cc.xy(2, content.getRowCount())); mUrlButton = new JButton(mLocalizer.msg("openBrowser", "Open browser")); mUrlButton.setToolTipText(mAuthorizationUrl); content.add(mUrlButton, cc.xy(4, content.getRowCount())); mUrlButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Launch.openURL(mAuthorizationUrl); } }); content.appendRow("3dlu"); content.appendRow("pref"); mLabelPin = new JLabel("2. " + mLocalizer.msg("step2", "Enter PIN from web page")); content.add(mLabelPin, cc.xy(2, content.getRowCount())); mPIN = new JTextField(); content.add(mPIN, cc.xy(4, content.getRowCount())); ButtonBarBuilder builder = new ButtonBarBuilder(); builder.addGlue(); JButton ok = new JButton(Localizer.getLocalization(Localizer.I18N_OK)); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mReturnValue = JOptionPane.OK_OPTION; AccessToken accessToken = null; try { String pin = mPIN.getText().trim(); if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(mRequestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } try { twitter.verifyCredentials().getId(); mSettings.setAccessToken(accessToken); } catch (TwitterException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } setVisible(false); } }); getRootPane().setDefaultButton(ok); JButton cancel = new JButton(Localizer.getLocalization(Localizer.I18N_CANCEL)); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); builder.addGriddedButtons(new JButton[] { ok, cancel }); content.appendRow("fill:pref:grow"); content.appendRow("pref"); content.add(builder.getPanel(), cc.xyw(1, content.getRowCount(), 4)); content.appendRow("5dlu"); content.setBorder(Borders.DIALOG_BORDER); getContentPane().add(content.getPanel()); UiUtilities.setSize(this, Sizes.dialogUnitXAsPixel(200, this), Sizes.dialogUnitYAsPixel(140, this)); }
From source file:ua.group06.presentation.UserLoginTwitter.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request/*from w ww . jav a2 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 = twitterauth.getTwitter(); RequestToken requestToken = twitterauth.getRequestToken(); //RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); System.err.println(twitter + " " + requestToken + " " + verifier); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); System.err.println(accessToken.getScreenName()); User twitterUser = twitter.showUser(accessToken.getUserId()); String fullName = twitterUser.getName(); String fName = ""; String lName = ""; String[] names = fullName.split(" "); if (names.length == 1) { fName = names[0]; } else if (names.length >= 2) { fName = names[0]; lName = names[names.length - 1]; } ExternalUser user = userService.authenticateOrCreate(accessToken.getScreenName(), "", fName, lName); if (user != null) { HttpSession session = request.getSession(); session.setAttribute("user", user); } //request.getSession().removeAttribute("requestToken"); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect("homepage"); }