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:co.thehotnews.lambda.TheHotNewsSpeechlet.java

License:Open Source License

public TheHotNewsSpeechlet() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(TWITTER_OAUTH_CONSUMER_KEY)
            .setOAuthConsumerSecret(TWITTER_OAUTH_CONSUMER_SECRET)
            .setOAuthAccessToken(TWITTER_OAUTH_ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(TWITTER_OAUTH_ACCESS_TOKEN_SECRET);
    twitterFactory = new TwitterFactory(cb.build());
}

From source file:co.uk.socialticker.ticker.TickerActivity.java

License:Open Source License

/**
 * Function to login twitter//from  ww  w  . j a v  a2 s  .  c o m
 * */
private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        try {
            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}

From source file:co.uk.socialticker.ticker.TickerActivity.java

License:Open Source License

/**
 * Test code to try and retrieve some data from twitter in a search!
 * @throws TwitterException /*w  w w.  ja v  a2s.  c  o m*/
 * */
public JSONArray doSearch(View v) throws TwitterException {

    if (mApiClient != null || debugOn) {
        // The factory instance is re-useable and thread safe.
        //get the hashtag - check to make sure if returned value is set to something with a length
        JSONArray jsA = new JSONArray();
        String qHash = p.getString(KEY_CAST_HASHTAG, "");
        Log.d(TAG, "Hash to search: " + qHash);
        if (qHash.length() == 0) {
            Toast.makeText(this, "The hashtag looks like it is not setup. May want to fix that",
                    Toast.LENGTH_LONG).show();
        } else {
            try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

                // Access Token 
                String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
                // Access Token Secret
                String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

                AccessToken accessToken = new AccessToken(access_token, access_token_secret);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
                //Query query = new Query("#MOTD2014");
                Query query = new Query(qHash);
                query.count(TWEET_COUNT);
                QueryResult result = twitter.search(query);
                for (twitter4j.Status status : result.getTweets()) {

                    MediaEntity[] me = status.getMediaEntities();
                    String meUrl = "";
                    if (me.length > 0) {
                        Log.d(TAG, "me[0] : " + me[0].getMediaURL());
                        //meUrl = me[0].getDisplayURL(); //sjort URl = useless.
                        meUrl = me[0].getMediaURL();
                    }

                    JSONObject jso = tweetJSON(status.getUser().getScreenName(), status.getUser().getName()
                    //                        , status.getUser().getOriginalProfileImageURL() //Whatever the size was it was uploaded in
                    //                        , status.getUser().getProfileImageURL() // 48x48
                            , status.getUser().getBiggerProfileImageURL() // 73x73
                            , status.getText(), status.getCreatedAt().toString(), status.getFavoriteCount(),
                            status.getRetweetCount(), meUrl);
                    jsA.put(jso);
                }

            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Search Error", e.getMessage());
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        ;
        return jsA;
    } else {
        Toast.makeText(this, "You do not seem to be connected to a cast device...", Toast.LENGTH_LONG).show();
        return null;
    }
}

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 w  w  w  .  j ava2  s.  co  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:collector.TwitterCollector.java

public TwitterCollector(List<String> credentials) {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    String OAuthConsumerKey = credentials.get(0);
    String OAuthConsumerSecret = credentials.get(1);
    String OAuthAccessToken = credentials.get(2);
    String OAuthAccessTokenSecret = credentials.get(3);

    cb.setDebugEnabled(true).setOAuthConsumerKey(OAuthConsumerKey).setOAuthConsumerSecret(OAuthConsumerSecret)
            .setOAuthAccessToken(OAuthAccessToken).setOAuthAccessTokenSecret(OAuthAccessTokenSecret);
    //                .setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();/*ww w  .  j a  v a 2 s . c  o  m*/

}

From source file:ColourUs.OAuth.java

public OAuth() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(C2_KEY).setOAuthConsumerSecret(C2_SECRET)
            .setOAuthAccessToken(A2_TOKEN).setOAuthAccessTokenSecret(A2_SECRET);
    config = cb.build();
}

From source file:com.adobe.acs.commons.twitter.impl.TwitterAdapterFactory.java

License:Apache License

private Configuration buildConfiguration() {
    final ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setUseSSL(true);//from w  ww. jav  a2s .c  o m
    builder.setApplicationOnlyAuthEnabled(true);
    return builder.build();
}

From source file:com.ahuralab.mozaic.auth.TwitterAuthenticator.java

License:Open Source License

public Twitter createTwitter(Context context) {
    SharedPreferences settings = context.getSharedPreferences(TWITTER_CREDENTIAL, 0);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(settings.getString("user_key", null))
            .setOAuthAccessTokenSecret(settings.getString("user_secret", null));
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();/* w  ww. j a va 2s  .c  o  m*/
    return twitter;
}

From source file:com.ak.android.akplaza.common.sns.twitter.TwitterController.java

License:Open Source License

