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:toninbot.ToninBot.java

/**
 * @param args the command line arguments
 *///from   w  w  w.j  a  v a 2  s.c o m
public static void main(String[] args) {

    AccessToken accessToken = new AccessToken(Credenciales.token, Credenciales.tokenSecret);
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(Credenciales.consumerKey);
    builder.setOAuthConsumerSecret(Credenciales.consumerSecret);

    Configuration configuration = builder.build();
    TwitterStreamFactory twStreamFactory = new TwitterStreamFactory(configuration);
    TwitterStream twitterStream = twStreamFactory.getInstance();
    twitterStream.setOAuthAccessToken(accessToken);

    ToninStatusListener listener = new ToninStatusListener();
    twitterStream.addListener(listener);

    FilterQuery filtre = new FilterQuery();
    filtre.follow(184742273L, 2841338087L);//Allegue y proyectoPSIa1
    //filtre.follow(2841338087L);//proyectoPSIa1

    twitterStream.filter(filtre);
}

From source file:toninbot.ToninStatusListener.java

public ToninStatusListener() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(Credenciales.consumerKey);
    builder.setOAuthConsumerSecret(Credenciales.consumerSecret);

    Configuration configuration = builder.build();
    AccessToken accessToken = new AccessToken(Credenciales.token, Credenciales.tokenSecret);

    TwitterFactory twFactory = new TwitterFactory(configuration);
    twitter = twFactory.getInstance();//from w w  w .j a  va2 s  .  c om
    twitter.setOAuthAccessToken(accessToken);

    randomGenerator = new Random();

    //La lista de tweets
    respuestas = new ArrayList();
    respuestas.add("Fora de horario! Este tweet esta fora de horario!");
    respuestas.add("Eeeeh!! Estas fora de horario!");
    respuestas.add("FORA DE HORARIO!");
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

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

    Scanner sc = new Scanner(System.in);
    System.out.println(//from   w w  w  . j  a v  a2 s.  c om
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twitterbot.example.tweet.RetweetMethods.java

static public void RetweetTweet(String id) {
    try {//  w w w  .j  a  v  a2s  .c o m
        String consumerKey = ""; // key obtained after registering app.
        String consumerSecret = ""; // secret key obtained from the registered app.
        String twitterToken = "";
        // access_token received by authentication user's twitter account
        String twitterSecret = "";
        // access_secret obtained by authentication user's twitter account
        String tweetId = id; //messageId of the tweet to be retweeted

        Twitter factory = new TwitterFactory().getInstance();
        Twitter twitter = factory;
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret);
        twitter.setOAuthAccessToken(accessToken);
        twitter.retweetStatus(Long.valueOf(tweetId));
    } catch (Exception ex) {
        System.out.println("Error: " + ex.getMessage());
    }
}

From source file:twitteremoji.FXMLDocumentController.java

