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:org.jraf.irondad.handler.twitter.links.TwitterLinksHandler.java

License:Open Source License

private static Twitter getTwitter(HandlerContext handlerContext) {
    Twitter res = (Twitter) handlerContext.get("twitter");
    if (res == null) {
        TwitterLinksHandlerConfig twitterLinksHandlerConfig = (TwitterLinksHandlerConfig) handlerContext
                .getHandlerConfig();//from   ww w  .j a v a 2s .  c om
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey(twitterLinksHandlerConfig.getOauthConsumerKey());
        configurationBuilder.setOAuthConsumerSecret(twitterLinksHandlerConfig.getOauthConsumerSecret());
        configurationBuilder.setOAuthAccessToken(twitterLinksHandlerConfig.getOauthAccessToken());
        configurationBuilder.setOAuthAccessTokenSecret(twitterLinksHandlerConfig.getOauthAccessTokenSecret());
        TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());
        res = twitterFactory.getInstance();

        handlerContext.put("twitter", res);
    }
    return res;
}

From source file:org.keycloak.examples.broker.twitter.TwitterShowUserServlet.java

License:Apache License

@Override
protected void doGet(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    TwitterOAuthResponse twitterOAuthResponse = getTwitterOAuthResponse(request);
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey(this.identityProvider.getConfig().get("clientId"))
            .setOAuthConsumerSecret(this.identityProvider.getConfig().get("clientSecret"))
            .setOAuthAccessToken(twitterOAuthResponse.getToken())
            .setOAuthAccessTokenSecret(twitterOAuthResponse.getTokenSecret());

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

    try {
        User user = twitter.users().showUser(twitterOAuthResponse.getScreenName());

        response.setContentType(MediaType.APPLICATION_JSON);

        PrintWriter writer = response.getWriter();

        writer.println(new ObjectMapper().writeValueAsString(user));

        writer.flush();
    } catch (TwitterException e) {
        throw new RuntimeException("Could not load social profile.", e);
    }
}

From source file:org.komusubi.feeder.sns.twitter.Twitter4j.java

License:Apache License

/**
 * 
 * @param prefix in property key
 */
public Twitter4j(ScrapeType scrapeType) {
    this(new TwitterFactory(scrapeType.name().toLowerCase()).getInstance());
}

From source file:org.loklak.harvester.TwitterAPI.java

License:Open Source License

private static TwitterFactory getUserTwitterFactory(String accessToken, String accessTokenSecret) {
    if (accessToken == null || accessToken.length() == 0 || accessTokenSecret == null
            || accessTokenSecret.length() == 0)
        return null;
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(DAO.getConfig("client.twitterConsumerKey", ""))
            .setOAuthConsumerSecret(DAO.getConfig("client.twitterConsumerSecret", ""))
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);//from w ww  .  j  ava  2 s . c  o m
    return new TwitterFactory(cb.build());
}

From source file:org.loklak.scraper.TwitterRiver.java

License:Apache License

/**
 * Get users id of each list to stream them.
 * @param tUserlists List of user list. Should be a public list.
 * @return//from w w w  .j  a va 2  s  . com
 */
private long[] getUsersListMembers(String[] tUserlists) {
    logger.debug("Fetching user id of given lists");
    List<Long> listUserIdToFollow = new ArrayList<Long>();
    Configuration cb = buildTwitterConfiguration();
    Twitter twitterImpl = new TwitterFactory(cb).getInstance();

    //For each list given in parameter
    for (String listId : tUserlists) {
        logger.debug("Adding users of list {} ", listId);
        String[] splitListId = listId.split("/");
        try {
            long cursor = -1;
            PagableResponseList<User> itUserListMembers;
            do {
                itUserListMembers = twitterImpl.getUserListMembers(splitListId[0], splitListId[1], cursor);
                for (User member : itUserListMembers) {
                    long userId = member.getId();
                    listUserIdToFollow.add(userId);
                }
            } while ((cursor = itUserListMembers.getNextCursor()) != 0);

        } catch (TwitterException te) {
            logger.error("Failed to get list members for : {}", listId, te);
        }
    }

    //Just casting from Long to long
    long ret[] = new long[listUserIdToFollow.size()];
    int pos = 0;
    for (Long userId : listUserIdToFollow) {
        ret[pos] = userId;
        pos++;
    }
    return ret;
}

From source file:org.luwrain.app.twitter.Auth.java

License:Open Source License

Auth(String consumerKey, String consumerSecret) throws TwitterException {
    NullCheck.notEmpty(consumerKey, "consumerKey");
    NullCheck.notNull(consumerSecret, "consumerSecret");
    conf = new ConfigurationLuwrain(consumerKey, consumerSecret, null, null);
    twitter = new TwitterFactory(conf).getInstance();
    requestToken = twitter.getOAuthRequestToken();
}

From source file:org.luwrain.app.twitter.Auth.java

