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.twitt4droid.Twitt4droid.java

License:Apache License

/**
 * Gets the current Twitter with consumer and access tokens pre-initialized.
 * /*from   www.j  ava  2s .c  om*/
 * @param context the application context.
 * @return an Twitter object.
 */
public static Twitter getTwitter(Context context) {
    return new TwitterFactory(getCurrentConfig(context)).getInstance();
}

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");
    }// w ww  .j  av  a  2  s. c om
    // 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:com.vti.managers.AccountManager.java

License:Apache License

public AccountManager(Context ctxt) {
    this.context = ctxt;
    final SharedPreferences settings = context.getSharedPreferences(Constants.AUTHORIZATION_PREFERENCE_FILE, 0);
    String accessToken = settings.getString(Constants.ACCESS_TOKEN, null);
    String tokenSecret = settings.getString(Constants.TOKEN_SECRET, null);

    if (null != accessToken && null != tokenSecret) {
        tf = new TwitterFactory(new ConfigurationBuilder().setDebugEnabled(true)
                .setOAuthConsumerKey(Constants.CONSUMER_KEY).setOAuthConsumerSecret(Constants.CONSUMER_SECRET)
                .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(tokenSecret).build());
    }/*from  w w w. jav  a2 s . c o m*/
}

From source file:com.vuze.client.plugins.twitter.TwitterPlugin.java

License:Open Source License

private TwitterResult sendTweet(String status) {
    TwitterResult twitter_result;//from   w ww.j a  v a 2  s  . c  o  m

    log.log("Updating status: " + status);

    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();

        //cb.setSource( "Vuze" );

        // Twitter twitter = new TwitterFactory( cb.build()).getInstance( twitter_user.getValue(), new String( twitter_password.getValue()));

        Status result;

        Twitter twitter = null;

        try {
            if (access_token == null) {

                throw (new Exception("Please configure your account settings in the plugin options"));
            }

            cb.setOAuthAccessToken(access_token.getToken())
                    .setOAuthAccessTokenSecret(access_token.getTokenSecret()).setOAuthConsumerKey(CONSUMER_KEY)
                    .setOAuthConsumerSecret(CONSUMER_SECRET);

            twitter = new TwitterFactory(cb.build()).getInstance();

            result = twitter.updateStatus(status);

        } catch (Throwable e) {

            // hack for old clients that don't have correct trust store

            if (twitter != null && (e instanceof TwitterException)
                    && ((TwitterException) e).getStatusCode() == -1) {

                String truststore_name = FileUtil.getUserFile(SESecurityManager.SSL_CERTS).getAbsolutePath();

                File target = new File(truststore_name);

                if (!target.exists() || target.length() < 2 * 1024) {

                    File cacerts = new File(
                            new File(new File(System.getProperty("java.home"), "lib"), "security"), "cacerts");

                    if (cacerts.exists()) {

                        FileUtil.copyFile(cacerts, target);
                    }
                }

                // this merely acts to trigger a load of the keystore

                plugin_interface.getUtilities().getSecurityManager()
                        .installServerCertificate(new URL("https://twitter.com/"));

                result = twitter.updateStatus(status);

            } else {

                throw (e);
            }
        }

        log.log("Status updated to '" + result.getText() + "'");

        twitter_result = new TwitterResult();

    } catch (TwitterException e) {

        int status_code = e.getStatusCode();

        if (status_code == 401) {

            log.logAlert(LoggerChannel.LT_ERROR, "Twitter status update failed: id or password incorrect");

            twitter_result = new TwitterResult("Authentication failed: ID or password incorrect", false);

        } else if (status_code == 403) {

            log.logAlert(LoggerChannel.LT_ERROR,
                    "Twitter status update failed: duplicate tweet rejected by the server");

            twitter_result = new TwitterResult("Tweet has already been sent!", false);

        } else if (status_code >= 500 && status_code < 600) {

            log.logAlert(LoggerChannel.LT_ERROR,
                    "Twitter status update failed: Twitter is down or being upgraded");

            twitter_result = new TwitterResult("Tweet servers unavailable - try again later", true);

        } else {

            log.logAlert("Twitter status update failed", e);

            twitter_result = new TwitterResult(Debug.getNestedExceptionMessage(e), false);
        }
    } catch (Throwable e) {

        log.logAlert("Twitter status update failed", e);

        twitter_result = new TwitterResult(Debug.getNestedExceptionMessage(e), false);
    }

    return (twitter_result);
}