public void setup(Stage stage) {
    this.stage = stage;
    try {//from ww w. ja  va2 s  .  co m
        // start twitter auth process
        twitter = TwitterFactory.getSingleton();
        twitter.setOAuthConsumer(key, secret);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        // check if we have a token for the user, if not authenticate and store in prefs
        if (!TokenPref.hasToken()) {
            System.out.println("has no prefs!");
            Dialogs dialog = Dialogs.create().owner(null).title("Grant account access")
                    .masthead("You must grant TwitterEmoji access to your account")
                    .message(
                            "You only have to do this once. Go to Twitter authorisation webpage (opens default browser)?")
                    .actions(Dialog.Actions.NO, Dialog.Actions.YES);
            Action response = dialog.showConfirm();
            if (response.textProperty().getValue().contains("No")) {
                Platform.exit();
                return;
            }
            try {
                java.awt.Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (IOException ex) {
                Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
                Platform.exit();
                return;
            } catch (URISyntaxException ex) {
                Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
                Platform.exit();
                return;
            }
            // get pin
            Optional<String> responsePin = Dialogs.create().owner(stage).title("Authentication")
                    .masthead("Authorise TwitterEmoji to get pin").message("Please enter pin:").showTextInput();
            // One way to get the response value.
            String pin = null;
            if (responsePin.isPresent()) {
                pin = responsePin.get();
            }
            AccessToken accessToken = null;
            if (pin == null) {
                accessToken = twitter.getOAuthAccessToken();
            } else {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            }
            // assume got, otherwise TwitterException thrown
            // store tokens
            TokenPref.putToken(accessToken.getToken());
            TokenPref.putSecret(accessToken.getTokenSecret());
        } else {
            System.out.println("has prefs!");
            /*
            Dialogs dialog = Dialogs.create()
                .owner(null)
                .title("Information")
                .masthead("Application has Twitter token/secret")
                .message("Token: "+TokenPref.getToken()+"\nSecret: "+TokenPref.getSecret());
            dialog.showInformation();
            */
            //Status status = twitter.updateStatus("testing api");
            AccessToken accessToken = new AccessToken(TokenPref.getToken(), TokenPref.getSecret());
            twitter.setOAuthAccessToken(accessToken);
            Dialogs dialog = Dialogs.create().owner(null).title("Information")
                    .masthead("Twitter authentication").message("Connected to Twitter");
            dialog.showInformation();
        }
    } catch (TwitterException ex) {
        Dialogs.create().owner(null).title("Error").masthead(null)
                .message("Twitter authentication could not be completed").showError();
        Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        Platform.exit();
        return;
    }
    statusLabel.setText(STATUS_PREFIX + STATUS_CONNECTED);
    /*
    // add close behaviour to window to shut down twitter
    stage.setOnHiding(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent event) {
        // TODO : check if this is triggered just by window minimisation
        // stop system
        System.out.println("--- Twitter client stopped");
    }
    });
    */
    /*
    // add message reader
    (new Thread() {
    public void run() {
        // do what?
    }
    }).start();
        */
}

From source file:twitterplugin.TwitterSettings.java

License:Open Source License

public AccessToken getAccessToken() {
    String token = get(ACCESS_TOKEN);
    String secret = get(ACCESS_TOKEN_SECRET);
    if (token == null || secret == null || token.length() == 0 || secret.length() == 0) {
        return null;
    }/*from   w w w . j  av a2 s  . co  m*/
    return new AccessToken(token, secret);
}

From source file:TwitterPublisher.Connexions.TwitterInterface.java

/**
 * Publish the given message on twitter.
 * @param message//from   w  w  w .ja v  a  2  s. c  o  m
 * @throws TwitterException 
 */
public static void publish(String message) throws TwitterException {

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer("vIZ097dCEeXqnYofk8N6qTw9E", "GdN2pVxNTHJNRBZltaeeCDSTRScQL1bjCzlIgDza2WVRGfZ5SC");
    twitter.setOAuthAccessToken(new AccessToken("795590633918464001-NpyvUY0OylVbLNznVvoG98M8pMIaajv",
            "z1xR0jyHBbUsDioW3T7LIAC9b3FgTyvaGxgMSiGGn9cjR"));
    twitter.updateStatus(message);
    System.out.println("Twitter message has been published");

}

From source file:twitterstreamsample.NewJFrame.java

private void ClickActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClickActionPerformed
    // TODO add your handling code here:

    String consKey = "Your key";
    String consSecret = "Your Secret";
    String accToken = "Your token";
    String accSecret = "Your secret";

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            textArea.append(status.getUser().getName() + ":" + status.getText());
        }/*  www.j  av  a  2  s .c om*/

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    twitterStream.setOAuthConsumer(consKey, consSecret);

    twitterStream.setOAuthAccessToken(new AccessToken(accToken, accSecret));

    twitterStream.addListener(listener);

    twitterStream.sample();

}

From source file:twitterswingclient.TwitterClient.java

