Example usage for twitter4j TwitterFactory getInstance

List of usage examples for twitter4j TwitterFactory getInstance

Introduction

In this page you can find the example usage for twitter4j TwitterFactory getInstance.

Prototype

public Twitter getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:com.socialnetwork.abhishekchandale.snloginlib.twitter.TwitterSocialNetwork.java

License:Open Source License

private void initTwitterClient() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(mConsumerKey);
    builder.setOAuthConsumerSecret(mConsumerSecret);

    String accessToken = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_TOKEN, null);
    String accessTokenSecret = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_SECRET, null);

    TwitterFactory factory = new TwitterFactory(builder.build());

    if (TextUtils.isEmpty(accessToken) && TextUtils.isEmpty(accessTokenSecret)) {
        mTwitter = factory.getInstance();
    } else {//www. ja  va  2  s.co m
        mTwitter = factory.getInstance(new twitter4j.auth.AccessToken(accessToken, accessTokenSecret));
    }
}

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

/**
 * Function to login twitter// ww  w . j a v a 2s . co 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.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 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);/*w w  w  . j a  v a2s .  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();

}

From source file:com.twit.AppCrawler.java

public static void main(String[] args) throws TwitterException {

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();

    CidadeController cidadeController = new CidadeController(new Cidade());
    List<Cidade> cidades = cidadeController.findEntities();

    String searchStr = "\"#viagem\" ";

    for (Cidade cidade : cidades) {

        //searchStr += "\"" + cidade.getNome() + "\" "; 

    }/*from w w  w. ja  v  a  2 s.  com*/

    // Create a Query object.
    Query query = new Query(searchStr);

    // Send API request to execute a search with the given query.
    QueryResult result = twitter.search(query);

    // Display search results.
    for (Status status : result.getTweets()) {
        System.out.println("\n@" + status.getUser().getName() + ": " + status.getText());
    }

}

From source file:com.twitter4rk.TwitterAuthFragment.java

License:Apache License

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mTwitterWebView = new WebView(getActivity());
    final Bundle args = getArguments();
    if (args == null) {
        // This wont be case because startTwitterAuth() handles args for
        // fragment
        throw new IllegalArgumentException(
                "No arguments passed to fragment, Please use startTwitterAuth(...) method for showing this fragment");
    }/*www.ja v a 2s  .  c  o  m*/
    // Get builder from args
    mBuilder = args.getParcelable(BUILDER_KEY);
    // Hide action bar
    if (mBuilder.hideActionBar)
        mBuilder.activity.getActionBar().hide();
    // Init progress dialog
    mProgressDialog = new ProgressDialog(mBuilder.activity);
    mProgressDialog.setMessage(mBuilder.progressText == null ? "Loading ..." : mBuilder.progressText);
    if (mBuilder.isProgressEnabled)
        mProgressDialog.show();

    // Init ConfigurationBuilder twitter4j
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    if (mBuilder.isDebugEnabled)
        cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(mBuilder.consumerKey);
    cb.setOAuthConsumerSecret(mBuilder.consumerSecret);

    // Web view client to handler url loading
    mTwitterWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Get url first
            final Uri uri = Uri.parse(url);
            // Check if we need to see for callback URL
            if (mBuilder.callbackUrl != null && url.contains(mBuilder.callbackUrl)) {
                // Get req info
                String oauthToken = uri.getQueryParameter("oauth_token");
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (mListener != null)
                    mListener.onSuccess(oauthToken, oauthVerifier);
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                mIsAuthenticated = true;
                removeMe();
                return true;
                // If no callback URL then check for info directly
            } else if (uri.getQueryParameter("oauth_token") != null
                    && uri.getQueryParameter("oauth_verifier") != null) {
                // Get req info
                String oauthToken = uri.getQueryParameter("oauth_token");
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (mListener != null)
                    mListener.onSuccess(oauthToken, oauthVerifier);
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                mIsAuthenticated = true;
                removeMe();
                return true;
                // If nothing then its failure
            } else {
                // Notify user
                if (mListener != null)
                    mListener.onFailure(
                            new Exception("Couldn't find the callback URL or oath parameters in response"));
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                removeMe();
                return false;
            }
        }
    });
    // Web Crome client to handler progress dialog visibility
    mTwitterWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
            }
        }
    });
    final Handler handler = new Handler();
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                final TwitterFactory twitterFactory = new TwitterFactory(cb.build());
                final Twitter twitter = twitterFactory.getInstance();
                RequestToken requestToken = null;
                if (mBuilder.callbackUrl == null)
                    requestToken = twitter.getOAuthRequestToken();
                else
                    requestToken = twitter.getOAuthRequestToken(mBuilder.callbackUrl);
                final RequestToken finalRequestToken = requestToken;
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        final String url = finalRequestToken.getAuthorizationURL();
                        mTwitterWebView.loadUrl(url);
                    }
                });
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    }).start();

    return mTwitterWebView;
}

