Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

In this page you can find the example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder.

Prototype

ConfigurationBuilder

Source Link

Usage

From source file:OAuth.MyOwnTwitterFactory.java

License:Open Source License

public TwitterStream createOneTwitterStreamInstanceFromApp(String APIKey, String APIKeySecret,
        String accessToken, String accessTokenSecret) {
    TwitterStream twitterStream;//from   ww  w.jav  a 2  s .  com
    ConfigurationBuilder builder = new ConfigurationBuilder();
    if (!Admin.isTest()) {
        builder.setOAuthConsumerKey(APIKey);
        builder.setOAuthConsumerSecret(APIKeySecret);
        builder.setOAuthAccessToken(accessToken);
        builder.setOAuthAccessTokenSecret(accessTokenSecret);
        builder.setJSONStoreEnabled(true);
    } else {
        builder.setOAuthConsumerKey("KNjw1QTK1hJKx8LpK6X6rg");
        builder.setOAuthConsumerSecret("ikX9blowuh3FqFAkIg5LQi5voLOV413EWzPsDl77uU");
        builder.setOAuthAccessToken("31805620-QQy8TFFDKRxWyOUVnY08UcxT5bzrFhRWUa0A3lEW3");
        builder.setOAuthAccessTokenSecret("iJuCkdgrfIpGn5odyF2evMSvAsovreeEV6cZU5ihVVI7j");
        builder.setJSONStoreEnabled(true);
    }
    Configuration configuration = builder.build();
    TwitterStreamFactory factory = new TwitterStreamFactory(configuration);
    twitterStream = factory.getInstance();

    return twitterStream;
}

From source file:onl.area51.a51li.twitter.TwitterAccount.java

License:Apache License

public TwitterAccount(int id, String account, String token, String secret, TwitterApplication application) {
    this.id = id;
    this.account = account;
    this.token = token;
    this.secret = secret;

    ConfigurationBuilder cb = new ConfigurationBuilder().setOAuthConsumerKey(application.getKey())
            .setOAuthConsumerSecret(application.getSecret()).setOAuthAccessToken(token)
            .setOAuthAccessTokenSecret(secret);

    TwitterFactory f = new TwitterFactory(cb.build());
    twitter = f.getInstance();/*from   w  w  w.j  ava 2s.  c  o m*/
}

From source file:ontoSentiment.Amigos.java

