Example usage for twitter4j.conf ConfigurationBuilder setHttpProxyHost

List of usage examples for twitter4j.conf ConfigurationBuilder setHttpProxyHost

Introduction

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

Prototype

public ConfigurationBuilder setHttpProxyHost(String httpProxyHost) 

Source Link

Usage

From source file:cojoytuerto.TAuth.java

public TAuth() throws IOException, TwitterException { //Constructor de la clase
    File file = new File("auth_file.txt");
    if (!file.exists()) {

        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        configBuilder.setDebugEnabled(true).setOAuthConsumerKey("wCWSOW8xHlxfQq24kSxXuXNm9")
                .setOAuthConsumerSecret("5B1R4bxZv7TcO7Vmq3NvhM3Bo3YcO0qCIJP2vDD9HnOaPL63YD");
        configBuilder.setHttpProxyHost("127.0.0.1");
        configBuilder.setUseSSL(true);//from  ww w  .  j av  a 2 s  .  c o m
        configBuilder.setHttpProxyPort(3128);
        Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        String url = null;

        do {
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                System.out.println("Request Token obtenido con xito.");
                System.out.println("Request Token: " + requestToken.getToken());
                System.out.println("Request Token secret: " + requestToken.getTokenSecret());
                url = requestToken.getAuthorizationURL();
                url = url.replace("http://", "https://");
                System.out.println("URL:");
                System.out.println(url);
            } catch (TwitterException ex) {
                Logger.getLogger(TAuth.class.getName()).log(Level.SEVERE, null, ex);
            }
            BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in));
            //Abro el navegador. Firefox, en este caso.
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("firefox " + url);
            } catch (Exception e) {
            }
            //Nos avisa de que introduciremos el PIN a continuacin

            System.out.print("Introduce el PIN del navegador y pulsa intro.nn PIN: ");
            //Leemos el PIN
            //                String pin = lectorTeclado.readLine();
            String pin = JOptionPane.showInputDialog(null,
                    "Introduce el PIN del navegador y pulsa intro.nn PIN: ");
            if (pin.length() > 0) {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken);
            }
        } while (accessToken == null);

        System.out.println("nnAccess Tokens obtenidos con xito.");
        System.out.println("Access Token: " + accessToken.getToken());
        System.out.println("Access Token secret: " + accessToken.getTokenSecret());
        FileOutputStream fileOS = null;
        //            File file;
        String content = accessToken.getToken() + "\n" + accessToken.getTokenSecret();
        try {
            //                file = new File("auth_file.txt");
            fileOS = new FileOutputStream(file);
            //Si el archivo no existe, se crea
            if (!file.exists()) {
                file.createNewFile();
            }
            //Se obtiene el contenido en Bytes
            byte[] contentInBytes = content.getBytes();
            fileOS.write(contentInBytes);
            fileOS.flush();
            fileOS.close();
            System.out.println("Escritura realizada con xito.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOS != null) {
                    fileOS.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.dwdesign.tweetings.activity.TwitterLoginActivity.java

License:Open Source License

private ConfigurationBuilder setAPI(ConfigurationBuilder cb) {
    final SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final boolean enable_gzip_compressing = preferences.getBoolean(PREFERENCE_KEY_GZIP_COMPRESSING, false);
    final boolean ignore_ssl_error = preferences.getBoolean(PREFERENCE_KEY_IGNORE_SSL_ERROR, false);
    final boolean enable_proxy = preferences.getBoolean(PREFERENCE_KEY_ENABLE_PROXY, false);
    final String consumer_key = preferences.getString(PREFERENCE_KEY_CONSUMER_KEY, CONSUMER_KEY);
    final String consumer_secret = preferences.getString(PREFERENCE_KEY_CONSUMER_SECRET, CONSUMER_SECRET);
    setUserAgent(this, cb);
    //if (!isNullOrEmpty(rest_base_url)) {
    cb.setRestBaseURL(DEFAULT_REST_BASE_URL);
    //}//  www . ja  v  a 2  s .  c o  m
    //if (!isNullOrEmpty(search_base_url)) {
    cb.setSearchBaseURL(DEFAULT_SEARCH_BASE_URL);
    //}
    if (isNullOrEmpty(consumer_key) || isNullOrEmpty(consumer_secret)) {
        cb.setOAuthConsumerKey(CONSUMER_KEY);
        cb.setOAuthConsumerSecret(CONSUMER_SECRET);
    } else {
        cb.setOAuthConsumerKey(consumer_key);
        cb.setOAuthConsumerSecret(consumer_secret);
    }
    cb.setGZIPEnabled(enable_gzip_compressing);
    if (enable_proxy) {
        final String proxy_host = preferences.getString(PREFERENCE_KEY_PROXY_HOST, null);
        final int proxy_port = parseInt(preferences.getString(PREFERENCE_KEY_PROXY_PORT, "-1"));
        if (!isNullOrEmpty(proxy_host) && proxy_port > 0) {
            cb.setHttpProxyHost(proxy_host);
            cb.setHttpProxyPort(proxy_port);
        }

    }
    return cb;
}

From source file:com.dwdesign.tweetings.util.Utils.java

License:Open Source License

public static Twitter getTwitterInstance(final Context context, final long account_id,
        final boolean include_entities, final boolean include_rts, final boolean use_httpclient) {
    if (context == null)
        return null;
    final SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
            Context.MODE_PRIVATE);
    final boolean enable_gzip_compressing = preferences != null
            ? preferences.getBoolean(PREFERENCE_KEY_GZIP_COMPRESSING, true)
            : true;/*from   ww w. ja  v  a  2 s  .com*/
    final boolean ignore_ssl_error = preferences != null
            ? preferences.getBoolean(PREFERENCE_KEY_IGNORE_SSL_ERROR, false)
            : false;
    final boolean enable_proxy = preferences != null
            ? preferences.getBoolean(PREFERENCE_KEY_ENABLE_PROXY, false)
            : false;
    final String consumer_key = preferences != null
            ? preferences.getString(PREFERENCE_KEY_CONSUMER_KEY, CONSUMER_KEY)
            : CONSUMER_KEY;
    final String consumer_secret = preferences != null
            ? preferences.getString(PREFERENCE_KEY_CONSUMER_SECRET, CONSUMER_SECRET)
            : CONSUMER_SECRET;

    Twitter twitter = null;
    final StringBuilder where = new StringBuilder();
    where.append(Accounts.USER_ID + "=" + account_id);
    final Cursor cur = context.getContentResolver().query(Accounts.CONTENT_URI, Accounts.COLUMNS,
            where.toString(), null, null);
    if (cur != null) {
        if (cur.getCount() == 1) {
            cur.moveToFirst();
            final ConfigurationBuilder cb = new ConfigurationBuilder();
            setUserAgent(context, cb);
            if (use_httpclient) {
                cb.setHttpClientImplementation(HttpClientImpl.class);
            }
            cb.setGZIPEnabled(enable_gzip_compressing);
            if (enable_proxy) {
                final String proxy_host = preferences.getString(PREFERENCE_KEY_PROXY_HOST, null);
                final int proxy_port = parseInt(preferences.getString(PREFERENCE_KEY_PROXY_PORT, "-1"));
                if (!isNullOrEmpty(proxy_host) && proxy_port > 0) {
                    cb.setHttpProxyHost(proxy_host);
                    cb.setHttpProxyPort(proxy_port);
                }

            }
            final String rest_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.REST_BASE_URL));
            final String signing_rest_base_url = cur
                    .getString(cur.getColumnIndexOrThrow(Accounts.SIGNING_REST_BASE_URL));
            final String search_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.SEARCH_BASE_URL));
            final String upload_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.UPLOAD_BASE_URL));
            final String oauth_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.OAUTH_BASE_URL));
            final String signing_oauth_base_url = cur
                    .getString(cur.getColumnIndexOrThrow(Accounts.SIGNING_OAUTH_BASE_URL));
            //if (!isNullOrEmpty(rest_base_url)) {
            cb.setRestBaseURL(DEFAULT_REST_BASE_URL);
            //}
            //if (!isNullOrEmpty(search_base_url)) {
            cb.setSearchBaseURL(DEFAULT_SEARCH_BASE_URL);
            //}
            cb.setIncludeEntitiesEnabled(include_entities);
            cb.setIncludeRTsEnabled(include_rts);

            switch (cur.getInt(cur.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
            case Accounts.AUTH_TYPE_OAUTH:
            case Accounts.AUTH_TYPE_XAUTH:
                if (isNullOrEmpty(consumer_key) || isNullOrEmpty(consumer_secret)) {
                    cb.setOAuthConsumerKey(CONSUMER_KEY);
                    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
                } else {
                    cb.setOAuthConsumerKey(consumer_key);
                    cb.setOAuthConsumerSecret(consumer_secret);
                }
                twitter = new TwitterFactory(cb.build()).getInstance(
                        new AccessToken(cur.getString(cur.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN)),
                                cur.getString(cur.getColumnIndexOrThrow(Accounts.TOKEN_SECRET))));
                break;
            case Accounts.AUTH_TYPE_BASIC:
                twitter = new TwitterFactory(cb.build()).getInstance(
                        new BasicAuthorization(cur.getString(cur.getColumnIndexOrThrow(Accounts.USERNAME)),
                                cur.getString(cur.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD))));
                break;
            default:
            }
        }
        cur.close();
    }
    return twitter;
}