License:Open Source License

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("You must provide consumer key and consumer secret");
        return;/*from   w  w  w. j  a  va 2 s . c  o m*/
    }
    Twitter twitter = null;
    try {
        ConfigurationLuwrain conf = new ConfigurationLuwrain(args[0], args[1], null, null);
        twitter = new TwitterFactory(conf).getInstance();
        final RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        AccessToken accessToken = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (accessToken == null) {
            System.out.println("Open the following URL and grant access to your account:");
            System.out.println(requestToken.getAuthorizationURL());
            System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
            try {
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                }
            } catch (TwitterException te) {
                if (te.getStatusCode() == 401) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        } //while();
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());
    } catch (IllegalStateException e) {
        if (!twitter.getAuthorization().isEnabled())
            System.out.println("OAuth consumer key/secret is not set.");
        else
            e.printStackTrace();
    } catch (TwitterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.luwrain.app.twitter.Base.java

License:Open Source License

static private Twitter createTwitter(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret) {
    final ConfigurationLuwrain conf = new ConfigurationLuwrain(consumerKey, consumerSecret, accessToken,
            accessTokenSecret);//from w  w w  .  j ava  2s  .c  om
    final Twitter twitter = new TwitterFactory(conf).getInstance();
    if (twitter == null)
        return null;
    if (!twitter.getAuthorization().isEnabled()) {
        Log.error("twitter", "no enabled authorization");
        return null;
    }
    return twitter;
}

From source file:org.manalith.ircbot.plugin.tweetreader.TweetReader.java

License:Open Source License

private void initTwitter4j() throws TwitterException {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    Configuration config = builder.setDebugEnabled(false).setJSONStoreEnabled(true)
            .setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).build();

    tweet = new TwitterFactory(config).getInstance();
    requestToken = tweet.getOAuthRequestToken();
}

From source file:org.mariotaku.twidere.util.Utils.java

License:Open Source License

@Nullable
public static Twitter getTwitterInstance(final Context context, final long accountId,
        final boolean includeEntities, final boolean includeRetweets) {
    if (context == null)
        return null;
    final TwidereApplication app = TwidereApplication.getInstance(context);
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int connection_timeout = prefs.getInt(KEY_CONNECTION_TIMEOUT, 10) * 1000;
    final boolean enableGzip = prefs.getBoolean(KEY_GZIP_COMPRESSING, true);
    final boolean ignoreSslError = prefs.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enableProxy = prefs.getBoolean(KEY_ENABLE_PROXY, false);
    // Here I use old consumer key/secret because it's default key for older
    // versions//www. j a v a  2s .  c om
    final ParcelableCredentials credentials = ParcelableCredentials.getCredentials(context, accountId);
    if (credentials == null)
        return null;
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(app));
    cb.setHttpClientFactory(new OkHttpClientFactory(context));
    cb.setHttpConnectionTimeout(connection_timeout);
    cb.setGZIPEnabled(enableGzip);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeCards(true);
    cb.setCardsPlatform("Android-12");
    //            cb.setModelVersion(7);
    if (enableProxy) {
        final String proxy_host = prefs.getString(KEY_PROXY_HOST, null);
        final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1"));
        if (!isEmpty(proxy_host) && proxy_port > 0) {
            cb.setHttpProxyHost(proxy_host);
            cb.setHttpProxyPort(proxy_port);
        }
    }
    final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
    final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
    final String apiUrlFormat = credentials.api_url_format;
    final String consumerKey = trim(credentials.consumer_key);
    final String consumerSecret = trim(credentials.consumer_secret);
    final boolean sameOAuthSigningUrl = credentials.same_oauth_signing_url;
    final boolean noVersionSuffix = credentials.no_version_suffix;
    if (!isEmpty(apiUrlFormat)) {
        final String versionSuffix = noVersionSuffix ? null : "/1.1/";
        cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix));
        cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
        cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix));
        cb.setOAuthAuthorizationURL(getApiUrl(apiUrlFormat, null, null));
        if (!sameOAuthSigningUrl) {
            cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
            cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
            cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
        }
    }
    setClientUserAgent(context, consumerKey, consumerSecret, cb);

    cb.setIncludeEntitiesEnabled(includeEntities);
    cb.setIncludeRTsEnabled(includeRetweets);
    cb.setIncludeReplyCountEnabled(true);
    cb.setIncludeDescendentReplyCountEnabled(true);
    switch (credentials.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
            cb.setOAuthConsumerKey(consumerKey);
            cb.setOAuthConsumerSecret(consumerSecret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        }
        final String token = credentials.oauth_token;
        final String tokenSecret = credentials.oauth_token_secret;
        if (isEmpty(token) || isEmpty(tokenSecret))
            return null;
        return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret));
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = credentials.screen_name;
        final String username = credentials.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = credentials.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password));
    }
    case Accounts.AUTH_TYPE_TWIP_O_MODE: {
        return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization());
    }
    default: {
        return null;
    }
    }
}