Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory(String configTreePath) 

Source Link

Document

Creates a TwitterFactory with a specified config tree

Usage

From source file:oauth.AppOAuth.java

License:Apache License

public TwitterFactory loadOAuthUser(String endpoint, int TOTAL_JOBS, int JOB_NO)
        throws ClassNotFoundException, SQLException, TwitterException {

    MysqlDB DB = new MysqlDB();

    // System.out.println("DEBUG AppOAuth.java");
    // get OAuth cradentials by calling DB's loadOAuthUser(endpoint)
    ConstVars StaticVars = DB.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);

    String consumer_key = StaticVars.consumer_key;
    String consumer_secret = StaticVars.consumer_secret;
    String user_token = StaticVars.user_token;
    String user_secret = StaticVars.user_secret;

    RemainingCalls = StaticVars.Remaining;
    screen_name = StaticVars.screen_name;

    // working with twitter4j.properties
    // Twitter twitter = new TwitterFactory().getInstance(); 
    // initialize Twitter OAuth
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true).setDebugEnabled(true).setOAuthConsumerKey(consumer_key)
            .setOAuthConsumerSecret(consumer_secret).setOAuthAccessToken(user_token)
            .setOAuthAccessTokenSecret(user_secret);

    TwitterFactory tf = new TwitterFactory(cb.build());
    return tf;//www.ja v a 2  s. c o m
}

From source file:oauth.AppOAuth.java

License:Apache License

public TwitterFactory loadOAuthUser(String endpoint, String consumer_key, String consumer_secret,
        String user_token, String user_secret) throws ClassNotFoundException, SQLException, TwitterException {

    // Send OAuth credentials and get rate limit of endpoint
    String[] args = { endpoint, consumer_key, consumer_secret, user_token, user_secret };
    StaticVars = GetRateLimitStatus.getRateLimit(args);

    RemainingCalls = StaticVars.Remaining;

    // working with twitter4j.properties
    // Twitter twitter = new TwitterFactory().getInstance(); 
    // initialize Twitter OAuth
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true).setDebugEnabled(true).setOAuthConsumerKey(consumer_key)
            .setOAuthConsumerSecret(consumer_secret).setOAuthAccessToken(user_token)
            .setOAuthAccessTokenSecret(user_secret);

    TwitterFactory tf = new TwitterFactory(cb.build());
    return tf;/*www.j a  v  a 2s.c o  m*/
}

From source file:OAuth.MyOwnTwitterFactory.java

License:Open Source License

public Twitter createOneTwitterInstance() {
    Twitter twitter;/*w w w . j  ava 2 s. c o  m*/
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(APIkeys.getTwitterAPIKey());
    builder.setOAuthConsumerSecret(APIkeys.getTwitterAPISecret());
    builder.setOAuthAccessToken("31805620-QQy8TFFDKRxWyOUVnY08UcxT5bzrFhRWUa0A3lEW3");
    builder.setOAuthAccessTokenSecret("iJuCkdgrfIpGn5odyF2evMSvAsovreeEV6cZU5ihVVI7j");
    Configuration configuration = builder.build();
    TwitterFactory factory = new TwitterFactory(configuration);
    twitter = factory.getInstance();

    return twitter;

}

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();//  www.j  a v  a  2  s . 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 {/* ww w .ja v  a 2  s .  c om*/
        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.  j  a va2 s  .  c om
    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;//from w  w  w  .ja v a2 s. c  om
    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./*  w w w.j a v  a2  s  . co 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.asterix.external.util.TwitterUtil.java

License:Apache License

public static Twitter getTwitterService(Map<String, String> configuration) {
    ConfigurationBuilder cb = getAuthConfiguration(configuration);
    TwitterFactory tf = null;//from   ww w.ja  v a 2s  . co m
    try {
        tf = new TwitterFactory(cb.build());
    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.WARNING)) {
            StringBuilder builder = new StringBuilder();
            builder.append("Twitter Adapter requires the following config parameters\n");
            builder.append(AuthenticationConstants.OAUTH_CONSUMER_KEY + "\n");
            builder.append(AuthenticationConstants.OAUTH_CONSUMER_SECRET + "\n");
            builder.append(AuthenticationConstants.OAUTH_ACCESS_TOKEN + "\n");
            builder.append(AuthenticationConstants.OAUTH_ACCESS_TOKEN_SECRET + "\n");
            LOGGER.warning(builder.toString());
            LOGGER.warning(
                    "Unable to configure Twitter adapter due to incomplete/incorrect authentication credentials");
            LOGGER.warning(
                    "For details on how to obtain OAuth authentication token, visit https://dev.twitter.com/oauth/overview/application-owner-access-tokens");
        }
    }
    Twitter twitter = tf.getInstance();
    return twitter;
}