List of usage examples for twitter4j.auth RequestToken getAuthorizationURL
public String getAuthorizationURL()
From source file:org.openhab.action.twitter.internal.TwitterActionService.java
License:Open Source License
private static AccessToken getAccessToken() { try {/*from w w w . j av a 2 s. c om*/ String accessToken = loadToken(getTokenFile(), "accesstoken"); String accessTokenSecret = loadToken(getTokenFile(), "accesstokensecret"); if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(accessTokenSecret)) { File pinFile = new File("twitter.pin"); RequestToken requestToken = Twitter.client.getOAuthRequestToken(); // no access token/secret specified so display the authorisation URL in the log logger.info( "################################################################################################"); logger.info("# Twitter-Integration: U S E R I N T E R A C T I O N R E Q U I R E D !!"); logger.info("# 1. Open URL '{}'", requestToken.getAuthorizationURL()); logger.info("# 2. Grant openHAB access to your Twitter account"); logger.info("# 3. Create an empty file 'twitter.pin' in your openHAB home directory at " + pinFile.getAbsolutePath()); logger.info("# 4. Add the line 'pin=<authpin>' to the twitter.pin file"); logger.info( "# 5. openHAB will automatically detect the file and complete the authentication process"); logger.info("# NOTE: You will only have 5 mins before openHAB gives up waiting for the pin!!!"); logger.info( "################################################################################################"); String authPin = null; int interval = 5000; int waitedFor = 0; while (StringUtils.isEmpty(authPin)) { try { Thread.sleep(interval); waitedFor += interval; // attempt to read the authentication pin from them temp file } catch (InterruptedException e) { // ignore } authPin = loadToken(pinFile, "pin"); // if we already waited for more than five minutes then stop if (waitedFor > 300000) { logger.info("Took too long to enter your Twitter authorisation pin! Please use OSGi " + "console to restart the org.openhab.io.net-Bundle and re-initiate the authorization process!"); break; } } // if no pin was detected after 5 mins then we can't continue if (StringUtils.isEmpty(authPin)) { logger.warn("Timed out waiting for the Twitter authorisation pin."); return null; } // attempt to get an access token using the user-entered pin AccessToken token = Twitter.client.getOAuthAccessToken(requestToken, authPin); accessToken = token.getToken(); accessTokenSecret = token.getTokenSecret(); // save the access token details saveToken(getTokenFile(), "accesstoken", accessToken); saveToken(getTokenFile(), "accesstokensecret", accessTokenSecret); } // generate an access token from the token details return new AccessToken(accessToken, accessTokenSecret); } catch (Exception e) { logger.error("Failed to authenticate openHAB against Twitter", e); return null; } }
From source file:org.orcid.core.manager.impl.OrcidSocialManagerImpl.java
License:Open Source License
/** * Return the URL where the user should authorize access * // w w w . ja v a 2 s . co m * @param orcid * the user orcid * @return the twitter URL where the user should authorize access * */ public String getTwitterAuthorizationUrl(String orcid) throws Exception { RequestToken token = getTwitterRequestToken(orcid); return token.getAuthorizationURL(); }
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 ww w . ja va2 s.co 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.rhq.enterprise.server.plugins.alertMicroblog.MicroblogServerPluginComponent.java
License:Open Source License
private String getAuthorizationURL() throws TwitterException { RequestToken requestToken = twitter.getOAuthRequestToken(); log.info("Open the following URL and grant access to your account: " + requestToken.getAuthorizationURL()); return requestToken.getAuthorizationURL(); }
From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java
License:Open Source License
/** * Starts a command line authentication with yammer to get the needed access * token./*from w ww. j a v a 2 s. c om*/ */ private void startCommandLineAuthentication() { if (!source.isPropertyTrue(TwitterProperties.ALLOW_COMMAND_LINE_AUTHENTICATION)) { return; } // get property values from configuration String consumerKey = source.getPropertyValue(TwitterProperties.CONSUMER_KEY_PROPERTY); String consumerSecret = source.getPropertyValue(TwitterProperties.CONSUMER_SECRET_PROPERTY); // check properties if (consumerKey == null || consumerKey.isEmpty()) { log("A valid consumer key is needed in the configuration specified by " + TwitterProperties.CONSUMER_KEY_PROPERTY, LogService.LOG_WARNING); return; } else if (consumerSecret == null || consumerSecret.isEmpty()) { log("A valid consumer secret is needed in the configuration specified by " + TwitterProperties.CONSUMER_SECRET_PROPERTY, LogService.LOG_WARNING); return; } log("Starting command line authentication.", LogService.LOG_INFO); // Access Token not contained in properties Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken; // create new request token try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { log("Unable to get request token from Twitter. Please check your Consumer Key and Secret.", LogService.LOG_ERROR); return; } System.out.println("Request token: " + requestToken.getToken()); System.out.println("Token secret: " + requestToken.getTokenSecret()); String authorizationURL = requestToken.getAuthorizationURL(); // wait for user confirming the request System.out.println("Now visit:\n" + authorizationURL + "\n... and grant this app authorization"); System.out.println("Enter the PIN code and hit ENTER when you're done:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String pin; try { pin = br.readLine(); } catch (IOException e) { e.printStackTrace(); return; } AccessToken accessToken = null; try { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } catch (Exception e) { accessToken = null; } if (accessToken == null) { log("Got no Twitter OAuth Access Token for given Request and Pin!", LogService.LOG_ERROR); return; } System.out.println("Access token: " + accessToken.getToken()); System.out.println("Token secret: " + accessToken.getTokenSecret()); }
From source file:org.sush.twitterstream.MyTwitterStream.java
License:Apache License
private AccessToken getAccessToken() throws TwitterException, URISyntaxException, IOException { Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance(); RequestToken requestToken = twitter.getOAuthRequestToken(); Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken); return accessToken; }
From source file:org.twitter.oauth.java
public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer("SjLUa1Pwrs81nIAGiR4f1l4I7", "ISAXBmzqzYLKWQXAaOe09j34APvVOyxahHghLBSvvR0Psnhozl"); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from w ww . j a va2s. c om*/ 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(); } } } //persist to the accessToken for future reference. storeAccessToken((int) twitter.verifyCredentials().getId(), accessToken); Status status = twitter.updateStatus(args[0]); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); }
From source file:org.yamaLab.TwitterConnector.GetAccessToken.java
License:Apache License
/** * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret] * * @param args message *///from w ww .j a v a 2 s . c o m public static void main(String[] args) { File file = new File("TweetByWikiEx2.properties"); Properties prop = new Properties(); InputStream is = null; OutputStream os = null; try { /* try-0 */ 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.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) { /* try-0 */ ioe.printStackTrace(); System.exit(-1); } finally { /* try-0 */ if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (os != null) { try { os.close(); } catch (IOException ignore) { } } try { /* try-1 in try-0 */ 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) { /* while */ System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); try { /* try-1 */ Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); } catch (UnsupportedOperationException ignore) { } catch (IOException ignore) { } catch (URISyntaxException e) { throw new AssertionError(e); } /* try-1 */ System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { /* try-3 in try-0 */ 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(); } } /* try-3 in try-0 */ } /* while */ System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); try { /* try-2 in try 0 */ 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); } /* try-1 in try-0 */ } /* try-0 */ }
From source file:org.yukung.following2ldr.command.impl.FindFeedUrlCommand.java
License:Apache License
@Override public void run() throws Throwable { // Twitter??// w w w. j a va 2 s .com long start = System.currentTimeMillis(); String consumerKey = config.getProperty(Constants.CONSUMER_KEY); String consumerSecret = config.getProperty(Constants.CONSUMER_SECRET); String userName = params.get(0); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken = twitter.getOAuthRequestToken(); String authorizationURL = requestToken.getAuthorizationURL(); System.out.println(":" + authorizationURL); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the PIN:"); String pin = br.readLine(); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin); twitter.setOAuthAccessToken(accessToken); long cursor = -1L; IDs friendIDs; List<Long> iDsList = new ArrayList<Long>(5000); do { friendIDs = twitter.getFriendsIDs(userName, cursor); long[] iDs = friendIDs.getIDs(); for (long iD : iDs) { iDsList.add(iD); } cursor = friendIDs.getNextCursor(); } while (friendIDs.hasNext()); List<long[]> list = new ArrayList<long[]>(); int offset = 0; long[] tmp = new long[100]; for (Long id : iDsList) { if (offset < 100) { tmp[offset] = id; offset++; } else { list.add(tmp); offset = 0; tmp = new long[100]; } } list.add(tmp); List<URL> urlList = new ArrayList<URL>(); for (long[] array : list) { ResponseList<User> lookupUsers = twitter.lookupUsers(array); for (User user : lookupUsers) { log.info("URL:" + user.getURL()); urlList.add(user.getURL()); } } String path = "C:\\Users\\ikeda_yusuke\\Documents\\sandbox\\java\\data\\" + userName + ".txt"; FileWriter writer = new FileWriter(path); BufferedWriter out = new BufferedWriter(writer); // PrintWriter pw = new PrintWriter(writer); for (URL url : urlList) { if (url != null) { out.write(url.toString() + "\n"); } } out.flush(); out.close(); long end = System.currentTimeMillis(); log.info("?:" + (end - start) + " ms"); // ??IDor?? // Twitter API??????ID? // ?????ID?URL100??? // ??URL? }
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;//from w w w.jav a 2 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); }