From source file:com.dwdesign.tweetings.util.Utils.java

License:Open Source License

public static HttpClientWrapper getHttpClient(final int timeout_millis, final boolean ignore_ssl_error,
        final Proxy proxy, final HostAddressResolver resolver, final String user_agent) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeout_millis);
    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());
        }/*  w w  w. j ava2 s.c  o m*/
    }
    // cb.setHttpClientImplementation(HttpClientImpl.class);
    return new HttpClientWrapper(cb.build());
}

From source file:crosstreams.twitter.TwitterStreamFileWriter.java

License:Mozilla Public License

/**
 * Start crawling tweets//from ww  w .j  a v  a 2s . c  o  m
 * @param args
 * @throws TwitterException
 */
public static void main(String[] args) throws TwitterException {

    System.err.println("### Twitter Stream Writer ###");
    System.err.println("Saves tweets from the Spritzer/Gardenhose Stream to a series of files");
    System.err.println(
            "Command: crosstreams.twitter.TwitterStreamFileWriter <saveFolder> <twitterusername> <twitterpassword> <numberoftweetstostoreperfile>(optional)");
    System.err.println("   saveFolder: Where the tweets will be downloaded to");
    System.err.println("   twitterusername: The username of the twitter account to use for downloading tweets");
    System.err.println("   twitterpassword: The password of the twitter account to use for downloading tweets");
    System.err.println(
            "   numberoftweetstostoreperfile: The total number of tweets to write to a file before closing that file and opening a new one (Integer) (defaults=1000000)");
    System.err.println("Optional System Properties (-D):");
    System.err.println("   http.proxyhost: The proxy host to use if needed");
    System.err.println("   http.proxyport: The proxy port to use if needed");
    System.err.println("   email: An email address to send alerts to if an error is encountered");
    System.err.println("   emailconf: An file containing the javax.mail configuration");
    System.err.println(
            "   emailonvalidate: true/false - should I send an email when a file is correctly validated rather than only when it fails? (default=false)");

    if (args.length <= 1 || args.length >= 5) {
        System.err.println("Example:");
        System.err.println(
                "java -Demail=\"MYEMAIL@HOST.COM\" -Demailconf=\"./javamail.conf\" -Demailonvalidate=\"true\" -jar TwitterStreamFileCrawler.jar ./ MYUSERNAME MYPASSWORD 100000");
        System.err.println("Don't forget to modify ./javamail.conf to contain your email server host");
        System.exit(0);
    }

    // user inputs
    String saveFolder = args[0];
    String username = args[1];
    String password = args[2];
    final int numberOfTweetsToStorePerFile;
    if (args.length > 2)
        numberOfTweetsToStorePerFile = Integer.parseInt(args[3]);
    else
        numberOfTweetsToStorePerFile = 1000000;
    String proxyhost = System.getProperty("http.proxyhost");
    String proxyport = System.getProperty("http.proxyport");
    final String email = System.getProperty("email");
    final String emailconf = System.getProperty("emailconf");

    // define the user account in use and proxy settings if needed
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    if (proxyhost != null && proxyport != null) {
        cb.setHttpProxyHost(proxyhost);
        cb.setHttpProxyPort(Integer.parseInt(proxyport));
    }
    cb.setUser(username);
    cb.setPassword(password);

    if (!saveFolder.endsWith("/") && !saveFolder.endsWith("\\")) {
        saveFolder = saveFolder + System.getProperty("file.separator");
    }
    final String finalSaveFolder = saveFolder;

    // Twitter4J Stream - the type of stream is set automatically, i.e. Gardenhose if you have it, Spritzer otherwise.
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    // The status listener is the important bit, this fires when a new tweet arrives.
    StatusListener listener = new StatusListener() {

        /** The status listener holds a writer to save content to **/
        BufferedWriter statusWriter = null; // the tweets go here
        BufferedWriter logWriter = null; // we write any delete requests or error messages here

        /** We store a fixed number of Tweets in each file **/
        int numberInThisFile = numberOfTweetsToStorePerFile;
        int numberPerFile = numberOfTweetsToStorePerFile;

        String currentFilename;
        int numerrors = 0;

        /**
         * A new tweet has arrived
         */
        public void onStatus(Status status) {
            if (numberInThisFile >= numberPerFile) {
                // closing and opening of new files
                try {
                    if (statusWriter != null) {

                        statusWriter.close();
                        logWriter.close();
                        validateJSONFile(currentFilename, numberPerFile);
                    }
                    Long currentTime = System.currentTimeMillis();

                    currentFilename = finalSaveFolder + currentTime.toString() + ".json.gz";
                    statusWriter = new BufferedWriter(new OutputStreamWriter(
                            new GZIPOutputStream(new FileOutputStream(currentFilename)), "UTF-8"));
                    logWriter = new BufferedWriter(new OutputStreamWriter(
                            new GZIPOutputStream(
                                    new FileOutputStream(finalSaveFolder + currentTime.toString() + ".log.gz")),
                            "UTF-8"));
                    numberInThisFile = 0;
                    numerrors = 0;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            numberInThisFile++;
            // write the JSON - note that I added the getJSON() method to the Twitter4J status object
            // this is why the Twitter4j sources are included rather than importing the jar.
            try {
                Object s = status.getJSON();
                statusWriter.write(status.getJSON().toString() + '\n');
                statusWriter.flush();
            } catch (Exception e) {
                e.printStackTrace();
                numerrors++;
                if (emailconf != null && email != null && numerrors < 5)
                    Mail.mail(emailconf, email, email, "Twitter Stream Writer Alert - Write Failed",
                            "An IOException was thrown when calling statusWriter.write()." + '\n'
                                    + e.getMessage() + '\n'
                                    + "The current file will be closed and a new file will be created.");
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            try {
                logWriter.write("DEL: " + statusDeletionNotice.getStatusId() + " "
                        + statusDeletionNotice.getUserId() + '\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            try {
                logWriter.write("LIMIT: " + numberOfLimitedStatuses + '\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void onScrubGeo(long userId, long upToStatusId) {
            try {
                logWriter.write("SCRUBGEO: " + userId + " " + upToStatusId + '\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void onException(Exception ex) {
            if (logWriter == null)
                return;
            try {
                logWriter.write("ERR: " + ex.getLocalizedMessage() + '\n');
                logWriter.flush();
                if (statusWriter != null) {
                    statusWriter.close();
                    statusWriter = null;
                    logWriter.close();
                    validateJSONFile(currentFilename, numberPerFile);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //ex.printStackTrace();
        }
    };
    if (emailconf != null && email != null)
        Mail.mail(emailconf, email, email, "Twitter Stream Writer Info - Writer has started",
                "The Gardenhose Writer has begun crawling the stream (this email indicates that you will recieve alerts if something goes wrong.");
    twitterStream.addListener(listener);
    twitterStream.sample();
}

From source file:de.fhm.bigdata.projekt.dataimport.TwitterSource.java

License:Apache License

/**
 * The initialization method for the Source. The context contains all the
 * Flume configuration info, and can be used to retrieve any configuration
 * values necessary to set up the Source.
 *///  w  w  w  .ja  v a 2  s.  c  om
@Override
public void configure(Context context) {
    consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY_KEY);
    consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET_KEY);
    accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN_KEY);
    accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET_KEY);

    proxyEnabled = context.getBoolean(TwitterSourceConstants.PROXY_ENABLED);
    proxyHost = context.getString(TwitterSourceConstants.PROXY_HOST);
    proxyPort = context.getInteger(TwitterSourceConstants.PROXY_PORT);

    String keywordString = context.getString(TwitterSourceConstants.KEYWORDS_KEY, "");
    if (keywordString.trim().length() == 0) {
        keywords = new String[0];
    } else {
        keywords = keywordString.split(",");
        for (int i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
        }
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    if (proxyEnabled) {
        cb.setHttpProxyHost(proxyHost);
        cb.setHttpProxyPort(proxyPort);//port
    }

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

From source file:de.vanita5.twittnuker.activity.support.SignInActivity.java

License:Open Source License

private Configuration getConfiguration() {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    final boolean enable_gzip_compressing = mPreferences.getBoolean(KEY_GZIP_COMPRESSING, false);
    final boolean ignore_ssl_error = mPreferences.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enable_proxy = mPreferences.getBoolean(KEY_ENABLE_PROXY, false);
    cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(mApplication));
    cb.setHttpClientFactory(new TwidereHttpClientFactory(mApplication));
    if (Utils.isOfficialConsumerKeySecret(this, mConsumerKey, mConsumerSecret)) {
        Utils.setMockOfficialUserAgent(this, cb);
    } else {/*from ww  w . ja va  2  s. c o m*/
        Utils.setUserAgent(this, cb);
    }
    if (!isEmpty(mAPIUrlFormat)) {
        final String versionSuffix = mNoVersionSuffix ? null : "/1.1/";
        cb.setRestBaseURL(Utils.getApiUrl(mAPIUrlFormat, "api", versionSuffix));
        cb.setOAuthBaseURL(Utils.getApiUrl(mAPIUrlFormat, "api", "/oauth/"));
        cb.setUploadBaseURL(Utils.getApiUrl(mAPIUrlFormat, "upload", versionSuffix));
        if (!mSameOAuthSigningUrl) {
            cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
            cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
            cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
        }
    }
    if (isEmpty(mConsumerKey) || isEmpty(mConsumerSecret)) {
        cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
        cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
    } else {
        cb.setOAuthConsumerKey(mConsumerKey);
        cb.setOAuthConsumerSecret(mConsumerSecret);
    }
    cb.setGZIPEnabled(enable_gzip_compressing);
    cb.setIgnoreSSLError(ignore_ssl_error);
    if (enable_proxy) {
        final String proxy_host = mPreferences.getString(KEY_PROXY_HOST, null);
        final int proxy_port = ParseUtils.parseInt(mPreferences.getString(KEY_PROXY_PORT, "-1"));
        if (!isEmpty(proxy_host) && proxy_port > 0) {
            cb.setHttpProxyHost(proxy_host);
            cb.setHttpProxyPort(proxy_port);
        }
    }
    return cb.build();
}

From source file:de.vanita5.twittnuker.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());
        }/* w w w.j ava 2s.  c  o  m*/
    }
    cb.setHostAddressResolverFactory(resolverFactory);
    if (userAgent != null) {
        cb.setHttpUserAgent(userAgent);
    }
    cb.setHttpClientFactory(new TwidereHttpClientFactory(context));
    return new HttpClientWrapper(cb.build());
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Twitter getTwitterInstance(final Context context, final long accountId,
        final boolean includeEntities, final boolean includeRetweets, final boolean apacheHttp,
        final String mediaProvider, final String mediaProviderAPIKey) {
    if (context == null)
        return null;
    final TwittnukerApplication app = TwittnukerApplication.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 ww  . j a va2s.  c  o m*/
    final String where = Where.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 {
        if (!c.moveToFirst())
            return null;
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(app));
        if (apacheHttp) {
            cb.setHttpClientFactory(new TwidereHttpClientFactory(app));
        }
        cb.setHttpConnectionTimeout(connection_timeout);
        cb.setGZIPEnabled(enableGzip);
        cb.setIgnoreSSLError(ignoreSSLError);
        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_2);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
        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;
        final boolean noVersionSuffix = c.getInt(c.getColumnIndex(Accounts.NO_VERSION_SUFFIX)) == 1;
        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));
            if (!sameOAuthSigningUrl) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }
        }
        if (isOfficialConsumerKeySecret(context, consumerKey, consumerSecret)) {
            setMockOfficialUserAgent(context, cb);
        } else {
            setUserAgent(context, cb);
        }

        if (!isEmpty(mediaProvider)) {
            cb.setMediaProvider(mediaProvider);
        }
        if (!isEmpty(mediaProviderAPIKey)) {
            cb.setMediaProviderAPIKey(mediaProviderAPIKey);
        }
        cb.setIncludeEntitiesEnabled(includeEntities);
        cb.setIncludeRTsEnabled(includeRetweets);
        cb.setIncludeReplyCountEnabled(true);
        cb.setIncludeDescendentReplyCountEnabled(true);
        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.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_2);
                cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
            }
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            if (isEmpty(token) || isEmpty(tokenSecret))
                return null;
            cb.setOAuthAccessToken(token);
            cb.setOAuthAccessTokenSecret(tokenSecret);
            return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret));
        }
        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 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;
        }
        }
    } finally {
        c.close();
    }
}

