Example usage for twitter4j Twitter setOAuthAccessToken

List of usage examples for twitter4j Twitter setOAuthAccessToken

Introduction

In this page you can find the example usage for twitter4j Twitter setOAuthAccessToken.

Prototype

void setOAuthAccessToken(AccessToken accessToken);

Source Link

Document

Sets the access token

Usage

From source file:javatwiter4j.NewJFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    String tweet = "";
    tweet = jTextField1.getText();/*w  w w.j a  v a2s  . c o m*/
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(apiKey, apiSecretKey);
        AccessToken accessTokenn = new AccessToken(accessToken, accessTokenSecret);
        twitter.setOAuthAccessToken(accessTokenn);
        twitter.updateStatus(tweet);
    } catch (Exception ex) {
        jLabel1.setText("Son Tweet: Gnderilemedi");
    }
    jLabel1.setText("Son Tweet: Gnderildi");
}

From source file:jp.co.tweetmap.util.TwitterUtils.java

License:Apache License

/**
 * Gets the Twitter instance. Access token is automatically set if it is saved.
 *
 * @param context {@link Context}, not {@code null}.
 * @return Twitter instance./*from  www . ja va2 s  .c  o  m*/
 */
public static Twitter getTwitterInstance(Context context) {
    String consumerKey = context.getString(R.string.twitter_consumer_key);
    String consumerSecret = context.getString(R.string.twitter_consumer_secret_key);

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    if (hasAccessToken(context)) {
        twitter.setOAuthAccessToken(loadAccessToken(context));
    }
    return twitter;
}

From source file:jp.wda.azeda.core.daemons.impl.RetweetsCrawlerImpl.java

License:Apache License

/**
 *
 *///from  w  w w .  j  ava2 s.c o m
@Aspect("aop.requiredTx")
public void crawl() throws TwitterException {
    log.debug("crawl retweets!!" + tweets.size());
    if (tweets.size() == 0) {
        loadTweets();
    }
    if (tweets.size() == 0) {
        return;
    }

    RetweetedTweet tweet = tweets.remove(0);
    log.debug("check tweet " + tweet.getTweetID());

    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(tweet.getAccessToken().getAccessToken(),
            tweet.getAccessToken().getAccessTokenSecret());
    twitter.setOAuthAccessToken(accessToken);

    ResponseList<Status> rt = getRetweets(twitter, tweet.getTweetID());
    if (!alive) {
        return;
    }
    if (rt == null || rt.size() == 0) {
        return;
    }

    HashMap<Long, Status> retweets = new HashMap<Long, Status>();
    for (Status status : rt) {
        retweets.put(status.getUser().getId(), status);
    }

    List<Retweeter> registered = retweetersDao.getRetweeterIDs(tweet.getTweetID());
    for (Retweeter retweeter : registered) {
        long registeredUserID = retweeter.getRetweeterID();
        if (retweets.containsKey(registeredUserID)) {
            retweets.remove(registeredUserID);
            continue;
        }
    }
    if (retweets.size() == 0) {
        return;
    }

    for (Status status : retweets.values()) {
        long retweeter = status.getUser().getId();
        long oldest = System.currentTimeMillis() - retweetExpired * 60 * 1000L;
        if (status.getCreatedAt().getTime() < oldest) {
            log.info(tweet.getTweetID() + " retweet by " + status.getUser().getScreenName() + " ? "
                    + retweetExpired + "?????????");
            insertRetweeter(twitter.getId(), tweet.getTweetID(), retweeter);
            continue;
        }

        List<Status> userTimeline = loadRetweetersTweets(twitter, tweet.getTweetID(), retweeter, 1);
        if (!alive) {
            return;
        }
        if (userTimeline == null) {
            continue;
        }

        int skips = 0;
        for (int i = userTimeline.size() - 1; i >= 0; i--) {
            Status s = userTimeline.get(i);
            UserMentionEntity[] mentions = s.getUserMentionEntities();
            if (s.isRetweet()) {
                skips++;
                continue;
            }
            if (mentions == null || mentions.length > 0) {
                skips++;
                continue;
            }

            log.debug(s.getId() + ":" + s.getCreatedAt() + "(" + s.isRetweet() + ") " + s.getText());

            Retweet retweet = new Retweet();
            retweet.setTweetID(s.getId());
            retweet.setRetweetTo(tweet.getTweetID());
            retweet.setRetweeterID(retweeter);
            retweet.setTweettext(s.getText());
            retweet.setCreatedat(new Timestamp(s.getCreatedAt().getTime()));
            retweet.setSkiptweets(skips);
            retweet.setScreenName(status.getUser().getScreenName());
            dtoRetweets.add(retweet);

            insertRetweeter(twitter.getId(), tweet.getTweetID(), retweeter);
            break;
        }
    }

    register();
}

