Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

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

Prototype

public Configuration build() 

Source Link

Usage

From source file:org.getlantern.firetweet.util.Utils.java

License:Open Source License

public static HttpClientWrapper getHttpClient(final Context context, final int timeoutMillis,
        final boolean ignoreSslError, final Proxy proxy, final HostAddressResolverFactory resolverFactory,
        final String userAgent, final boolean twitterClientHeader) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeoutMillis);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeTwitterClientHeader(twitterClientHeader);
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress address = proxy.address();
        if (address instanceof InetSocketAddress) {
            cb.setHttpProxyHost(((InetSocketAddress) address).getHostName());
            cb.setHttpProxyPort(((InetSocketAddress) address).getPort());
        }/*from   w  w w . ja v  a2  s.  co  m*/
    }
    cb.setHostAddressResolverFactory(resolverFactory);
    if (userAgent != null) {
        cb.setHttpUserAgent(userAgent);
    }
    cb.setHttpClientFactory(new OkHttpClientFactory(context));
    return new HttpClientWrapper(cb.build());
}

From source file:org.getlantern.firetweet.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context,
        final ParcelableCredentials account) {
    if (context == null || account == null)
        return null;
    switch (account.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE);
        // Here I use old consumer key/secret because it's default
        // key for older
        // versions
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        if (!isEmpty(account.api_url_format)) {
            final String versionSuffix = account.no_version_suffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(account.api_url_format, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(account.api_url_format, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(account.api_url_format, "upload", versionSuffix));
            cb.setOAuthAuthorizationURL(getApiUrl(account.api_url_format, null, null));
            if (!account.same_oauth_signing_url) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }/*  w  ww  . ja v a2 s  .  c  o m*/
        }
        if (!isEmpty(account.consumer_key) && !isEmpty(account.consumer_secret)) {
            cb.setOAuthConsumerKey(account.consumer_key);
            cb.setOAuthConsumerSecret(account.consumer_secret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        }
        final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
        auth.setOAuthAccessToken(new AccessToken(account.oauth_token, account.oauth_token_secret));
        return auth;
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = account.screen_name;
        final String username = account.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = account.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new BasicAuthorization(loginName, password);
    }
    default: {
        return null;
    }
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context, final long accountId) {

    final String where = Expression.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL();
    final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI,
            Accounts.COLUMNS, where, null, null);
    if (c == null)
        return null;
    try {/*from ww  w.  jav  a2  s . co  m*/
        if (!c.moveToFirst())
            return null;

        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
        case Accounts.AUTH_TYPE_OAUTH:
        case Accounts.AUTH_TYPE_XAUTH: {
            final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                    Context.MODE_PRIVATE);
            // Here I use old consumer key/secret because it's default
            // key for older
            // versions
            final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
            final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
            final ConfigurationBuilder cb = new ConfigurationBuilder();
            final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT));
            final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY)));
            final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET)));
            final boolean sameOAuthSigningUrl = c
                    .getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1;
            if (!isEmpty(apiUrlFormat)) {
                cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", "/1.1/"));
                cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
                cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", "/1.1/"));
                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);
                }
            }
            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 OAuthAuthorization auth = new OAuthAuthorization(cb.build());
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            auth.setOAuthAccessToken(new AccessToken(token, tokenSecret));
            return auth;
        }
        case Accounts.AUTH_TYPE_BASIC: {
            final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME));
            final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME));
            final String loginName = username != null ? username : screenName;
            final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD));
            if (isEmpty(loginName) || isEmpty(password))
                return null;
            return new BasicAuthorization(loginName, password);
        }
        default: {
            return null;
        }
        }
    } finally {
        c.close();
    }
}

From source file:org.getlantern.firetweet.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 FiretweetApplication app = FiretweetApplication.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 2  s.  co m*/
    final ParcelableCredentials credentials = ParcelableCredentials.getCredentials(context, accountId);
    if (credentials == null)
        return null;
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHostAddressResolverFactory(new FiretweetHostResolverFactory(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);
        }
    }
    if (TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret)) {
        setMockOfficialUserAgent(context, cb);
    } else {
        setUserAgent(context, 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;
    }
    }
}

From source file:org.glassfish.jersey.sample.sse.TwitterBean.java

License:Open Source License

/**
 * Since twitter uses the v1.1 API we use twitter4j to get
 * the search results using OAuth/* w  w w  .  j  ava 2  s . c  o  m*/
 * @return a JsonArray containing tweets
 * @throws TwitterException
 * @throws IOException
 */