public static void write(String content, Activity at) {
    //      Log.d(TAG, "content : " + content);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String fileName = "example.jpg";
    InputStream is = null;/*from  w ww . ja  va 2 s  .  c o  m*/

    try {
        if (new File(path + File.separator + fileName).exists())
            is = new FileInputStream(path + File.separator + fileName);
        else
            is = null;

        ConfigurationBuilder cb = new ConfigurationBuilder();
        String oAuthAccessToken = acToken.getToken();
        String oAuthAccessTokenSecret = tacs;
        String oAuthConsumerKey = C.TWITTER_CONSUMER_KEY;
        String oAuthConsumerSecret = C.TWITTER_CONSUMER_SECRET;
        cb.setOAuthAccessToken(oAuthAccessToken);
        cb.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
        cb.setOAuthConsumerKey(oAuthConsumerKey);
        cb.setOAuthConsumerSecret(oAuthConsumerSecret);
        Configuration config = cb.build();
        OAuthAuthorization auth = new OAuthAuthorization(config);

        TwitterFactory tFactory = new TwitterFactory(config);
        Twitter twitter = tFactory.getInstance();
        //         ImageUploadFactory iFactory = new ImageUploadFactory(getConfiguration(C.TWITPIC_API_KEY));
        //         ImageUpload upload = iFactory.getInstance(MediaProvider.TWITPIC, auth);

        if (is != null) {
            //        String strResult = upload.upload("example.jpg", is, mEtContent.getText().toString());
            //        twitter.updateStatus(mEtContent.getText().toString() + " " + strResult);
        } else
            twitter.updateStatus(content);
        new AlertDialog.Builder(at).setMessage(" ? ? ?.")
                .setPositiveButton("?", null).show();
    } catch (Exception e) {
        e.printStackTrace();
        new AlertDialog.Builder(at).setMessage("? ?  ")
                .setPositiveButton("?", null).show();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
        }
    }

}

From source file:com.alainesp.fan.sanderson.SummaryFragment.java

License:Open Source License

protected int doWork() {
    int state = DownloadParseSaveTask.STATE_SUCCESS;

    try {/*from w ww  .java2  s.com*/
        List<twitter4j.Status> tweets;

        // Twitter client configuration
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TwitterAPISecrets.CONSUMER_KEY)
                .setOAuthConsumerSecret(TwitterAPISecrets.CONSUMER_SECRET);
        // TODO: Use guest authentication instead of application
        builder.setApplicationOnlyAuthEnabled(true).setDebugEnabled(false).setGZIPEnabled(true);

        Twitter twitter = new TwitterFactory(builder.build()).getInstance();
        twitter.getOAuth2Token();

        // Get the tweets
        long lastTweetID = DB.Tweet.getLastTweetID();
        if (lastTweetID <= 0)
            tweets = twitter.getUserTimeline("BrandSanderson");
        else
            tweets = twitter.getUserTimeline("BrandSanderson", new Paging(lastTweetID));

        if (tweets != null) {
            long brandonID = 28187205;
            Hashtable<Long, DB.Tweet> findTweet = new Hashtable<>(tweets.size() * 16, 0.25f);
            List<DB.Tweet> dbTweets = new ArrayList<>(tweets.size());
            for (twitter4j.Status tweet : tweets) {
                // Create the tweet
                if (tweet.isRetweet())
                    tweet = tweet.getRetweetedStatus();

                long tweetID = tweet.getId();
                // TODO: Include the tweets in the DB
                if (findTweet.get(tweetID) == null)// This eliminate tweets already in the replies tree
                {
                    DB.Tweet dbTweet = new DB.Tweet(tweetID, getTweetText(tweet), tweet.getCreatedAt(), false,
                            tweet.getUser().getName(), tweet.getUser().getBiggerProfileImageURLHttps());
                    InternetHelper.getRemoteFile(tweet.getUser().getBiggerProfileImageURLHttps());
                    dbTweets.add(dbTweet);
                    findTweet.put(tweetID, dbTweet);

                    // Traverse the tree of the replies tweets
                    twitter4j.Status treeTweet = tweet;
                    while (treeTweet != null && treeTweet.getInReplyToStatusId() >= 0) {
                        try {
                            long id = treeTweet.getInReplyToStatusId();
                            long userID = treeTweet.getUser().getId();
                            treeTweet = null;
                            if (findTweet.get(id) == null || brandonID == userID)
                                treeTweet = twitter.showStatus(id);
                            else// Remove duplicates. Not sure why they appear, but the difference of the text is a dot at the end.
                                dbTweets.remove(dbTweets.size() - 1);
                        } catch (Exception ignore) {
                        }

                        if (treeTweet != null) {
                            findTweet.put(treeTweet.getId(), dbTweet);
                            StringBuilder replyBuilder = new StringBuilder();

                            replyBuilder.append("<blockquote>");

                            // Profile image
                            replyBuilder.append("<img src=\"");
                            InternetHelper.getRemoteFile(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append("\"/>&nbsp;<b>");

                            // Username - date
                            replyBuilder.append(treeTweet.getUser().getName());
                            replyBuilder.append("</b> @");
                            replyBuilder.append(treeTweet.getUser().getScreenName());
                            replyBuilder.append(" - ");
                            replyBuilder
                                    .append(TwitterFragment.showDateFormat.format(treeTweet.getCreatedAt()));

                            // Tweet text
                            replyBuilder.append("<br/>");
                            replyBuilder.append(getTweetText(treeTweet));

                            // Remaining
                            replyBuilder.append(dbTweet.htmlReply);
                            replyBuilder.append("</blockquote>");

                            dbTweet.htmlReply = replyBuilder.toString();
                        }
                    }
                }
            }
            DB.Tweet.updateTwitter(dbTweets);
        }
    } catch (Exception e) {
        Logger.reportError(e.toString());
        state = DownloadParseSaveTask.STATE_ERROR_PARSING;
    }

    return state;
}