List of usage examples for twitter4j.auth RequestToken getAuthorizationURL
public String getAuthorizationURL()
From source file:Servlet.TwitterAuthServlet.java
License:Apache License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*from w ww . java2s . 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"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(TwitterApp.CONSUMER_KEY); cb.setOAuthConsumerSecret(TwitterApp.CONSUMER_SECRET); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); request.getSession().setAttribute("twitter", twitter); try { StringBuffer callbackURL = request.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/callback"); System.out.println(callbackURL); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); System.out.println("Authentication " + requestToken.getAuthenticationURL()); System.out.println("Authorization " + requestToken.getAuthorizationURL()); request.getSession().setAttribute("requestToken", requestToken); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (TwitterException e) { throw new ServletException(e); } }
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 ww . j a v a2s .co 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 . j av a 2s. c om //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 . j av 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>/*from w ww.j ava2 s . 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/* www . j av a 2 s . 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); } 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 ww . j a v a2s. 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:twitteremoji.FXMLDocumentController.java
public void setup(Stage stage) { this.stage = stage; try {/*from ww w .j a v a 2s .co m*/ // start twitter auth process twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(key, secret); RequestToken requestToken = twitter.getOAuthRequestToken(); // check if we have a token for the user, if not authenticate and store in prefs if (!TokenPref.hasToken()) { System.out.println("has no prefs!"); Dialogs dialog = Dialogs.create().owner(null).title("Grant account access") .masthead("You must grant TwitterEmoji access to your account") .message( "You only have to do this once. Go to Twitter authorisation webpage (opens default browser)?") .actions(Dialog.Actions.NO, Dialog.Actions.YES); Action response = dialog.showConfirm(); if (response.textProperty().getValue().contains("No")) { Platform.exit(); return; } try { java.awt.Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); } catch (IOException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); Platform.exit(); return; } catch (URISyntaxException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); Platform.exit(); return; } // get pin Optional<String> responsePin = Dialogs.create().owner(stage).title("Authentication") .masthead("Authorise TwitterEmoji to get pin").message("Please enter pin:").showTextInput(); // One way to get the response value. String pin = null; if (responsePin.isPresent()) { pin = responsePin.get(); } AccessToken accessToken = null; if (pin == null) { accessToken = twitter.getOAuthAccessToken(); } else { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } // assume got, otherwise TwitterException thrown // store tokens TokenPref.putToken(accessToken.getToken()); TokenPref.putSecret(accessToken.getTokenSecret()); } else { System.out.println("has prefs!"); /* Dialogs dialog = Dialogs.create() .owner(null) .title("Information") .masthead("Application has Twitter token/secret") .message("Token: "+TokenPref.getToken()+"\nSecret: "+TokenPref.getSecret()); dialog.showInformation(); */ //Status status = twitter.updateStatus("testing api"); AccessToken accessToken = new AccessToken(TokenPref.getToken(), TokenPref.getSecret()); twitter.setOAuthAccessToken(accessToken); Dialogs dialog = Dialogs.create().owner(null).title("Information") .masthead("Twitter authentication").message("Connected to Twitter"); dialog.showInformation(); } } catch (TwitterException ex) { Dialogs.create().owner(null).title("Error").masthead(null) .message("Twitter authentication could not be completed").showError(); Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); Platform.exit(); return; } statusLabel.setText(STATUS_PREFIX + STATUS_CONNECTED); /* // add close behaviour to window to shut down twitter stage.setOnHiding(new EventHandler<WindowEvent>() { public void handle(WindowEvent event) { // TODO : check if this is triggered just by window minimisation // stop system System.out.println("--- Twitter client stopped"); } }); */ /* // add message reader (new Thread() { public void run() { // do what? } }).start(); */ }