Search in sources :

Example 1 with RequestToken

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;
    }
}
Also used : RequestToken(twitter4j.auth.RequestToken) AccessToken(twitter4j.auth.AccessToken) File(java.io.File) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 2 with RequestToken

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);
    }
}
Also used : Account(weibo4j.Account) T2WUser(h2weibo.model.T2WUser) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper) JSONException(weibo4j.org.json.JSONException) twitter4j(twitter4j) Oauth(weibo4j.Oauth) Weibo(weibo4j.Weibo) WeiboException(weibo4j.model.WeiboException) T2WUser(h2weibo.model.T2WUser) JSONObject(weibo4j.org.json.JSONObject) AccessToken(weibo4j.http.AccessToken) RequestToken(twitter4j.auth.RequestToken) HttpServletRouter(h2weibo.HttpServletRouter)

Example 3 with RequestToken

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");
}
Also used : RequestToken(twitter4j.auth.RequestToken) Properties(java.util.Properties)

Example 4 with RequestToken

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);
    }
}
Also used : Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory) URISyntaxException(java.net.URISyntaxException) Properties(java.util.Properties) URI(java.net.URI) RequestToken(twitter4j.auth.RequestToken) AccessToken(twitter4j.auth.AccessToken) TwitterException(twitter4j.TwitterException)

Example 5 with RequestToken

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);
    }
}
Also used : Status(twitter4j.Status) InputStreamReader(java.io.InputStreamReader) RequestToken(twitter4j.auth.RequestToken) AccessToken(twitter4j.auth.AccessToken) BufferedReader(java.io.BufferedReader) Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory) IOException(java.io.IOException) TwitterException(twitter4j.TwitterException)

Aggregations

RequestToken (twitter4j.auth.RequestToken)8 Twitter (twitter4j.Twitter)4 TwitterFactory (twitter4j.TwitterFactory)4 AccessToken (twitter4j.auth.AccessToken)4 IOException (java.io.IOException)3 TwitterException (twitter4j.TwitterException)3 Properties (java.util.Properties)2 StudyTwitterPluginConfigurator (com.jetbrains.edu.learning.StudyTwitterPluginConfigurator)1 HttpServletRouter (h2weibo.HttpServletRouter)1 DBHelper (h2weibo.model.DBHelper)1 T2WUser (h2weibo.model.T2WUser)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStreamReader (java.io.InputStreamReader)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 HttpSession (javax.servlet.http.HttpSession)1 ConfigurationException (org.osgi.service.cm.ConfigurationException)1 twitter4j (twitter4j)1