@Override
public void run() {
    ConfigurationBuilder cb = new ConfigurationBuilder();

    //the following is set without accesstoken- desktop client
    cb.setDebugEnabled(true).setOAuthConsumerKey("FBd5n7dyl8mCz73qyfZ0p4XHb")
            .setOAuthConsumerSecret("vu5Xt5TzBSL9naOZylIYlx5MdcRlhH2LvkpW6KIkxSf9AqwuGt")
            .setOAuthAccessToken("3232400175-lAchtC6ChWMTnJKe3BaWbst8SucIaTjn5gm4Rp2")
            .setOAuthAccessTokenSecret("DnkquBWAS6igYpM8Z4r54hH7ztcfMX6u8OzMXBLwM9Xkh");

    try {/*from  ww  w.  j  a  v  a  2  s  .  co  m*/
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        //User u = twitter.showUser("karlaffabiola");            
        User u = twitter.showUser("raythemaster");
        IDs ids;
        System.out.println("Listing followers's ids.");

        System.out.println("ID: " + u.getId());
        System.out.println("Nome: " + u.getScreenName());

        long cursor = -1;
        PagableResponseList<User> pagableFollowings;
        List<User> listFriends = new ArrayList<>();
        List<User> listFriends2 = new ArrayList<>();

        pagableFollowings = twitter.getFriendsList(u.getId(), cursor, 200);
        System.out.println("Qunatidade followers: " + pagableFollowings.size());
        for (User user : pagableFollowings) {
            System.out.println("Id: " + user.getId() + " Nome: " + user.getScreenName());
            listFriends.add(user); // ArrayList<User>
        }

        for (User user : listFriends) {
            System.out.println("Id1: " + user.getId() + " Nome1: " + user.getScreenName());
            pagableFollowings = twitter.getFriendsList(user.getId(), cursor, 200);
            System.out.println("Qunatidade followers: " + pagableFollowings.size());
            for (User user2 : pagableFollowings) {
                System.out.println("Id2: " + user2.getId() + " Nome2: " + user2.getScreenName());
                listFriends2.add(user2); // ArrayList<User>
            }
        }
        System.out.println("Lista 1:" + listFriends.size());
        System.out.println("Lista 2:" + listFriends2.size());
        System.exit(0);
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get timeline: " + new Date());
        try {
            Thread.sleep(3 * 60 * 1000);
            run();
        } catch (InterruptedException ex) {
            Logger.getLogger(Amigos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ontoSentiment.Util.java

public static OAuth2Token getOAuth2Token() {
    OAuth2Token token = null;//  w  w  w. ja v  a 2s.co  m
    ConfigurationBuilder cb;
    cb = new ConfigurationBuilder();
    cb.setApplicationOnlyAuthEnabled(true);
    cb.setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET);
    try {
        token = new TwitterFactory(cb.build()).getInstance().getOAuth2Token();
    } catch (Exception e) {
        System.out.println("Could not get OAuth2 token");
        e.printStackTrace();
        System.exit(0);
    }
    return token;
}

From source file:ontoSentiment.Util.java

public static Twitter getTwitter() {
    OAuth2Token token;/*www  .ja v  a  2  s .  c o m*/
    token = getOAuth2Token();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setApplicationOnlyAuthEnabled(true);
    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
    cb.setOAuth2TokenType(token.getTokenType());
    cb.setOAuth2AccessToken(token.getAccessToken());
    return new TwitterFactory(cb.build()).getInstance();
}

From source file:org.addhen.smssync.data.twitter.TwitterClient.java

License:Open Source License

private void initTwitterFactory() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(mAuthConfig.consumerKey);
    builder.setOAuthConsumerSecret(mAuthConfig.consumerSecret);
    mTwitterFactory = new TwitterFactory(builder.build());

}

From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java

/**
 * Entry point for a Lappsgrid service.//from w  w w.j a  va 2  s  .c o m
 * <p>
 * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object
 * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container}
 * payload.
 * <p>
 * Errors and exceptions that occur during processing should be wrapped in a {@code Data}
 * object with the discriminator set to http://vocab.lappsgrid.org/ns/error
 * <p>
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br />
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br />
 *
 * @param input A JSON string representing a Data object
 * @return A JSON string containing a Data object with a Container payload.
 */
@Override
public String execute(String input) {
    Data<String> data = Serializer.parse(input, Data.class);
    String discriminator = data.getDiscriminator();

    // Return ERRORS back
    if (Discriminators.Uri.ERROR.equals(discriminator)) {
        return input;
    }

    // Generate an error if the used discriminator is wrong
    if (!Discriminators.Uri.GET.equals(discriminator)) {
        return generateError(
                "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator);
    }

    Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false)
            .build();

    // Authentication using saved keys
    Twitter twitter = new TwitterFactory(config).getInstance();
    String key = readProperty(KEY_PROPERTY);
    if (key == null) {
        return generateError("The Twitter Consumer Key property has not been set.");
    }

    String secret = readProperty(SECRET_PROPERTY);
    if (secret == null) {
        return generateError("The Twitter Consumer Secret property has not been set.");
    }

    twitter.setOAuthConsumer(key, secret);

    try {
        twitter.getOAuth2Token();
    } catch (TwitterException te) {
        String errorData = generateError(te.getMessage());
        logger.error(errorData);
        return errorData;
    }

    // Get query String from data payload
    Query query = new Query(data.getPayload());

    // Set the type to Popular or Recent if specified
    // Results will be Mixed by default.
    if (data.getParameter("type") == "Popular")
        query.setResultType(Query.POPULAR);
    if (data.getParameter("type") == "Recent")
        query.setResultType(Query.RECENT);

    // Get lang string
    String langCode = (String) data.getParameter("lang");

    // Verify the validity of the language code and add it to the query if it's valid
    if (validateLangCode(langCode))
        query.setLang(langCode);

    // Get date strings
    String sinceString = (String) data.getParameter("since");
    String untilString = (String) data.getParameter("until");

    // Verify the format of the date strings and set the parameters to query if correctly given
    if (validateDateFormat(untilString))
        query.setUntil(untilString);
    if (validateDateFormat(sinceString))
        query.setSince(sinceString);

    // Get GeoLocation
    if (data.getParameter("address") != null) {
        String address = (String) data.getParameter("address");
        double radius = (double) data.getParameter("radius");
        if (radius <= 0)
            radius = 10;
        Query.Unit unit = Query.MILES;
        if (data.getParameter("unit") == "km")
            unit = Query.KILOMETERS;
        GeoLocation geoLocation;
        try {
            double[] coordinates = getGeocode(address);
            geoLocation = new GeoLocation(coordinates[0], coordinates[1]);
        } catch (Exception e) {
            String errorData = generateError(e.getMessage());
            logger.error(errorData);
            return errorData;
        }

        query.geoCode(geoLocation, radius, String.valueOf(unit));

    }

    // Get the number of tweets from count parameter, and set it to default = 15 if not specified
    int numberOfTweets;
    try {
        numberOfTweets = (int) data.getParameter("count");
    } catch (NullPointerException e) {
        numberOfTweets = 15;
    }

    // Generate an ArrayList of the wanted number of tweets, and handle possible errors.
    // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed
    ArrayList<Status> allTweets;
    Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter);
    String tweetsDataDisc = tweetsData.getDiscriminator();
    if (Discriminators.Uri.ERROR.equals(tweetsDataDisc))
        return tweetsData.asPrettyJson();

    else {
        allTweets = (ArrayList<Status>) tweetsData.getPayload();
    }

    // Initialize StringBuilder to hold the final string
    StringBuilder builder = new StringBuilder();

    // Append each Status (each tweet) to the initialized builder
    for (Status status : allTweets) {
        String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : "
                + status.getText() + "\n";
        builder.append(single);
    }

    // Output results
    Container container = new Container();
    container.setText(builder.toString());
    Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container);
    return output.asPrettyJson();
}

