use of twitter4j.auth.RequestToken in project openhab1-addons by openhab.
the class TwitterActionService method getAccessToken.
private static AccessToken getAccessToken() {
try {
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;
}
}
use of twitter4j.auth.RequestToken in project twitter-2-weibo by rjyo.
the class CallbackServlet method doGet.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpServletRouter r = new HttpServletRouter(request);
r.setPattern("/:type");
if (request.getParameter("denied") != null) {
response.sendRedirect("/");
return;
}
HttpSession session = request.getSession(false);
String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
String oauthVerifier = request.getParameter("oauth_verifier");
DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
if (r.is(":type", "weibo.jsp")) {
String code = request.getParameter("code");
if (code != null) {
T2WUser tid = helper.findOneByUser(loginUser);
if (tid.getToken() == null) {
// send for the first time
session.setAttribute(Keys.SESSION_PROMPT_TWEET, "You are ready to go! Do you want to tweet about this service and share it with your friends?");
}
Oauth oauth = new Oauth();
try {
AccessToken token = oauth.getAccessTokenByCode(code);
tid.setToken(token.getAccessToken());
Weibo weibo = new Weibo();
weibo.setToken(tid.getToken());
Account am = new Account();
try {
JSONObject obj = am.getUid();
String uid = obj.getString("uid");
tid.setWeiboUserId(uid);
} catch (WeiboException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
helper.saveUser(tid);
} catch (WeiboException e) {
log.error(e);
}
} else {
log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
}
} else if (r.is(":type", "twitter")) {
try {
TwitterFactory factory = new TwitterFactory();
Twitter t = factory.getInstance();
twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN);
twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier);
session.removeAttribute(Keys.SESSION_REQUEST_TOKEN);
if (accessToken != null) {
t.setOAuthAccessToken(accessToken);
User user = t.verifyCredentials();
loginUser = user.getScreenName();
T2WUser tid = helper.findOneByUser(loginUser);
if (tid.getTwitterToken() == null) {
// save latest id for the first time. sync from that tweet
ResponseList<Status> tl = t.getUserTimeline();
if (tl.size() > 0) {
Status s = tl.get(0);
tid.setLatestId(s.getId());
}
}
tid.setTwitterToken(accessToken.getToken());
tid.setTwitterTokenSecret(accessToken.getTokenSecret());
helper.saveUser(tid);
session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser);
}
} catch (TwitterException e) {
log.error("Twitter Exception", e);
throw new RuntimeException(e);
}
}
String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL);
if (requestUrl != null) {
session.removeAttribute(Keys.SESSION_REQUEST_URL);
response.sendRedirect(requestUrl);
} else {
response.sendRedirect("/u/" + loginUser);
}
}
use of twitter4j.auth.RequestToken in project twitter4j by yusuke.
the class ConfigurationTest method testConfigurationBuilder.
public void testConfigurationBuilder() throws Exception {
deleteFile("./twitter4j.properties");
ConfigurationBuilder builder;
Configuration conf;
builder = new ConfigurationBuilder();
conf = builder.build();
Configuration t = (Configuration) serializeDeserialize(conf);
assertEquals(conf, (Configuration) serializeDeserialize(conf));
assertTrue(0 == conf.getRestBaseURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAuthenticationURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAuthorizationURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAccessTokenURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthRequestTokenURL().indexOf("https://"));
builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey("key");
builder.setOAuthConsumerSecret("secret");
conf = builder.build();
assertTrue(0 == conf.getRestBaseURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAuthenticationURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAuthorizationURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAccessTokenURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthRequestTokenURL().indexOf("https://"));
RequestToken rt = new RequestToken("key", "secret");
// TFJ-328 RequestToken.getAuthenticationURL()/getAuthorizationURL() should return URLs starting with https:// for security reasons
assertTrue(0 == rt.getAuthenticationURL().indexOf("https://"));
assertTrue(0 == rt.getAuthorizationURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthAccessTokenURL().indexOf("https://"));
assertTrue(0 == conf.getOAuthRequestTokenURL().indexOf("https://"));
// disable SSL
writeFile("./twitter4j.properties", "twitter4j.restBaseURL=http://somewhere.com/" + "\n" + "twitter4j.debug=true" + "\n" + "media.providerParameters=debug=true&foo=bar");
conf = new ConfigurationBuilder().build();
assertEquals("http://somewhere.com/", conf.getRestBaseURL());
assertTrue(conf.isDebugEnabled());
Properties mediaProps = conf.getMediaProviderParameters();
assertNotNull(mediaProps);
assertNull(mediaProps.getProperty("hoge"));
assertEquals("true", mediaProps.getProperty("debug"));
assertEquals("bar", mediaProps.getProperty("foo"));
deleteFile("./twitter4j.properties");
}
use of twitter4j.auth.RequestToken in project twitter4j by yusuke.
the class GetAccessToken method main.
/**
* Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
*
* @param args message
*/
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);
}
}
use of twitter4j.auth.RequestToken in project twitter4j by yusuke.
the class UpdateStatus method main.
/**
* Usage: java twitter4j.examples.tweets.UpdateStatus [text]
*
* @param args message
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
System.exit(-1);
}
try {
Twitter twitter = new TwitterFactory().getInstance();
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(args[0]);
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);
}
}
Aggregations