From source file:com.wavemaker.runtime.ws.TwitterFeedService.java

License:Open Source License

private Twitter getTwitter() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(OAuthConsumerKey).setOAuthConsumerSecret(OAuthConsumerSecret)
            .setOAuthAccessToken(OAuthAccessToken).setOAuthAccessTokenSecret(OAuthAccessTokenSecret);

    return new TwitterFactory(cb.build()).getInstance();
}

From source file:com.wimbli.serverevents.Register.java

License:Open Source License

private static void execute() {
    try {// w w  w  .j a va 2 s  . c  o m
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("QyuUqx8UFaRLMWORQinphg")
                .setOAuthConsumerSecret("EWORHYNo3JkJgvihiGwFL8tWNHExyhWFilR1Q");

        twitter = new TwitterFactory(cb.build()).getInstance();
        accessToken = null;
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            requestToken = twitter.getOAuthRequestToken();

            msg("Open the following URL and grant access to ServerEvents:");
            msg(requestToken.getAuthorizationURL());
            outputToFile("Open the following URL and grant access to ServerEvents: \n"
                    + requestToken.getAuthorizationURL());
            msg("For convenience, this URL has also been output to a file: " + outFile);

            if (cmdLine) {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                while (null == accessToken) {
                    System.out.print(
                            "Enter the PIN(if available) and hit enter after you have granted access. [PIN]:");
                    String pin = br.readLine();
                    tryPin(pin);
                }
            }
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                msg("OAuth consumer key/secret is not set.");
                exit(-1);
            }
        }
    } catch (TwitterException te) {
        msg("Failed to get timeline: " + te.getMessage());
        msg("Try revoking access to the ServerEvents application from your Twitter settings page.");
        exit(-1);
    } catch (IOException ioe) {
        msg("Failed to read the system input.");
        exit(-1);
    }

    if (cmdLine)
        exit(0);
}

From source file:com.yattatech.dbtc.util.TwitterUtil.java

License:Open Source License

public static Twitter getTwitter() {
    if (sTwitter == null) {
        final ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setHttpConnectionTimeout(Constants.TWITTER_TIMEOUT);
        sTwitter = new TwitterFactory(builder.build()).getInstance();
        // These values represents DBTC Twitter app credentials, don't
        // expose that data to anyone else
        final String twitterKey = DBTCApplication.sApplicationContext.getString(R.string.twitter_key);
        final String twitterSecret = DBTCApplication.sApplicationContext.getString(R.string.twitter_secret);
        sTwitter.setOAuthConsumer(twitterKey, twitterSecret);
    }//from ww w  .  j  a va 2  s. c om
    return sTwitter;
}

From source file:com.yfiton.notifiers.twitter.TwitterNotifier.java

License:Apache License

public TwitterNotifier() throws NotificationException {
    super(CLIENT_ID, SECRET_ID, PromptReceiver.class, TwitterWebEngineListener.class);

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setGZIPEnabled(true).setDebugEnabled(true).setOAuthConsumerKey(getClientId())
            .setOAuthConsumerSecret(getClientSecret());

    com.yfiton.notifiers.twitter.AccessToken accessToken = getAccessToken();

    if (accessToken != null) {
        configurationBuilder.setOAuthAccessToken(accessToken.getAccessToken());
        configurationBuilder.setOAuthAccessTokenSecret(accessToken.getAccessTokenSecret());
    }/*from   w w w .j a  v  a  2 s  .co m*/

    twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
}

From source file:com.zeus3110.iotstation.DeviceServer.java

License:Apache License

private void TwitterSetting() {
    cb = new ConfigurationBuilder();
    // change your key and token
    cb.setDebugEnabled(true).setOAuthConsumerKey(TwitterKey.CONSUMER_KEY)
            .setOAuthConsumerSecret(TwitterKey.CONSUMER_SECRET).setOAuthAccessToken(TwitterKey.ACCESS_TOKEN_KEY)
            .setOAuthAccessTokenSecret(TwitterKey.ACCESS_TOKEN_SECRET);
    factory = new TwitterFactory(cb.build());
    Log.i(TAG, "Twetter Auth Setting End");
}

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;/*  ww  w. ja  v  a 2 s. 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);

}