Example usage for twitter4j.auth AccessToken AccessToken

List of usage examples for twitter4j.auth AccessToken AccessToken

Introduction

In this page you can find the example usage for twitter4j.auth AccessToken AccessToken.

Prototype

public AccessToken(String token, String tokenSecret) 

Source Link

Usage

From source file:org.openhab.action.twitter.internal.TwitterActionService.java

License:Open Source License

private static AccessToken getAccessToken() {
    try {/*from  w  w  w.ja  v a  2  s .  c o  m*/
        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;
    }
}

From source file:org.orcid.core.manager.impl.OrcidSocialManagerImpl.java

License:Open Source License

/**
 * Tweet a message to the specified profile
 * //from w w w. ja va 2s  .c o m
 * @param entity
 *            An entity containing the user information and the twitter
 *            credentials
 * @return true if it was able to tweet the updates
 * */
@SuppressWarnings("unchecked")
private boolean tweet(OrcidSocialEntity entity) {
    String jsonCredentials = decrypt(entity.getEncryptedCredentials());
    Map<String, String> credentials = (HashMap<String, String>) JSON.parse(jsonCredentials);
    Twitter twitter = new TwitterFactory().getInstance();

    twitter.setOAuthConsumer(twitterKey, twitterSecret);
    AccessToken accessToken = new AccessToken(credentials.get(TWITTER_USER_KEY),
            credentials.get(TWITTER_USER_SECRET));

    twitter.setOAuthAccessToken(accessToken);
    try {
        twitter.updateStatus(buildUpdateMessage(entity.getId().getOrcid()));
    } catch (Exception e) {
        LOGGER.error("Unable to tweet on profile {}", entity.getId().getOrcid());
        return false;
    }

    return true;
}

From source file:org.osframework.maven.plugins.twitter.AbstractTwitterMojo.java

License:Apache License

protected void loadAccessToken(final Twitter twitter) throws TwitterException {
    // Check for stored access token
    File tokenStore = new File(getWorkDirectory(), "auth");
    if (tokenStore.canRead()) {
        Properties p = new Properties();
        InputStream in = null;//from   w  ww .jav  a2  s  .co  m
        try {
            in = new FileInputStream(tokenStore);
            p.load(in);
        } catch (IOException ignore) {
        } finally {
            IOUtil.close(in);
        }
        authToken = new AccessToken(p.getProperty(OAUTH_ACCESS_TOKEN),
                p.getProperty(OAUTH_ACCESS_TOKEN_SECRET));
    }
    // Get access token via user authorization
    else {
        RequestToken requestToken = twitter.getOAuthRequestToken();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == authToken) {
            getLog().info("Open the following URL and grant access to your account:");
            getLog().info(requestToken.getAuthorizationURL());
            System.out.print("Enter the PIN (if available) or just hit enter. [PIN]: ");
            try {
                String pin = br.readLine();
                authToken = (0 < pin.length()) ? twitter.getOAuthAccessToken(requestToken, pin)
                        : twitter.getOAuthAccessToken();
            } catch (IOException ioe) {
                getLog().error("Could not read authorization PIN from input");
                throw new TwitterException(ioe);
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    getLog().error("Could not acquire access token");
                }
                throw te;
            }
        }
    }
}

From source file:org.primefaces.examples.service.TwitterAPIService.java

License:Apache License

public List<Status> getTweets(String username) {
    List<Status> tweets = null;

    try {/*from   w  w  w.  j  a v a2 s.c o  m*/
        if (username != null && !username.equals("")) {
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
            twitter.setOAuthAccessToken(new AccessToken(access_token, access_token_secret));
            Paging p = new Paging(1, 200);
            tweets = twitter.getUserTimeline(username, p);
        }
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }

    return tweets;
}

From source file:org.primefaces.examples.service.TwitterAPIService.java

License:Apache License

public List<Status> asyncSearch(String query) {

    TwitterListener listener = new TwitterAdapter() {
        @Override/*  w w w.j  a v  a  2s  .  co m*/
        public void searched(QueryResult queryResult) {
            asyncTweets = queryResult.getTweets();
        }

        @Override
        public void onException(TwitterException e, TwitterMethod method) {
            logger.severe(e.getMessage());
        }
    };

    AsyncTwitter twitter = new AsyncTwitterFactory().getInstance();
    twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    twitter.setOAuthAccessToken(new AccessToken(access_token, access_token_secret));
    twitter.addListener(listener);
    Query q = new Query(query);
    twitter.search(q);
    return asyncTweets;
}

From source file:org.rtsa.storm.TwitterSpout.java

License:Apache License

