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:com.speed.traquer.app.TraqComplaintTaxi.java

/**
 * Function to login twitter//from  w ww  . j  av  a  2  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(TraqComplaintTaxi.this, "Already Logged into twitter", Toast.LENGTH_SHORT).show();

        /* Get Access Token after login*/
        /*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);
                
                
        // Getting user details from twitter
        // For now i am getting his name only
        twitterID= accessToken.getUserId();
        User user = twitter.showUser(twitterID);
                
        userName = user.getName();
                
        // Displaying in xml ui
        //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description));
                
                
        } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
        }*/

    }
}

From source file:com.speed.traquer.app.TraqComplaintTaxi.java

private void checkTwitterID() {

    /* Get Access Token after login*/
    try {/*  ww w .j  av a2  s . c  o  m*/
        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);

        // Getting user details from twitter
        // For now i am getting his name only
        twitterID = accessToken.getUserId();
        User user = twitter.showUser(twitterID);

        userName = user.getName();

        //Toast.makeText(TraqComplaintTaxi.this, Long.toString(twitterID) + userName, Toast.LENGTH_SHORT).show();
        // Displaying in xml ui
        //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description));

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    } catch (Exception e) {
        // Error in updating status
        Log.d("error!", e.getMessage());
    }
}

From source file:com.stronquens.amgtwitter.ControllerOAuth.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w  .  j  av  a 2 s.  com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Parametros del request
        HttpSession sesion = request.getSession();
        String verifier = request.getParameter("verifier");
        String op = request.getParameter("op");

        // Definimos variables
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        Twitter OAuthTwitter = null;
        String url = null;

        // Devolemos la url generada          
        if ((verifier == null || verifier == "") && "url".equalsIgnoreCase(op)) {
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                    .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
            OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
            sesion.setAttribute("twitter", OAuthTwitter);
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                sesion.setAttribute("requestToken", requestToken);
                url = requestToken.getAuthenticationURL();
                out.println("{\"url\":\"" + url + "\"}");
            } catch (TwitterException ex) {
            }
        }

        // Devolvemos el acces token generado
        if (verifier != null && verifier.length() > 0) {
            OAuthTwitter = (Twitter) sesion.getAttribute("twitter");
            requestToken = (RequestToken) sesion.getAttribute("requestToken");
            accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, verifier);
            sesion.setAttribute("accesToken", accessToken);
            sesion.removeAttribute("twitter");
            sesion.removeAttribute("requestToken");
            out.println("{\"token\":\"" + accessToken.getToken() + "\",\"secret\":\""
                    + accessToken.getTokenSecret() + "\"}");
        }

    }
}

