List of usage examples for twitter4j Twitter getOAuthRequestToken
RequestToken getOAuthRequestToken() throws TwitterException;
From source file:com.stronquens.amgtwitter.ControllerOAuth.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w. j a va2 s . 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 w w w .j ava 2s . c o 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); }
From source file:com.twitter4rk.TwitterAuthFragment.java
License:Apache License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mTwitterWebView = new WebView(getActivity()); final Bundle args = getArguments(); if (args == null) { // This wont be case because startTwitterAuth() handles args for // fragment throw new IllegalArgumentException( "No arguments passed to fragment, Please use startTwitterAuth(...) method for showing this fragment"); }/*from w w w.ja v a 2 s . co m*/ // Get builder from args mBuilder = args.getParcelable(BUILDER_KEY); // Hide action bar if (mBuilder.hideActionBar) mBuilder.activity.getActionBar().hide(); // Init progress dialog mProgressDialog = new ProgressDialog(mBuilder.activity); mProgressDialog.setMessage(mBuilder.progressText == null ? "Loading ..." : mBuilder.progressText); if (mBuilder.isProgressEnabled) mProgressDialog.show(); // Init ConfigurationBuilder twitter4j final ConfigurationBuilder cb = new ConfigurationBuilder(); if (mBuilder.isDebugEnabled) cb.setDebugEnabled(true); cb.setOAuthConsumerKey(mBuilder.consumerKey); cb.setOAuthConsumerSecret(mBuilder.consumerSecret); // Web view client to handler url loading mTwitterWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // Get url first final Uri uri = Uri.parse(url); // Check if we need to see for callback URL if (mBuilder.callbackUrl != null && url.contains(mBuilder.callbackUrl)) { // Get req info String oauthToken = uri.getQueryParameter("oauth_token"); String oauthVerifier = uri.getQueryParameter("oauth_verifier"); if (mListener != null) mListener.onSuccess(oauthToken, oauthVerifier); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); mIsAuthenticated = true; removeMe(); return true; // If no callback URL then check for info directly } else if (uri.getQueryParameter("oauth_token") != null && uri.getQueryParameter("oauth_verifier") != null) { // Get req info String oauthToken = uri.getQueryParameter("oauth_token"); String oauthVerifier = uri.getQueryParameter("oauth_verifier"); if (mListener != null) mListener.onSuccess(oauthToken, oauthVerifier); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); mIsAuthenticated = true; removeMe(); return true; // If nothing then its failure } else { // Notify user if (mListener != null) mListener.onFailure( new Exception("Couldn't find the callback URL or oath parameters in response")); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); removeMe(); return false; } } }); // Web Crome client to handler progress dialog visibility mTwitterWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { if (mProgressDialog.isShowing()) mProgressDialog.dismiss(); } } }); final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final TwitterFactory twitterFactory = new TwitterFactory(cb.build()); final Twitter twitter = twitterFactory.getInstance(); RequestToken requestToken = null; if (mBuilder.callbackUrl == null) requestToken = twitter.getOAuthRequestToken(); else requestToken = twitter.getOAuthRequestToken(mBuilder.callbackUrl); final RequestToken finalRequestToken = requestToken; handler.post(new Runnable() { @Override public void run() { final String url = finalRequestToken.getAuthorizationURL(); mTwitterWebView.loadUrl(url); } }); } catch (TwitterException e) { e.printStackTrace(); } } }).start(); return mTwitterWebView; }
From source file:com.vuze.client.plugins.twitter.TwitterPlugin.java
License:Open Source License
public void initialize(PluginInterface _plugin_interface) { plugin_interface = _plugin_interface; String ac_str = plugin_interface.getPluginconfig().getPluginStringParameter("twitter.access.token", ""); String acs_str = plugin_interface.getPluginconfig().getPluginStringParameter("twitter.access.token.secret", "");//from www. j a v a2 s . co m if (ac_str.length() > 0 && acs_str.length() > 0) { access_token = new AccessToken(ac_str, acs_str); } ta_tweets = plugin_interface.getTorrentManager().getPluginAttribute("tweets"); final LocaleUtilities loc_utils = plugin_interface.getUtilities().getLocaleUtilities(); log = plugin_interface.getLogger().getChannel("Twitter"); UIManager ui_manager = plugin_interface.getUIManager(); config_model = ui_manager.createBasicPluginConfigModel("plugins", "twitter.name"); enable = config_model.addBooleanParameter2(CONFIG_ENABLE, "twitter.enable", CONFIG_ENABLE_DEFAULT); LabelParameter tweet_info = config_model.addLabelParameter2("twitter.tweet.info"); tweet_text = config_model.addStringParameter2(CONFIG_TWEET_ADDED, CONFIG_TWEET_ADDED, loc_utils.getLocalisedMessageText(CONFIG_TWEET_ADDED_DEFAULT)); ParameterGroup tweet_group = config_model.createGroup("twitter.tweet.group", new Parameter[] { tweet_info, tweet_text }); // twitter_user = config_model.addStringParameter2( CONFIG_TWITTER_USER, "twitter.user", "" ); // twitter_password = config_model.addPasswordParameter2( CONFIG_TWITTER_PASSWORD, "twitter.password", PasswordParameter.ET_PLAIN, new byte[0] ); LabelParameter oauth_info = config_model.addLabelParameter2("twitter.oauth.info"); final ActionParameter oauth_setup = config_model.addActionParameter2("twitter.oauth.start.label", "twitter.oauth.start.button"); final RequestToken[] request_token = { null }; final StringParameter oauth_pin = config_model.addStringParameter2("twitter.oauth.pin", "twitter.oauth.pin", ""); oauth_pin.setValue(""); final ActionParameter oauth_done = config_model.addActionParameter2("twitter.oauth.done.label", "twitter.oauth.done.button"); oauth_setup.addConfigParameterListener(new ConfigParameterListener() { public void configParameterChanged(ConfigParameter param) { oauth_setup.setEnabled(false); plugin_interface.getUtilities().createThread("Twitter Setup", new Runnable() { public void run() { Twitter twitter = new TwitterFactory().getInstance(); try { RequestToken requestToken = twitter.getOAuthRequestToken(); request_token[0] = requestToken; oauth_done.setEnabled(true); log.log("OAuth URL: " + requestToken.getAuthorizationURL()); plugin_interface.getUIManager().openURL(new URL(requestToken.getAuthorizationURL())); Thread.sleep(5000); } catch (Throwable e) { log.log("OAuth setup failed", e); plugin_interface.getUIManager().showMessageBox("twitter.oauth.error.title", "twitter.oauth.error.details", UIManagerEvent.MT_OK); } finally { oauth_setup.setEnabled(true); } } }); } }); oauth_done.addConfigParameterListener(new ConfigParameterListener() { public void configParameterChanged(ConfigParameter param) { plugin_interface.getUtilities().createThread("Twitter Setup", new Runnable() { public void run() { try { Twitter twitter = new TwitterFactory().getInstance(); AccessToken at = twitter.getOAuthAccessToken(request_token[0], oauth_pin.getValue()); access_token = at; String token = at.getToken(); String token_secret = at.getTokenSecret(); plugin_interface.getPluginconfig().setPluginParameter("twitter.access.token", token); plugin_interface.getPluginconfig().setPluginParameter("twitter.access.token.secret", token_secret); plugin_interface.getPluginconfig().save(); log.log("OAuth setup successful - token saved"); plugin_interface.getUIManager().showMessageBox("twitter.oauth.ok.title", "twitter.oauth.ok.details", UIManagerEvent.MT_OK); } catch (Throwable e) { log.log("OAuth setup failed", e); plugin_interface.getUIManager().showMessageBox("twitter.oauth.error.title", "twitter.oauth.error.details", UIManagerEvent.MT_OK); } } }); } }); oauth_done.setEnabled(false); ParameterGroup auth_group = config_model.createGroup("twitter.oauth.group", new Parameter[] { oauth_info, oauth_setup, oauth_pin, oauth_done }); ActionParameter action = config_model.addActionParameter2("twitter.tweet_test", "twitter.send"); action.addConfigParameterListener(new ConfigParameterListener() { public void configParameterChanged(ConfigParameter param) { plugin_interface.getUtilities().createThread("Twitter Test", new Runnable() { public void run() { Map<String, String> params = new HashMap<String, String>(); params.put("%t", "<test_torrent_name>"); params.put("%m", "<magnet_uri>"); TwitterResult result = sendTweet(params); if (result.isOK()) { plugin_interface.getUIManager().showMessageBox("twitter.testok.title", "twitter.testok.details", UIManagerEvent.MT_OK); } else { plugin_interface.getUIManager() .showMessageBox("twitter.testfail.title", "!" + loc_utils.getLocalisedMessageText("twitter.testfail.details", new String[] { result.getError() }) + "!", UIManagerEvent.MT_OK); } } }); } }); view_model = ui_manager.createBasicPluginViewModel(loc_utils.getLocalisedMessageText("twitter.name")); view_model.getActivity().setVisible(false); view_model.getProgress().setVisible(false); log.addListener(new LoggerChannelListener() { public void messageLogged(int type, String content) { view_model.getLogArea().appendText(content + "\n"); } public void messageLogged(String str, Throwable error) { view_model.getLogArea().appendText(str + "\n"); view_model.getLogArea().appendText(error.toString() + "\n"); } }); view_model.getStatus().setText(enable.getValue() ? "Enabled" : "Disabled"); enable.addListener(new ParameterListener() { public void parameterChanged(Parameter p) { view_model.getStatus().setText(enable.getValue() ? "Enabled" : "Disabled"); checkEnabled(); } }); enable.addEnabledOnSelection(tweet_info); enable.addEnabledOnSelection(tweet_text); enable.addEnabledOnSelection(oauth_info); enable.addEnabledOnSelection(oauth_setup); enable.addEnabledOnSelection(oauth_pin); enable.addEnabledOnSelection(oauth_done); enable.addEnabledOnSelection(action); plugin_interface.getUIManager().addUIListener(new UIManagerListener() { public void UIAttached(UIInstance instance) { if (instance instanceof UISWTInstance) { checkEnabled(); } } public void UIDetached(UIInstance instance) { } }); timer = plugin_interface.getUtilities().createTimer("refresher"); timer_event = timer.addPeriodicEvent(60 * 1000, this); plugin_interface.getDownloadManager().addListener(this); }
From source file:de.dev.eth0.retweeter.TwitterAuthenticator.java
License:BEER-WARE LICENSE
public void authenticate() throws TwitterException, IOException { Twitter twitter = getTwitter(); twitter.setOAuthAccessToken(null);//from w ww. ja va2s.c o m AccessToken accessToken = null; RequestToken requestToken = twitter.getOAuthRequestToken(); 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) { logger.error("Couldnt get access token", te); } } System.out.println("Your accessToken: " + accessToken.getToken()); System.out.println("Your accessTokenSecret: " + accessToken.getTokenSecret()); System.out.println("add this to your config: "); System.out.println("\"accessToken\":\"" + accessToken.getToken() + "\","); System.out.println("\"accessSecret\":\"" + accessToken.getTokenSecret() + "\","); }
From source file:de.hikinggrass.eiwomisarc.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * // w w w. j a v a 2 s . c o m * @param args * message */ public UpdateStatus() { try { ConfigurationBuilder confBuilder = new ConfigurationBuilder(); //use https for oauth confBuilder.setUseSSL(true); Configuration conf = confBuilder.build(); Twitter twitter = new TwitterFactory(conf).getInstance(); twitter.setOAuthConsumer("HaBxuZMHygmtcuPeCbOLg", "zg6bV26ksBrgKHdhmiLlubTtV9MaDhoIRZC1ODUKw"); try { // get request token. // this will throw IllegalStateException if access token is already available 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()); 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()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus("test from eiwomisarc"); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + 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:ehealth.external.twitter.GetAccessToken.java
License:Apache License
/** * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret] * * @param args message/*from w w w .ja va2s.co m*/ */ protected void loginTwitter(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:generatetwittertokens.GenerateTwitterTokens.java
License:Open Source License
public static void main(String[] args) { String username = ""; ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(consumerKey); configurationBuilder.setOAuthConsumerSecret(consumerSecret); try {/*w w w.ja v a2 s . c o m*/ Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance(); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); while (accessToken == null) { System.out.println("PhantomBot Twitter API Connection Tool\r\n\r\n" + "This tool will request access to read and write to your Twitter account.\r\n" + "You will be presented with a URL to open in your local browser to approve\r\n" + "access, however, this application will attempt to launch a browser for\r\n" + "you automatically.\r\n\r\n" + "You will be presented with a PIN that you must provide back to this\r\n" + "application. After that is completed, Twitter will generate OAuth keys\r\n" + "which will be stored in the PhantomBot directory as twitter.txt.\r\n\r\n" + "Do keep this file safe! The keys are the same as a password to your Twitter\r\n" + "account!\r\n\r\n" + "You may regenerate the OAuth keys at any time if needed.\r\n"); System.out.println("Open the following URL in your browser if a browser does not automatically\r\n" + "launch within a few seconds:"); System.out.println(" " + requestToken.getAuthorizationURL() + "\r\n"); /* * Attempt to launch a local browser. Ignore exceptions, except if the URL is bad. */ try { Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); } catch (UnsupportedOperationException ignore) { } catch (IOException ignore) { } catch (URISyntaxException e) { throw new AssertionError(e); } /* * Request the username from the user. */ username = ""; while (username.length() < 1) { System.out.print("Provide your Twitter username: "); try { username = bufferedReader.readLine(); } catch (IOException ex) { username = ""; System.out.println("Failed to read input. Please try again."); } } /* * Request the PIN from the user. */ String pin = ""; while (pin.length() < 1) { System.out.print("Enter the PIN provided by Twitter: "); try { pin = bufferedReader.readLine(); accessToken = twitter.getOAuthAccessToken(requestToken, pin); } catch (TwitterException ex) { if (ex.getStatusCode() == 401) { pin = ""; System.out.println("Twitter failed to provide access tokens. Please try again."); } else { System.out.println("Twitter returned an error:\r\n" + ex.getMessage()); System.exit(1); } } catch (IOException ex) { pin = ""; System.out.println("Failed to read input. Please try again."); } } } System.out.println("Twitter has provided PhantomBot with OAuth Access Tokens."); String twitterData = ""; try { twitterData = "# Twitter Configuration File\r\n" + "# Generated by PhantomBot GenerateTwitterTokens\r\n" + "# If new tokens are required, run the application again.\r\n" + "#\r\n" + "# PROTECT THIS FILE AS IF IT HAD YOUR TWITTER PASSWORD IN IT!\r\n" + "twitter_username=" + username + "\r\n" + "twitter_access_token=" + accessToken.getToken() + "\r\n" + "twitter_secret_token=" + accessToken.getTokenSecret() + "\r\n"; Files.write(Paths.get("./twitter.txt"), twitterData.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); System.out.println("Data has been successfully stored in twitter.txt."); } catch (IOException ex) { System.out.println("Unable to create twitter.txt.\r\nPlease create with the following content:\r\n" + twitterData); System.exit(1); } } catch (TwitterException ex) { System.out.println("Twitter returned an error:\r\n" + ex.getMessage()); System.exit(1); } }
From source file:hashimotonet.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * /*from ww w .j a va2s. c o m*/ * @param args * message */ public static void main(String[] args) { /* try { new UpdateStatus().connectTwitter(); } catch(Exception e) { e.printStackTrace(); } */ if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); System.exit(-1); } String message = ""; for (int i = 0; i < args.length; i++) { message += args[i] + " "; } try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is // already available RequestToken requestToken = twitter.getOAuthRequestToken(); // RequestToken requestToken = new RequestToken(Globals.KEY,Globals.SECRET); String url = requestToken.getAuthenticationURL(); System.out.println("url = " + url); 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()); 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()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is // not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(message); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + 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:info.maslowis.twitterripper.twitter.OAuthTwitter.java
License:Open Source License
/** * Displays authorization URL and gets PIN for connection to twitter under authorized user *//*from w w w . ja va 2s .c o m*/ public void authorization() throws IOException { try { Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerKeySecret); RequestToken requestToken = twitter.getOAuthRequestToken(); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Authorization URL:").reset()); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.CYAN).a(requestToken.getAuthorizationURL())); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.RED).a("Enter PIN please:").reset()); String pin = reader.readLine(); twitter.getOAuthAccessToken(requestToken, pin); } catch (TwitterException e) { logger.error("Authorization fail! Please try to run application again and enter PIN."); exit(1); } }