List of usage examples for twitter4j.auth RequestToken getAuthorizationURL
public String getAuthorizationURL()
From source file:com.aldebaran.demo.picture.GetAccessToken.java
License:Apache License
/** * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret] * * @param args message/*from w ww . j av a 2 s . c om*/ */ 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.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:com.allenzheng.twittersyn.utility.impl.TwitterAPIImpl.java
License:Apache License
public String getAuthorisationUrl() throws TwitterException{ Properties prop = loadProperties(); //from ww w . jav a 2 s. c o m Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(prop.getProperty("twitter.consumerkey"), prop.getProperty("twitter.consumersecret")); try { RequestToken requestToken; if (callbackUrl == null) { requestToken = twitter.getOAuthRequestToken(); } else { requestToken = twitter .getOAuthRequestToken(callbackUrl); } String authorisationUrl = requestToken .getAuthorizationURL(); // session.setAttribute(ATTR_TWITTER, twitter); // session.setAttribute(ATTR_REQUEST_TOKEN, requestToken); logger.debug("Redirecting user to " + authorisationUrl); // response.sendRedirect(authorisationUrl); return authorisationUrl; } catch (TwitterException e) { logger.error("Sign in with Twitter failed - " + e.getMessage()); e.printStackTrace(); throw new TwitterException(e); } }
From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java
License:Open Source License
@Command(name = "twituser", desc = "Add your twitter account so you can tweet from IRC") @Usage(".twituser <twitter username>") public CommandResult twituser(CommandSource source, CommandContext context) { if (source.getSource() != CommandSource.Source.USER) { return get(ReturnType.MESSAGE, "Muse be done from IRC.", source, context); }//w w w.j a v a 2 s . c o m if (context.getPrefix() == null || !context.getPrefix().equals(".")) { return null; } if (context.getArgs() == null || context.getArgs().length < 1) { return get(ReturnType.MESSAGE, "Correct usage is .twituser <twitter username>", source, context); } String username = context.getArgs()[0]; CyborgUser permsAccount = getUser(source.getUser()); if (getUser(source.getUser()) == null) { return get(ReturnType.NOTICE, "You have not registered with me! You need to register to add a twitter account! Type .register for help!", source, context); } TwitterUser twitterUser = getDatabase().select(TwitterUser.class).where() .equal("permUser", permsAccount.getName()).execute().findOne(); if (twitterUser != null) { return get(ReturnType.NOTICE, "You already have an twitter user associated with your account!", source, context); } if (tokenMap.get(permsAccount.getName()) != null) { return get(ReturnType.NOTICE, "You already have twitter OAuth URL! Get your pin and type .twitpin <pin>", source, context); } Twitter twitter = defaultTwitterFactory.getInstance(); try { RequestToken token = twitter.getOAuthRequestToken(); tokenMap.put(permsAccount.getName(), token); StringBuilder body = new StringBuilder(); body.append("Here is your OAuth Auth URL: ").append(token.getAuthorizationURL()).append(lineBreak) .append("Go to it. Sign in to twitter and Authorize this Bot. After granting access, it will give you a pin.") .append(lineBreak).append("Execute this command to finish the registration: .twitpin <pin>"); return get(ReturnType.NOTICE, body.toString(), source, context); } catch (TwitterException e) { e.printStackTrace(); return get(ReturnType.MESSAGE, "Internal Twitter Exception httpcode:" + e.getStatusCode(), source, context); } }
From source file:com.amandine.twitterpostforcoucou.Tweet.java
private void publishStatusUpdateWithMedia(String message) throws MalformedURLException, IOException { Status status = null;// www. ja v a 2 s .c o m try { Twitter twitter = new TwitterFactory().getInstance(); try { RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; while (null == accessToken) { logger.fine("Open the following URL and grant access to your account:"); logger.fine(requestToken.getAuthorizationURL()); try { accessToken = twitter.getOAuthAccessToken(requestToken); } catch (TwitterException te) { if (401 == te.getStatusCode()) { logger.severe("Unable to get the access token."); } else { te.printStackTrace(); } } } logger.log(Level.INFO, "Got access token."); logger.log(Level.INFO, "Access token: {0}", accessToken.getToken()); logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { logger.severe("OAuth consumer key/secret is not set."); return; } } //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate(message); //attach any media, if you want to statusUpdate.setMedia( //title of media "Amandine Leforestier Spring Summer 2015 white", new URL("https://issuu.com/kadiemurphy/docs/volume_xxi_issuu/52?e=0").openStream()); //tweet or update status status = twitter.updateStatus(statusUpdate); //Status status = twitter.updateStatus(message); logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText()); } catch (TwitterException te) { te.printStackTrace(); logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage()); } }
From source file:com.amandine.twitterpostforcoucou.Tweet.java
public Twitter getTwitter() { Twitter twitter = new TwitterFactory().getInstance(); try {/*ww w. j a v a2 s . co m*/ RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; while (null == accessToken) { logger.fine("Open the following URL and grant access to your account:"); logger.fine(requestToken.getAuthorizationURL()); try { accessToken = twitter.getOAuthAccessToken(requestToken); } catch (TwitterException te) { if (401 == te.getStatusCode()) { logger.severe("Unable to get the access token."); } else { logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage()); } } } logger.log(Level.INFO, "Got access token."); logger.log(Level.INFO, "Access token: {0}", accessToken.getToken()); logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { logger.log(Level.SEVERE, "OAuth consumer key/secret is not set: {0}", ie.getMessage()); return null; } } catch (TwitterException te) { logger.log(Level.SEVERE, "OAuth request token: {0}", te.getMessage()); } return twitter; }
From source file:com.anshul.LoginServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try {//from w ww . ja va2 s. co m Twitter twitter = new TwitterFactory().getInstance(); try { twitter.setOAuthConsumer("dyHSJLTZhh2eSSw2RVpqMIKyJ", "jW22uPPA54DOMNicfFJWzf4jB7nKHbdi7L6VuPFlfWEPAOt5Ai"); } catch (IllegalStateException e) { e.printStackTrace(); } StringBuffer callbackURL = req.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/home"); RequestToken requestToken; requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); String token = requestToken.getToken(); String tokenSecret = requestToken.getTokenSecret(); HttpSession session = req.getSession(); session.setAttribute("twitter", twitter); String authUrl = requestToken.getAuthorizationURL(); // session.setAttribute("authUrl", authUrl); req.setAttribute("authUrl", authUrl); RequestDispatcher rd = req.getRequestDispatcher("index.jsp"); rd.forward(req, resp); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.appdynamics.alerts.twitter.TwitterAlert.java
License:Apache License
/** * Generate request URL and prompt user to grant access for this app. Then stores the access token on disk * * @throws TwitterException/* w w w. j ava 2 s . c o m*/ */ private static void getAuthorization() throws TwitterException { RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Follow this URL and grant this extension access to your Twitter account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.println("Enter PIN shown on page:"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); AccessToken accessToken; try { String pin = reader.readLine(); if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { System.out.println("No PIN entered"); accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException e) { logger.error("Failed to get access token", e); accessToken = twitter.getOAuthAccessToken(); } catch (IOException e) { logger.error("Cannot read PIN"); accessToken = twitter.getOAuthAccessToken(); } storeAccessToken(accessToken); }
From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java
License:Apache License
public static AccessToken getAccessToken(String username) { AccessToken accessToken = null;//from ww w . j a v a2 s . co m if (Prefs.get(username + "/accessToken").isEmpty()) { Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret")); RequestToken requestToken; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { requestToken = twitter.getOAuthRequestToken(); 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 ex) { if (401 == ex.getStatusCode()) { System.out.println("Unable to get the access token."); } else { logger.log(Level.SEVERE, "Unable to get the Access Token", ex); } } } } catch (IOException | TwitterException ex) { logger.log(Level.SEVERE, "Unable to get the Access Token", ex); } Prefs.put(username + "/accessToken", accessToken.getToken()); Prefs.put(username + "/accessTokenSecret", accessToken.getTokenSecret()); } logger.finest("Token&Secret: " + Prefs.get(username + "/accessToken") + " " + Prefs.get(username + "/accessTokenSecret")); logger.finest("OauthConsum&Secret: " + Prefs.get("OAuthConsumerKey") + " " + Prefs.get("consumerSecret")); accessToken = new AccessToken(Prefs.get(username + "/accessToken"), Prefs.get(username + "/accessTokenSecret")); return accessToken; }
From source file:com.freedomotic.plugins.devices.twitter.gateways.OAuthSetup.java
License:Open Source License
/** * @param args/* w ww . j a v a 2 s.co m*/ */ public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); //insert the appropriate consumer key and consumer secret here twitter.setOAuthConsumer("TLGtvoeABqf2tEG4itTUaw", "nUJPxYR1qJmhX9SnWTBT0MzO7dIqUtNyVPfhg10wf0"); RequestToken requestToken = twitter.getOAuthRequestToken(); 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("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. System.out.println(twitter.verifyCredentials().getId()); System.out.println("token : " + accessToken.getToken()); System.out.println("tokenSecret : " + accessToken.getTokenSecret()); //storeAccessToken(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:com.gmail.altakey.joanne.service.TwitterAuthService.java
License:Apache License
private void authenticate(final Twitter tw) { final AccessToken accessToken = getAccessToken(); if (accessToken == null) { try {//from w w w . j ava 2 s . com final RequestToken req = tw.getOAuthRequestToken(); final Intent intent = new Intent(this, AuthorizeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse(req.getAuthorizationURL())); startActivity(intent); } catch (TwitterException e) { Log.e(TAG, "authentication failure", e); } } else { Log.d(TAG, String.format("got access token: %s", accessToken.toString())); updateRelations(this, accessToken); final Intent intent = new Intent(ACTION_AUTH_SUCCESS); intent.putExtra(EXTRA_TOKEN, accessToken); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } }