List of usage examples for twitter4j Twitter getOAuthAccessToken
AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;
From source file:com.tuncaysenturk.jira.plugins.compatibility.servlet.TwitterLoginServlet.java
private void twitterCallback(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> context) { if (null == req.getParameter("denied") && null != req.getParameter("oauth_verifier")) { String verifier = req.getParameter("oauth_verifier").toString(); PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet(); propSet.setString("accessTokenVerifier", verifier); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(propSet.getString("consumerKey"), propSet.getString("consumerSecret")); RequestToken requestToken = new RequestToken(propSet.getString("requestToken"), propSet.getString("requestTokenSecret")); propSet.remove("requestToken"); propSet.remove("requestTokenSecret"); try {/* ww w . j ava 2 s. co m*/ AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); propSet.setString("accessToken", accessToken.getToken()); propSet.setString("accessTokenSecret", accessToken.getTokenSecret()); User user = twitter.verifyCredentials(); logger.info(JTPConstants.LOG_PRE + "User :" + user.getScreenName() + " logged in successfully"); restartListener(req, resp, context); } catch (TwitterException e) { logger.error(JTPConstants.LOG_PRE + "Error while streaming", e); ExceptionMessagesUtil.addExceptionMessage("Error while streaming : ", e); } } else { logger.warn(JTPConstants.LOG_PRE + "User denied Twitter authorization, plugin will not work properly"); ExceptionMessagesUtil .addExceptionMessage("User denied Twitter authorization, plugin will not work properly"); } }
From source file:com.twitstreet.servlet.CallBackServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1 response.setHeader("Pragma", "no-cache"); //HTTP 1.0 response.setDateHeader("Expires", 0); //prevents caching at the proxy server Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret()); RequestToken requestToken = (RequestToken) request.getSession().getAttribute(REQUEST_TOKEN); String verifier = request.getParameter(OAUTH_VERIFIER); try {/* ww w .ja v a2s . c o m*/ AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); long userId = accessToken.getUserId(); String screenName = accessToken.getScreenName(); String oauthToken = accessToken.getToken(); String oauthTokenSecret = accessToken.getTokenSecret(); User user = null; user = userMgr.getUserById(userId); //new user if (user == null) { twitter4j.User twUser = twitter.showUser(userId); user = new User(); user.setId(userId); user.setUserName(screenName); user.setLastIp(request.getRemoteAddr()); user.setOauthToken(oauthToken); user.setOauthTokenSecret(oauthTokenSecret); user.setCash(configMgr.getInitialMoney()); user.setPictureUrl(twUser.getProfileImageURL().toExternalForm()); user.setDescription(twUser.getDescription()); user.setLongName(twUser.getName()); user.setLocation(twUser.getLocation()); user.setLanguage(twUser.getLang()); user.setUrl(twUser.getURL() == null ? null : twUser.getURL().toExternalForm()); userMgr.saveUser(user); String referenceId = (String) request.getSession().getAttribute(HomePageServlet.REFERENCE_ID); long referenceLong = -1; try { referenceLong = Long.parseLong(referenceId); } catch (NumberFormatException e) { logger.error("Parsing reference id failed: " + referenceId); } if (referenceLong > -1) { userMgr.invite(referenceLong, user.getId()); } request.getSession().removeAttribute(HomePageServlet.REFERENCE_ID); } else { //existing user logging in again user = new User(); user.setId(userId); user.setUserName(screenName); user.setLastIp(request.getRemoteHost()); user.setOauthToken(oauthToken); user.setOauthTokenSecret(oauthTokenSecret); user.setAutoPlayer(false); userMgr.updateUser(user); } request.getSession().setAttribute(User.USER_ID, user.getId()); Cookie cookies[] = createCookie(userId, oauthToken); writeCookies(response, cookies); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
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", "");/* www . j a v a2s . c o 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:com.yattatech.dbtc.dao.SystemPreferences.java
License:Open Source License
public TwitterLoginStatus setTwitterData(final Bundle bundle) { if (Debug.isDebugable()) { Debug.d(TAG, "setTwitterData b=" + bundle); }/*from w ww .j a va 2 s .c o m*/ TwitterLoginStatus status = TwitterLoginStatus.UNKNOWN; try { final RequestToken requestToken = (RequestToken) bundle.get(Constants.TWITTER_REQUEST_TOKEN); final String twitterCallback = bundle.getString(Constants.TWITTER_CALLBACK_VALUE); if (Debug.isDebugable()) { Debug.d(TAG, "twitterCallback=" + twitterCallback); } if (twitterCallback.contains("denied")) { status = TwitterLoginStatus.DENIED; } else { final Uri url = Uri.parse(twitterCallback); final Twitter twitter = TwitterUtil.getTwitter(); final String verifier = url.getQueryParameter(Constants.OAUTH_VERIFIER); final AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); if (accessToken == null) { Debug.d(TAG, "Unable to create AccessToken Twitter"); status = TwitterLoginStatus.FAILED; } else { mPrefs.edit().putString(TWITTER_TOKEN, accessToken.getToken()) .putString(TWITTER_TOKEN_SECRET, accessToken.getTokenSecret()).commit(); status = TwitterLoginStatus.SUCCESS; } } } catch (Exception e) { Debug.e(TAG, "Failed:", e); } return status; }
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);// www.j a v a 2s .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] * //from w w w. ja v a2s .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:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
public void addTwitter() { Long vdcId = getVDCRequestBean().getCurrentVDCId(); try {/* w w w . j a v a 2 s. c o m*/ Twitter twitter = new TwitterFactory().getInstance(); AccessToken accessToken = twitter .getOAuthAccessToken((RequestToken) getSessionMap().remove("requestToken"), twitterVerifier); vdcService.setTwitterCredentials(accessToken.getToken(), accessToken.getTokenSecret(), vdcId); if (vdcId != null) { // refresh the current vdc object, since it has changed getVDCRequestBean().setCurrentVDC(vdcService.findById(vdcId)); } getVDCRenderBean().getFlash().put("successMessage", "Automatic tweets are now enabled."); } catch (TwitterException te) { te.printStackTrace(); } }
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 v a 2s . com */ 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:ens.demo.twitter.CallbackServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j av a2s. co 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 { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); if (twitter == null) { response.sendRedirect(request.getContextPath() + "/"); return; } Customer customer = (Customer) request.getSession().getAttribute("cust"); RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); if (customer == null) { customer = new Customer(); request.getSession().setAttribute("cust", customer); } customer.setFirstName(twitter.getScreenName()); customer.setToken(accessToken.getToken()); customer.setTokenSecret(accessToken.getTokenSecret()); customer.setUserId(twitter.getId()); DataStore store = DataStore.getInstance(); Customer existingCustomer = store.findCustomerbyId(twitter.getId()); if (existingCustomer == null) { existingCustomer = new Customer(); existingCustomer.setFirstName(twitter.getScreenName()); existingCustomer.setToken(accessToken.getToken()); existingCustomer.setTokenSecret(accessToken.getTokenSecret()); existingCustomer.setUserId(twitter.getId()); store.addCustomer(existingCustomer); } else { existingCustomer.setFirstName(twitter.getScreenName()); existingCustomer.setToken(accessToken.getToken()); existingCustomer.setTokenSecret(accessToken.getTokenSecret()); customer.setMobileNo(existingCustomer.getMobileNo()); customer.setEmergencyNo1(existingCustomer.getEmergencyNo1()); customer.setEmergencyNo2(existingCustomer.getEmergencyNo2()); customer.setEmergencyNo3(existingCustomer.getEmergencyNo3()); } request.getSession().removeAttribute("requestToken"); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/index.jsp"); }
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 . j a va2 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); } }