From source file:org.apache.apex.malhar.contrib.twitter.TwitterSampleInput.java

License:Apache License

/**
 * Allow derived classes to customize the configuration
 *//* www  . j ava 2 s  .  c  o m*/
protected ConfigurationBuilder setupConfigurationBuilder() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(debug).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
    return cb;
}

From source file:org.apache.blur.demo.twitter.TwitterSearchQueueReader.java

License:Apache License

public TwitterSearchQueueReader(BlurIndex index, ShardContext shardContext) {
    super(index, shardContext);
    twitter = new TwitterFactory(new ConfigurationBuilder().build()).getInstance();

    try {/*from w w w  .j a v  a 2  s. c  o  m*/
        OAuth2Token token = twitter.getOAuth2Token();
    } catch (TwitterException e) {
        throw new RuntimeException("Unable to connect to twitter.", e);
    }
    searchCriteria = _tableContext.getDescriptor().getTableProperties().get(TWITTER_SEARCH_CRITERIA_KEY);
    tableName = _tableContext.getTable();

    if (searchCriteria == null) {
        throw new RuntimeException("Twitter search criteria cannot be null.");
    }
    log.info("Initialized with search criteria[" + searchCriteria + "]");
}

From source file:org.apache.blur.demo.twitter.Whiteboard.java

License:Apache License

/**
 * @param args/* w ww .j  av a  2 s.  co  m*/
 * @throws TwitterException
 */
public static void main(String[] args) throws TwitterException {
    Twitter twitter = new TwitterFactory(new ConfigurationBuilder().build()).getInstance();
    OAuth2Token token = twitter.getOAuth2Token();
    System.out.println(token.getTokenType());

    try {
        Query query = new Query("Apache");
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());

            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }

}