From source file:com.stronquens.amgtwitter.ControllerTwitter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  . ja v  a 2 s . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Obtenemos parametros de la peticion
        String op = request.getParameter("op");
        String accesToken = request.getParameter("token");
        String accesTokenSecret = request.getParameter("secret");

        // Inicializamos variables
        String jsonResult = "";
        Twitter twitter = null;
        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create();

        // Se crea la instancia de twitter segun los parametros de ususario
        if (!"".equalsIgnoreCase(accesToken) && !"".equalsIgnoreCase(accesTokenSecret)) {
            try {
                configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                        .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW")
                        .setOAuthAccessToken(accesToken).setOAuthAccessTokenSecret(accesTokenSecret);
                twitter = new TwitterFactory(configBuilder.build()).getInstance();
            } catch (Exception e) {
                System.out.println(e);
            }
        } else {
            try {
                configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                        .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
                twitter = new TwitterFactory(configBuilder.build()).getInstance();
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        // Se realizan las diferentes operaciones
        switch (op) {
        case "timeline":
            try {
                Paging pagina = new Paging();
                pagina.setCount(25);
                ResponseList listado = twitter.getHomeTimeline(pagina);
                jsonResult = gson.toJson(listado);
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        case "usersettings":
            try {
                jsonResult = gson.toJson(twitter.showUser(twitter.getId()));
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        case "pruebas":
            try {
                jsonResult = gson.toJson(twitter.showUser(twitter.getId()));
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        default:
            jsonResult = "{\"eror\":\"la operacion no existe\"}";
        }
        // Se devuelven los valores
        out.println(jsonResult);
    }
}

From source file:com.thesmartweb.swebrank.TwitterAnalysis.java

License:Apache License

/**
 * Method to get tweets regarding a string 
 * @param query_string the string to search for
 * @param config_path the directory with the twitter api key
 * @return the tweets in a string// ww  w .  j a  v a2s.c o m
 */
public String perform(String query_string, String config_path) {
    try {
        List<String> twitterkeys = GetKeys(config_path);
        //configuration builder in order to set the keys of twitter
        ConfigurationBuilder cb = new ConfigurationBuilder();
        String consumerkey = twitterkeys.get(0);
        String consumersecret = twitterkeys.get(1);
        String accesstoken = twitterkeys.get(2);
        String accesstokensecret = twitterkeys.get(3);
        cb.setDebugEnabled(true).setOAuthConsumerKey(consumerkey).setOAuthConsumerSecret(consumersecret)
                .setOAuthAccessToken(accesstoken).setOAuthAccessTokenSecret(accesstokensecret);
        TwitterFactory tf = new TwitterFactory(cb.build());
        AccessToken acc = new AccessToken(accesstoken, accesstokensecret);

        Twitter twitter = tf.getInstance(acc);

        //query the twitter
        Query query = new Query(query_string);
        int rpp = 100;
        query.count(rpp);
        query.setQuery(query_string);

        //----------get the tweets------------
        QueryResult result = twitter.search(query);
        List<Status> tweets = result.getTweets();

        RateLimitStatus rls = result.getRateLimitStatus();

        String tweet_txt = "";
        for (Status tweet : tweets) {
            tweet_txt = tweet_txt + " " + tweet.getText();
        }
        DataManipulation txtpro = new DataManipulation();
        Stopwords st = new Stopwords();
        tweet_txt = txtpro.removeChars(tweet_txt);
        tweet_txt = st.stop(tweet_txt);
        tweet_txt = txtpro.removeChars(tweet_txt);
        return tweet_txt;
    } catch (TwitterException ex) {
        String tweet_txt = "";
        Logger.getLogger(TwitterAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return tweet_txt = "fail";
    }
}

From source file:com.tweet.HelperMethods.java

License:Apache License

public static void postToTwitter(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);// w  ww  . j  a  v a2 s . c om
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {
                Calendar cal = Calendar.getInstance();

                twitter.updateStatus(message + "\n@" + cal.getTime().toString());
            } catch (TwitterException e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.tweet.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);//from w  ww.  jav  a2  s.c  o m
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    //final File file = new File(imageUrl);

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {

                if (StaticData.graphFile.exists()) {
                    Calendar cal = Calendar.getInstance();

                    StatusUpdate status = new StatusUpdate(message + "\n@" + cal.getTime().toString());
                    status.setMedia(StaticData.graphFile);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.tweet.LoginActivity.java

License:Apache License

private void askOAuth() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(twitterConsumerKey);
    configurationBuilder.setOAuthConsumerSecret(twitterConsumerSecret);
    Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {
        @Override/* ww  w.  ja  v  a 2s.c o  m*/
        public void run() {
            try {
                requestToken = twitter.getOAuthRequestToken(AppConstant.TWITTER_CALLBACK_URL);
            } catch (Exception e) {
                final String errorString = e.toString();
                LoginActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAlertBuilder.cancel();
                        Toast.makeText(LoginActivity.this, errorString.toString(), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
                return;
            }

            LoginActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    twitterLoginWebView.loadUrl(requestToken.getAuthenticationURL());
                }
            });
        }
    }).start();
}

From source file:com.TweetExtractor.java

public TweetExtractor() throws ParserConfigurationException, SAXException, IOException {
    //PropertyConfigurator.configure("src/main/resources/log4j.properties");
    buildConfiguration(); // set the API keys to the Config Builder
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitterApp = tf.getInstance();/*from ww w . j  a va 2  s .com*/
}

From source file:com.tweetmyhome.TweetMyHome.java

public TweetMyHome() throws TweetMyHomeException, IOException, TweetStringException {

    Log.setLogger(new MyCustomLogger());
    p = new TweetMyHomeProperties();
    if (!p.isFirstTimeCreated()) {
        if (p.getValueByKey(Key.debuggin).equalsIgnoreCase("true")) {
            Log.set(Log.LEVEL_DEBUG);//www. j  av a2 s. c o m
            Log.set(Log.LEVEL_TRACE);
        } else {
            Log.set(Log.LEVEL_INFO);
        }
    } else {
        File file = new File(TweetMyHomeProperties.FILE_NAME);
        info(String.format("Properties file created at: %s", file.getAbsolutePath()));
        info(String.format("Please edit '%s' to correct aplication function", TweetMyHomeProperties.FILE_NAME));
        info("Exiting aplication...");
        System.exit(0);
    }
    tweetCount = new TweetMensajeCount(COUNT_FILE);
    tmh_device_xml = XMLFilesManager.getTweetMyHomeDevices();
    if (tmh_device_xml == null) {
        throw new TweetMyHomeException(
                "Fail to read [" + XMLFilesManager.TWEET_MY_HOME_DEVICES_XML_FILE + "] file");
    }
    tmh_dic_xml = XMLFilesManager.getTweetMyHomeDictionaryCommand();
    if (tmh_dic_xml == null) {
        throw new TweetMyHomeException(
                "Fail to read [" + XMLFilesManager.TWEET_MY_HOME_DICTIONARY_XML_FILE + "] file");
    }
    tweetDictionary = new TweetStringDictionary(tmh_dic_xml);
    trace("XML Files already Readed [" + XMLFilesManager.TWEET_MY_HOME_DEVICES_XML_FILE + ","
            + XMLFilesManager.TWEET_MY_HOME_DICTIONARY_XML_FILE + "]");

    if (!NetUtil.isConnectedToInternet() && INTERNET_REQUIRED_DEV) {
        throw new TweetMyHomeException("Not Connected to Internet");
    }
    trace("Internet conecction detected");
    trace("Trying to connect to DBMS...");
    db = new TweetMyHomeDatabase(p);
    if (!db.connect()) {
        throw new TweetMyHomeException("Not Connected to DBMS");
    }
    trace("Connected to DBMS");
    db.addTweetMyHomeDevices(tmh_device_xml);

    if (RASPBERRY_ON_BOARD) {
        if (p.getValueByKey(Key.arduinoIOBridge).equalsIgnoreCase("true")) {
            throw new TweetMyHomeException("Arduino not supported...");
        } else {
            iob = new RaspberryPiGPIO(tmh_device_xml);
        }
        if (iob != null) {
            iob.addIODeviceListener(this);
            iob.connect();
            trace("GPIO Link established");
            com = new Comunity(false, iob);
            sec = new Security(false, iob);
            //sect = new SecurityThreshhold(sec);
            trace("Security , Security threshold & Comunity initiated");
        }
    } else {
        warn("Raspberry PI GPIO omited. APP prob. won't work well");
    }
    sect = new SecurityThreshhold(sec);
    trace("Setting Twitter OAuth parameters...");
    ConfigurationBuilder cb1 = new ConfigurationBuilder();
    cb1.setDebugEnabled(false).setOAuthConsumerKey("RaTG5hw5OwhQQugghtLthG0ug")
            .setOAuthConsumerSecret("brJ0vcrdGnCHMTxDCmKoThPpJubD6e2xol5WjdO9bBa19nzkXp")
            .setOAuthAccessToken("3236804811-V6MOxfbox4jVylx6pDjkR9UrEpuPzZyOwkaVIWp")
            .setOAuthAccessTokenSecret("33HvizelxmGN700a7pLa6YBKv0l2uTMLoJK593MlXellg");
    ConfigurationBuilder cb2 = new ConfigurationBuilder();
    cb2.setDebugEnabled(false).setOAuthConsumerKey("RaTG5hw5OwhQQugghtLthG0ug")
            .setOAuthConsumerSecret("brJ0vcrdGnCHMTxDCmKoThPpJubD6e2xol5WjdO9bBa19nzkXp")
            .setOAuthAccessToken("3236804811-V6MOxfbox4jVylx6pDjkR9UrEpuPzZyOwkaVIWp")
            .setOAuthAccessTokenSecret("33HvizelxmGN700a7pLa6YBKv0l2uTMLoJK593MlXellg");
    TwitterFactory tf = new TwitterFactory(cb1.build());
    TwitterStreamFactory sf = new TwitterStreamFactory(cb2.build());

    trace("Connecting to Twitter STREAM API...");
    tws = sf.getInstance();
    tws.addListener(this);
    tws.user();
    trace("Connecting to Twitter REST API...");
    tw = tf.getInstance();
    debug("Contructor fi");
    /*----------------NEEDED WORK TO DO-------------------*/

    // integrityCheckSuperAdmin();

}