public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<Status>(1000);
    _collector = collector;//from   w w w.jav  a 2s  . co  m

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {

            if (status.getText().length() != 0 && status.getLang().equals("en")) {
                queue.offer(status);

            }
        }

        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        public void onTrackLimitationNotice(int i) {
        }

        public void onScrubGeo(long l, long l1) {
        }

        public void onException(Exception ex) {
        }

        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }

    };

    TwitterStream twitterStream = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance();

    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {

        twitterStream.sample();
    }

    else {

        FilterQuery query = new FilterQuery().track(keyWords);
        twitterStream.filter(query);
    }

}

From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java

License:Educational Community License

/**
  * {@inheritDoc}/*w w w  .  ja  v a2  s  . c o  m*/
  */
public String getTwitterName(ExternalIntegrationInfo info) {

    if (info == null) {
        return null;
    }

    //get values
    String token = info.getTwitterToken();
    String secret = info.getTwitterSecret();

    if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(secret)) {

        //global config
        Map<String, String> config = getTwitterOAuthConsumerDetails();

        //token for user
        AccessToken accessToken = new AccessToken(token, secret);

        //setup
        TwitterFactory factory = new TwitterFactory();
        Twitter twitter = factory.getInstance();
        twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
        twitter.setOAuthAccessToken(accessToken);

        //check
        try {
            return twitter.verifyCredentials().getScreenName();
        } catch (TwitterException e) {
            log.error("Error retrieving Twitter credentials: " + e.getClass() + ": " + e.getMessage());
        }
    }
    return null;
}

From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java

License:Educational Community License

/**
  * {@inheritDoc}/*ww  w .j  ava 2 s.c om*/
  */
public void sendMessageToTwitter(final String userUuid, String message) {
    //setup class thread to call later
    class TwitterUpdater implements Runnable {
        private Thread runner;
        private String userUuid;
        private String userToken;
        private String userSecret;
        private String message;

        public TwitterUpdater(String userUuid, String userToken, String userSecret, String message) {
            this.userUuid = userUuid;
            this.userToken = userToken;
            this.userSecret = userSecret;
            this.message = message;

            runner = new Thread(this, "Profile2 TwitterUpdater thread");
            runner.start();
        }

        //do it!
        public synchronized void run() {

            //global config
            Map<String, String> config = getTwitterOAuthConsumerDetails();

            //token for user
            AccessToken accessToken = new AccessToken(userToken, userSecret);

            //setup
            TwitterFactory factory = new TwitterFactory();
            Twitter twitter = factory.getInstance();
            twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
            twitter.setOAuthAccessToken(accessToken);

            try {
                twitter.updateStatus(message);
                log.info("Twitter status updated for: " + userUuid);

                //post update event
                sakaiProxy.postEvent(ProfileConstants.EVENT_TWITTER_UPDATE, "/profile/" + userUuid, true);
            } catch (TwitterException e) {
                log.error(
                        "ProfileLogic.sendMessageToTwitter() failed. " + e.getClass() + ": " + e.getMessage());
            }
        }
    }

    //is twitter enabled
    if (!sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
        return;
    }

    //get user info
    ExternalIntegrationInfo info = getExternalIntegrationInfo(userUuid);
    String token = info.getTwitterToken();
    String secret = info.getTwitterSecret();
    if (StringUtils.isBlank(token) || StringUtils.isBlank(secret)) {
        return;
    }

    //PRFL-423 limit to 140 chars
    //Hardcoded limit because 140 is the Twitter requirement so no need to make configurable
    message = ProfileUtils.truncate(message, 140, false);

    //instantiate class to send the data
    new TwitterUpdater(userUuid, token, secret, message);
}

From source file:org.sintef.jarduino.examples.advanced.Twitter4Arduino.java

License:LGPL

public Twitter4Arduino(String port, String customerKey, String customerSecret, String accessKey,
        String accessSecret, String userName) {
    super(port);// w  w  w.j  a v  a  2s.c  o m
    this.userName = userName;
    this.twitter = new TwitterFactory().getInstance();
    this.twitter.setOAuthConsumer(customerKey, customerSecret);
    AccessToken accessToken = new AccessToken(accessKey, accessSecret);
    this.twitter.setOAuthAccessToken(accessToken);

    this.timer = new Timer();
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

public void start(final BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {

    LOGGER.info("Starting " + this);

    client = new TwitterStreamingClient(this, consumerKey, consumerSecret, accessToken, accessTokenSecret);
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    try {/* w  ww  . ja  v  a  2 s .c  om*/
        client.run();
    } catch (InterruptedException | ControlStreamException | IOException e) {
        e.printStackTrace();
    }
}