From source file:it.greenvulcano.gvesb.social.twitter.TwitterSocialAdapterAccount.java

License:Open Source License

/**
 * This method returns the interface class towards Twitter, already instantiated with the
 * account's tokens/*from   w w  w .j a  v a  2 s .  c om*/
 * 
 * @return {@link Twitter}
 */
public Twitter getProxyObject() {
    if (twitter != null) {
        return twitter;
    } else {
        // setting OAuth tokens
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        if (proxy != null) {
            confBuilder.setHttpProxyHost(proxy.getHttpProxyHost());
            confBuilder.setHttpProxyPort(proxy.getHttpProxyPort());
            confBuilder.setHttpProxyUser(proxy.getHttpProxyUser());
            confBuilder.setHttpProxyPassword(proxy.getHttpProxyPassword());
        }
        confBuilder.setOAuthConsumerKey(consumerKey);
        confBuilder.setOAuthConsumerSecret(consumerSecret);
        confBuilder.setOAuthAccessToken(accessToken);
        confBuilder.setOAuthAccessTokenSecret(accessTokenSecret);
        Configuration config = confBuilder.build();
        // instantiating Twitter object
        this.twitter = new TwitterFactory(config).getInstance();
    }
    logger.info("got TwitterFactory instance.");
    return twitter;
}