private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed
    // TODO add your handling code here:
    String consKey = "Your key";
    String consSecret = "Your secret";
    String accToken = "Your key";
    String accSecret = "Your secret";
    try {/*from  w w w.  j  a  va2s.  c  om*/

        TwitterFactory twitterFactory = new TwitterFactory();

        Twitter twitter = twitterFactory.getInstance();

        twitter.setOAuthConsumer(consKey, consSecret);

        twitter.setOAuthAccessToken(new AccessToken(accToken, accSecret));

        StatusUpdate statusUpdate = new StatusUpdate(status.getText());

        statusUpdate.setMedia("Feeling great",
                new URL("http://media3.giphy.com/media/el1tH0BzEWm4w/giphy.gif").openStream());

        Status stat = twitter.updateStatus(statusUpdate);

        textArea.append("status.toString() = " + stat.toString());
        textArea.append("status.getInReplyToScreenName() = " + stat.getInReplyToScreenName());
        textArea.append("status.getSource() = " + stat.getSource());
        textArea.append("status.getText() = " + stat.getText());
        textArea.append("status.getContributors() = " + Arrays.toString(stat.getContributors()));
        textArea.append("status.getCreatedAt() = " + stat.getCreatedAt());
        textArea.append("status.getCurrentUserRetweetId() = " + stat.getCurrentUserRetweetId());
        textArea.append("status.getGeoLocation() = " + stat.getGeoLocation());
        textArea.append("status.getId() = " + stat.getId());
        textArea.append("status.getInReplyToStatusId() = " + stat.getInReplyToStatusId());
        textArea.append("status.getInReplyToUserId() = " + stat.getInReplyToUserId());
        textArea.append("status.getPlace() = " + stat.getPlace());
        textArea.append("status.getRetweetCount() = " + stat.getRetweetCount());
        textArea.append("status.getRetweetedStatus() = " + stat.getRetweetedStatus());
        textArea.append("status.getUser() = " + stat.getUser());
        textArea.append("status.getAccessLevel() = " + stat.getAccessLevel());
        textArea.append("status.getHashtagEntities() = " + Arrays.toString(stat.getHashtagEntities()));
        textArea.append("status.getMediaEntities() = " + Arrays.toString(stat.getMediaEntities()));

        if (stat.getRateLimitStatus() != null) {
            textArea.append("status.getRateLimitStatus().getLimit() = " + stat.getRateLimitStatus().getLimit());
            textArea.append(
                    "status.getRateLimitStatus().getRemaining() = " + stat.getRateLimitStatus().getRemaining());
            textArea.append("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + stat.getRateLimitStatus().getResetTimeInSeconds());
            textArea.append("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + stat.getRateLimitStatus().getSecondsUntilReset());
            textArea.append("status.getRateLimitStatus().getRemainingHits() = "
                    + stat.getRateLimitStatus().getRemaining());
        }
        textArea.append("status.getURLEntities() = " + Arrays.toString(stat.getURLEntities()));
        textArea.append("status.getUserMentionEntities() = " + Arrays.toString(stat.getUserMentionEntities()));

    } catch (IOException ex) {
        textArea.append("IO Exception");
    } catch (TwitterException tw) {
        textArea.append("Twitter Exception");
    }
}

From source file:uk.ac.cam.cl.dtg.segue.auth.TwitterAuthenticator.java

License:Apache License

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference)
        throws NoUserException, IOException, AuthenticatorSecurityException {
    Credential credentials = credentialStore.get(internalProviderReference);
    twitter.setOAuthAccessToken(new AccessToken(credentials.getAccessToken(), credentials.getRefreshToken()));

    try {//www  .j a  v a  2s  .  c  o m
        twitter4j.User userInfo = twitter.verifyCredentials();

        if (userInfo != null) {
            // Using twitter id for email field is a hack to avoid a duplicate
            // exception due to null email field. Alistair and Steve dislike this...
            String givenName = null;
            String familyName = null;
            if (userInfo.getName() != null) {
                String[] names = userInfo.getName().split(" ");
                if (names != null) {
                    if (names.length > 0) {
                        givenName = names[0];
                    }
                    if (names.length > 1) {
                        familyName = names[1];
                    }
                }
            }

            return new UserFromAuthProvider(String.valueOf(userInfo.getId()), givenName, familyName,
                    userInfo.getId() + "-twitter", EmailVerificationStatus.NOT_VERIFIED, null, null, null);
        } else {
            throw new NoUserException();
        }
    } catch (TwitterException e) {
        throw new IOException(e.getMessage());
    }
}