public JsonArray getFeedData() throws TwitterException, IOException {

    Properties prop = new Properties();
    // try {
    //load a properties file
    prop.load(this.getClass().getResourceAsStream("twitter4j.properties"));

    //get the property value and print it out
    String consumerKey = prop.getProperty("oauth.consumerKey");
    String consumerSecret = prop.getProperty("oauth.consumerSecret");
    String accessToken = prop.getProperty("oauth.accessToken");
    String accessTokenSecret = prop.getProperty("oauth.accessTokenSecret");
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    Query query = new Query("glassfish");
    QueryResult result = twitter.search(query);

    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    for (Status status : result.getTweets()) {
        jsonArrayBuilder.add(Json.createObjectBuilder().add("text", status.getText()).add("created_at",
                status.getCreatedAt().toString()));

        System.out.println(
                "@" + status.getUser().getScreenName() + ":" + status.getText() + status.getCreatedAt());
    }

    return jsonArrayBuilder.build();
}

From source file:org.graylog2.inputs.twitter.TwitterTransport.java

License:Open Source License

@Override
public void launch(final MessageInput input) throws MisfireException {
    final ConfigurationBuilder cb = new ConfigurationBuilder()
            .setOAuthConsumerKey(configuration.getString(CK_OAUTH_CONSUMER_KEY))
            .setOAuthConsumerSecret(configuration.getString(CK_OAUTH_CONSUMER_SECRET))
            .setOAuthAccessToken(configuration.getString(CK_OAUTH_ACCESS_TOKEN))
            .setOAuthAccessTokenSecret(configuration.getString(CK_OAUTH_ACCESS_TOKEN_SECRET))
            .setJSONStoreEnabled(true);//  w w w  .j  av a 2 s . com

    final StatusListener listener = new StatusListener() {
        public void onStatus(final Status status) {
            try {
                input.processRawMessage(createMessageFromStatus(status));
            } catch (IOException e) {
                LOG.debug("Error while processing tweet status", e);
            }
        }

        private RawMessage createMessageFromStatus(final Status status) throws IOException {
            return new RawMessage(TwitterObjectFactory.getRawJSON(status).getBytes(StandardCharsets.UTF_8));
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onException(final Exception ex) {
            LOG.error("Error while reading Twitter stream", ex);
        }

        @Override
        public void onScrubGeo(long lon, long lat) {
        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {
            LOG.info("Stall warning: {} ({}% full)", stallWarning.getMessage(), stallWarning.getPercentFull());
        }
    };

    final String[] track = Iterables.toArray(
            Splitter.on(',').omitEmptyStrings().trimResults().split(configuration.getString(CK_KEYWORDS)),
            String.class);
    final FilterQuery filterQuery = new FilterQuery();
    filterQuery.track(track);

    if (twitterStream == null) {
        twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    }

    twitterStream.addListener(listener);
    twitterStream.filter(filterQuery);
}

From source file:org.hubiquitus.hubotsdk.adapters.HTwitterAdapterInbox.java

License:Open Source License

/**
 * Function for tweet Streaming//www . j a  va  2  s  .c  o m
 */
private void stream() {
    /**
     * Configuration for access to twitter account
     */
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setUseSSL(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(twitterAccessToken)
            .setOAuthAccessTokenSecret(twitterAccessTokenSecret);

    //Instantiation of tweet stream
    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener = new StatusListener() {
        public void onStatus(Status tweet) {
            String lang = tweet.getUser().getLang();
            //Set the filter for the language
            if ((langFilter == null) || (lang != null && lang.equalsIgnoreCase(langFilter))) {
                HMessage message = transformtweet(tweet);
                put(message);
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onScrubGeo(long userId, long upToStatusId) {
        }

        public void onException(Exception ex) {
            log.info("message: ", ex);
        }
    };

    FilterQuery fq = new FilterQuery();
    fq.track(tags.split(","));
    twitterStream.addListener(listener);
    twitterStream.filter(fq);
}

From source file:org.hubiquitus.hubotsdk.adapters.HTwitterAdapterOutbox.java

License:Open Source License

@Override
public void start() {

    log.info("Twitter adapter outbox '" + actor + "' starting...");

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setUseSSL(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(twitterAccessToken)
            .setOAuthAccessTokenSecret(twitterAccessTokenSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();/*from w  w  w .j  a va 2s  .com*/

    log.info("Twitter adapter outbox '" + actor + "' started.");
}

From source file:org.jraf.irondad.handler.twitter.follow.TwitterFollowHandler.java

License:Open Source License

private static Twitter getTwitter(HandlerContext handlerContext) {
    Twitter res = (Twitter) handlerContext.get("twitter");
    if (res == null) {
        TwitterFollowHandlerConfig twitterFollowHandlerConfig = (TwitterFollowHandlerConfig) handlerContext
                .getHandlerConfig();/*from www .  jav a  2 s  .co  m*/
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey(twitterFollowHandlerConfig.getOauthConsumerKey());
        configurationBuilder.setOAuthConsumerSecret(twitterFollowHandlerConfig.getOauthConsumerSecret());
        configurationBuilder.setOAuthAccessToken(twitterFollowHandlerConfig.getOauthAccessToken());
        configurationBuilder.setOAuthAccessTokenSecret(twitterFollowHandlerConfig.getOauthAccessTokenSecret());
        TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());
        res = twitterFactory.getInstance();

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

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  va  2s.co  m*/
        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;
}