From source file:Control.MyOwnTwitterFactory.java

License:Open Source License

public Twitter createOneTwitterInstance() {
    Twitter twitter;/*from w w w  .ja  va  2 s  .co  m*/
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(APIkeys.getTwitterAPIKey());
    builder.setOAuthConsumerSecret(APIkeys.getTwitterAPISecret());
    builder.setUseSSL(true);
    Configuration configuration = builder.build();
    twitter4j.TwitterFactory factory = new twitter4j.TwitterFactory(configuration);
    twitter = factory.getInstance();

    return twitter;

}

From source file:Controller.DetailsmesoffresController.java

@FXML
void partageTwitter(ActionEvent event) throws TwitterException, FileNotFoundException {

    OffreService offreService = new OffreService();
    FXMLAfficheroffresController z = new FXMLAfficheroffresController();

    Offre x = offreService.findById(Integer.parseInt(FXMLAfficheroffresController.getLabelid()));

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("zFrvXiT4O6bPh7wtfX2qpxTJM")
            .setOAuthConsumerSecret("pZeG2yJ71HYSu3y8MC4sbOcAeKstRKmp8bVKfCOmxnd4QjsKmC")
            .setOAuthAccessToken("3345656831-F533Ns9kdMPI6GfmHwiVor3BUHM6kYJn4WO4xhq")
            .setOAuthAccessTokenSecret("1hWrntZlel0gOju0xOEVf2t5kRo2CjSp5H75sieOUfT89");

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

    twitter4j.Twitter tw = tf.getInstance();

    String pathphoto = x.getPhoto();
    String nomphoto = pathphoto.substring(62);
    System.out.println(nomphoto);

    File file = null;/* w ww.  j  av  a 2s. co m*/
    file = new File(x.getPhoto());

    String StatusMessage = (x.getPtvente().getNom() + "\n" + x.getDescription() + "\n" + x.getTaux_remise());

    StatusUpdate status = new StatusUpdate(StatusMessage);
    status.setMedia(file);
    tw.updateStatus(status);

}

From source file:Controller.DetailsOffreController.java

@FXML
void partagersurtwitter(ActionEvent event) throws TwitterException {

    OffreService offreService = new OffreService();
    AfficherToutesOffresController z = new AfficherToutesOffresController();

    Offre x = offreService.findById(Integer.parseInt(AfficherToutesOffresController.getLabelid()));

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("zFrvXiT4O6bPh7wtfX2qpxTJM")
            .setOAuthConsumerSecret("pZeG2yJ71HYSu3y8MC4sbOcAeKstRKmp8bVKfCOmxnd4QjsKmC")
            .setOAuthAccessToken("3345656831-F533Ns9kdMPI6GfmHwiVor3BUHM6kYJn4WO4xhq")
            .setOAuthAccessTokenSecret("1hWrntZlel0gOju0xOEVf2t5kRo2CjSp5H75sieOUfT89");

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

    twitter4j.Twitter tw = tf.getInstance();

    String pathphoto = x.getPhoto();
    String nomphoto = pathphoto.substring(62);
    System.out.println(nomphoto);

    File file = null;//from  www  .  j av  a2 s  .  c  o  m
    file = new File(x.getPhoto());

    String StatusMessage = (x.getPtvente().getNom() + "\n" + x.getDescription() + "\n" + x.getTaux_remise());

    StatusUpdate status = new StatusUpdate(StatusMessage);
    status.setMedia(file);
    tw.updateStatus(status);

}

From source file:controllers.modules.CorpusModule.java

License:Open Source License

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;//  w  w w. j a  v  a2  s.co m
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}