Example usage for twitter4j.conf ConfigurationBuilder setHttpProxyPort

List of usage examples for twitter4j.conf ConfigurationBuilder setHttpProxyPort

Introduction

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

Prototype

public ConfigurationBuilder setHttpProxyPort(int httpProxyPort) 

Source Link

Usage

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/*from   w  w  w .ja v  a 2s.c o m*/
    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;
    }
    }
}

From source file:org.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Connects to Twitter//from   w ww.java  2  s.co  m
 * @param accessKey The access key provided by Twitter
 * @param accessSecret The access secret provided by Twitter
 * @throws ConnectionException when the connection fails
 */
@Connect
public void connect(@ConnectionKey String accessKey, String accessSecret) throws ConnectionException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setUseSSL(useSSL);
    cb.setHttpProxyHost(proxyHost);
    cb.setHttpProxyPort(proxyPort);
    cb.setHttpProxyUser(proxyUsername);
    cb.setHttpProxyPassword(proxyPassword);

    HttpClientHiddenConstructionArgument.setUseMule(true);
    twitter = new TwitterFactory(cb.build()).getInstance();

    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    if (accessKey != null) {
        twitter.setOAuthAccessToken(new AccessToken(accessKey, accessSecret));
        setAccessToken(accessKey);
        setAccessTokenSecret(accessSecret);
    }
}

From source file:streamflow.spout.twitter.TwitterSampleSpout.java

License:Apache License

@Override
public void open(Map config, TopologyContext context, SpoutOutputCollector collector) {
    this.collector = collector;

    logger.info(/*from   w  ww  .j  a  va  2  s  .co m*/
            "Twitter Sampler Started: Consumer Key = " + consumerKey + ", Consumer Secret = " + consumerSecret
                    + ", Access Token = " + accessToken + ", Access Token Secret = " + accessTokenSecret);

    if (StringUtils.isNotBlank(consumerKey) && StringUtils.isNotBlank(consumerSecret)
            && StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(accessTokenSecret)) {
        // Build the twitter config to authenticate the requests
        ConfigurationBuilder twitterConfig = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey)
                .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
                .setOAuthAccessTokenSecret(accessTokenSecret).setJSONStoreEnabled(true)
                .setIncludeEntitiesEnabled(true).setIncludeEntitiesEnabled(true);

        // Add the proxy settings to the Twitter config if they were specified
        if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
            try {
                twitterConfig.setHttpProxyPort(proxyPort).setHttpProxyHost(proxyHost);
            } catch (Exception ex) {
            }
        }

        // Status listener which handle the status events and add them to the queue
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                queue.offer(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                logger.debug("Twitter Deletion Notice: " + statusDeletionNotice.getUserId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                logger.debug("Twitter On Track Limitation Notice: Number Of Limited Statuses"
                        + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                logger.debug("Twitter Scrub Geo: UserID = " + userId + ", UpToStatusId = " + upToStatusId);
            }

            @Override
            public void onException(Exception exception) {
                logger.debug("Twitter Exception: " + exception.getMessage());
            }

            @Override
            public void onStallWarning(StallWarning stallWarning) {
                logger.debug("Twitter Stall Warning: " + stallWarning.toString());
            }
        };

        TwitterStreamFactory twitterFactory = new TwitterStreamFactory(twitterConfig.build());
        twitterStream = twitterFactory.getInstance();
        twitterStream.addListener(listener);
        twitterStream.sample();

        logger.info("Twitter Sample Stream Initialized");

    } else {
        logger.info("Twitter Sampler missing required OAuth properties. "
                + "Pleast check your settings and try again.");
    }
}