From source file:jp.wda.azeda.core.daemons.impl.UserCrawlerImpl.java

License:Apache License

/**
 *
 */// w ww  . j a  v a  2s.  c o m
@Aspect("aop.requiredTx")
public void crawl() throws TwitterException {
    StoredAccessToken storedAccessToken = accessTokensDao.getAccessTokenByUserID(userID);
    if (storedAccessToken == null) {
        return;
    }
    if (!alive) {
        return;
    }
    log.debug("crawl user retweets!!");

    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(storedAccessToken.getAccessToken(),
            storedAccessToken.getAccessTokenSecret());
    twitter.setOAuthAccessToken(accessToken);

    List<Status> retweets = twitter.getRetweetsOfMe();
    if (!alive) {
        return;
    }

    List<RetweetedTweet> registered = dao.getAll(userID,
            new Timestamp(System.currentTimeMillis() - 365 * 24 * 60 * 60 * 1000L));
    List<Long> registeredIDs = new ArrayList<Long>();
    for (RetweetedTweet t : registered) {
        registeredIDs.add(t.getTweetID());
    }
    if (!alive) {
        return;
    }

    List<RetweetedTweet> dtos = new ArrayList<RetweetedTweet>();
    long oldest = System.currentTimeMillis() - expired * 24 * 60 * 60 * 1000L;
    for (Status s : retweets) {
        if (registeredIDs.contains(s.getId())) {
            continue;
        }
        if (s.getCreatedAt().getTime() < oldest) {
            continue;
        }

        RetweetedTweet dto = new RetweetedTweet();
        dto.setTweetID(s.getId());
        dto.setUserID(userID);
        dto.setTweettext(s.getText());
        dto.setCreatedat(new Timestamp(s.getCreatedAt().getTime()));
        dtos.add(dto);
    }
    if (!alive) {
        return;
    }
    dao.insertBatch(dtos);
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.MainApp.java

License:Open Source License

@Override
public void init() throws Exception {
    // DI/*from  w w w  . j  a v a 2s  .c  om*/
    Injector injector = Guice.createInjector();
    injector.injectMembers(this);

    // Twitter?ConsumerKey/ConsumerSecret?
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(TwitterAPIKey.getConsumerKey(), TwitterAPIKey.getConsumerSecret());
    AccessToken accessToken = repository.load();
    if (accessToken != null) {
        twitter.setOAuthAccessToken(accessToken);
    }
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.service.AuthenticationService.java

License:Open Source License

/**
 * RequestToken?PIN??AccessToken??// w w  w.j av a2 s . co  m
 * RequestToken??????????{@code null}?
 *
 * @param requestToken RequestToken
 * @param pinCode ???PIN
 * @return AccessToken??????????{@code null}
 */
public AccessToken requestAccessToken(RequestToken requestToken, String pinCode) {
    Twitter twitter = TwitterFactory.getSingleton();

    AccessToken accessToken = null;
    try {
        accessToken = twitter.getOAuthAccessToken(requestToken, pinCode);
        twitter.setOAuthAccessToken(accessToken);
    } catch (IllegalStateException e) {
        System.err.println(ErrorCode.NO_TOKEN_AVAILABLE);
    } catch (TwitterException e) {
        System.err.println(ErrorCode.TWITTER_AUTHORIZATION_FAILED);
    }

    return accessToken;
}

From source file:mineTwit.Main.java

License:Open Source License

private void authenticateTwitter(AccessToken accessToken, Twitter twitter, String loadKey, String loadSecret) {
    //getLogger().info("[authenticateTwitter][DEBUG]APItoken is " + loadKey);
    //getLogger().info("[authenticateTwitter][DEBUG]APIsecret is " + loadSecret);
    twitter.setOAuthConsumer(loadKey, loadSecret);
    twitter.setOAuthAccessToken(accessToken);
}

From source file:net.bluemix.droneselfie.TwitterUtilities.java

License:Open Source License

private String tweet(String pictureId, String message) {
    String output = null;/* w  ww .  ja v a2s  .co  m*/
    if (message == null)
        return null;
    if (message.equalsIgnoreCase(""))
        return null;

    try {
        String consumerKey = ConfigUtilities.getSingleton().getTwitterConsumerKey();
        String consumerSecret = ConfigUtilities.getSingleton().getTwitterConsumerSecret();
        String accessToken = ConfigUtilities.getSingleton().getTwitterAccessToken();
        String accessTokenSecret = ConfigUtilities.getSingleton().getTwitterAccessTokenSecret();

        TwitterFactory twitterFactory = new TwitterFactory();
        Twitter twitter = twitterFactory.getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

        StatusUpdate statusUpdate = new StatusUpdate(message);

        AttachmentInputStream data = DatabaseUtilities.getSingleton().getDB().getAttachment(pictureId,
                pictureId);
        statusUpdate.setMedia("picture", data);

        Status status = twitter.updateStatus(statusUpdate);
        if (status == null)
            return null;
        output = "https://twitter.com/bluedroneselfie/status/" + String.valueOf(status.getId());

        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return output;
}

From source file:net.bluemix.newsaggregator.TwitterUtilities.java

License:Open Source License

private String tweet(String message) {
    String output = null;// ww w.  ja  va2  s.com
    if (message == null)
        return null;
    if (message.equalsIgnoreCase(""))
        return null;

    try {
        String consumerKey = ConfigUtilities.getSingleton().getTwitterConsumerKey();
        String consumerSecret = ConfigUtilities.getSingleton().getTwitterConsumerSecret();
        String accessToken = ConfigUtilities.getSingleton().getTwitterAccessToken();
        String accessTokenSecret = ConfigUtilities.getSingleton().getTwitterAccessTokenSecret();

        TwitterFactory twitterFactory = new TwitterFactory();
        Twitter twitter = twitterFactory.getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

        StatusUpdate statusUpdate = new StatusUpdate(message);

        Status status = twitter.updateStatus(statusUpdate);
        if (status == null)
            return null;
        output = "https://twitter.com/BluemixInfo/status/" + String.valueOf(status.getId());

        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return output;
}

From source file:net.firejack.platform.web.security.twitter.MobileTwitterAuthenticationProcessor.java

License:Apache License

@Override
public void processAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    ServiceResponse serviceResponse;//from ww w  .jav  a 2s.com
    if (StringUtils.isBlank(getTwitterConsumerKey()) || StringUtils.isBlank(getTwitterConsumerSecret())) {
        logger.error("Twitter consumer key or consumer secret configs were not set.");
        serviceResponse = new ServiceResponse("Twitter consumer key or consumer secret configs were not set.",
                false);
    } else {
        String accessToken = request.getParameter(PARAM_ACCESS_TOKEN);
        String accessTokenSecret = request.getParameter(PARAM_ACCESS_TOKEN_SECRET);
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(accessTokenSecret)) {
            serviceResponse = new ServiceResponse(PARAM_ACCESS_TOKEN + " and " + PARAM_ACCESS_TOKEN_SECRET
                    + " parameters should be provided.", false);
        } else {
            AccessToken token = new AccessToken(accessToken, accessTokenSecret);
            if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(accessTokenSecret)) {
                logger.warn("accessToken = " + accessToken + "; accessSecret = " + accessTokenSecret);
            }
            try {
                Twitter twitter = populateTwitterService();
                twitter.setOAuthAccessToken(token);
                String browserIpAddress = request.getRemoteAddr();
                AuthenticationToken authenticationToken = getOpenFlameToken(twitter, browserIpAddress);

                if (authenticationToken == null) {
                    logger.error("Authentication token is null.");
                    serviceResponse = new ServiceResponse("Authentication token is null.", false);
                } else {
                    serviceResponse = new ServiceResponse(authenticationToken,
                            "Authentication token obtained successfully.", true);
                }
            } catch (Throwable th) {
                logger.error(th.getMessage(), th);
                serviceResponse = new ServiceResponse(
                        th.getMessage() == null ? "Server error occurred." : th.getMessage(), false);
            }
        }
    }
    try {
        processMobilePhoneResponse(serviceResponse, request, response);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}