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

    try {
      requestToken = twitter.getOAuthRequestToken(Const.CALLBACK_URL);

      // Intent dialogIntent = new Intent(Intent.ACTION_VIEW,
      // Uri.parse(requestToken.getAuthenticationURL()));
      // oActivity.startActivity(dialogIntent);
      // oActivity.startActivityForResult(dialogIntent,0);
      Intent intent = ActivityHelper.createActivityIntent(oActivity, TwitterAuthActivity.class);
      intent.putExtra("auth_twitter_url", requestToken.getAuthenticationURL());
      // oActivity.startActivity(intent);
      oActivity.startActivityForResult(intent, 0);
      Log.v(
          this.getClass().getCanonicalName(),
          "askOAuth-> After:" + requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 2
0
    /** getting Places JSON */
    protected String doInBackground(String... args) {
      Log.d("Tweet Text", "> " + args[0]);
      String status = args[0];
      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);

        // Update status
        twitter4j.Status response = twitter.updateStatus(status);

        Log.d("Status", "> " + response.getText());
      } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
      }
      return null;
    }
Exemplo n.º 3
0
    protected Void doInBackground(String... args) {

      String status = args[0];
      try {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(consumerKey);
        builder.setOAuthConsumerSecret(consumerSecret);

        // 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);

        // Update status
        StatusUpdate statusUpdate = new StatusUpdate(status);
        twitter4j.Status response = twitter.updateStatus(statusUpdate);

        Log.d("Status", response.getText());

      } catch (TwitterException e) {
        Log.d("Failed to post!", e.getMessage());
      }
      return null;
    }
Exemplo n.º 4
0
  public static void main(String args[]) {
    try {
      ConfigurationBuilder cb = new ConfigurationBuilder();
      cb.setDebugEnabled(true)
          .setOAuthConsumerKey(cK)
          .setOAuthConsumerSecret(cS)
          .setOAuthAccessToken(aT)
          .setOAuthAccessTokenSecret(aTS);

      TwitterFactory tf = new TwitterFactory(cb.build());
      Twitter twitter = tf.getInstance();
      long cursor = -1;
      long IDS = 2458351900L;
      IDs ids;
      System.out.println("Listing followers's ids.");
      do {
        ids = twitter.getFollowersIDs(IDS, cursor);

        for (long id : ids.getIDs()) {
          System.out.println(id);
        }
      } while ((cursor = ids.getNextCursor()) != 0);
      System.exit(0);
    } catch (TwitterException te) {
      te.printStackTrace();
      System.out.println("Failed to get followers' ids: " + te.getMessage());
      System.exit(-1);
    }
  }
Exemplo n.º 5
0
  public TwitterClient(String fileName) throws IOException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
  }
Exemplo n.º 6
0
  public void inviteFriends(String id, String msg) {
    try {
      if (mTwitter == null) {
        ConfigurationBuilder confbuilder = new ConfigurationBuilder();
        Configuration conf =
            confbuilder
                .setOAuthConsumerKey(Const.CONSUMER_KEY)
                .setOAuthConsumerSecret(Const.CONSUMER_SECRET)
                .build();
        mTwitter = new TwitterFactory(conf).getInstance();
      }

      SharedPreferences pref = context.getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
      String accessToken = pref.getString(Const.PREF_KEY_ACCESS_TOKEN, null);
      String accessTokenSecret = pref.getString(Const.PREF_KEY_ACCESS_TOKEN_SECRET, null);
      if (accessToken == null || accessTokenSecret == null) {
        Toast.makeText(activity, "please Login first", Toast.LENGTH_SHORT).show();
        return;
      }
      mTwitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

      System.out.println("idddddd: " + id);
      mTwitter.sendDirectMessage(Long.parseLong(id), msg);

      Toast.makeText(activity, "Your Invitation has been sent!", Toast.LENGTH_SHORT).show();

    } catch (TwitterException e) {
      e.printStackTrace();
    } catch (NumberFormatException ne) {
      ne.printStackTrace();
    }
  }
Exemplo n.º 7
0
  public String getCurrentUserScreenName() {

    try {
      if (mTwitter == null) {
        ConfigurationBuilder confbuilder = new ConfigurationBuilder();
        Configuration conf =
            confbuilder
                .setOAuthConsumerKey(Const.CONSUMER_KEY)
                .setOAuthConsumerSecret(Const.CONSUMER_SECRET)
                .build();
        mTwitter = new TwitterFactory(conf).getInstance();
      }
      SharedPreferences pref = context.getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
      String accessToken = pref.getString(Const.PREF_KEY_ACCESS_TOKEN, null);
      String accessTokenSecret = pref.getString(Const.PREF_KEY_ACCESS_TOKEN_SECRET, null);
      if (accessToken == null || accessTokenSecret == null) {
        Toast.makeText(activity, "please Login first", Toast.LENGTH_SHORT).show();
        return null;
      }

      mTwitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
      return mTwitter.getScreenName();

    } catch (TwitterException te) {
      te.printStackTrace();
    }
    return null;
  }
Exemplo n.º 8
0
  private void loginToTwitter() {
    boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

    if (!isLoggedIn) {
      final ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.setOAuthConsumerKey(consumerKey);
      builder.setOAuthConsumerSecret(consumerSecret);

      final Configuration configuration = builder.build();
      final TwitterFactory factory = new TwitterFactory(configuration);
      twitter = factory.getInstance();

      try {
        requestToken = twitter.getOAuthRequestToken(callbackUrl);

        /**
         * Loading twitter login page on webview for authorization Once authorized, results are
         * received at onActivityResult
         */
        final Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
        startActivityForResult(intent, WEBVIEW_REQUEST_CODE);

      } catch (TwitterException e) {
        e.printStackTrace();
      }
    } else {
      Intent intent = new Intent(MainActivity.this, MenuActivity.class);
      startActivity(intent);
    }
  }
  public String twitterLogin() {
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true)
        .setOAuthConsumerKey(BUNDLE.getString("twt.client_id"))
        .setOAuthConsumerSecret(BUNDLE.getString("twt.secret"))
        .setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token")
        .setOAuthAuthorizationURL(("https://api.twitter.com/oauth/authorize"))
        .setOAuthAccessTokenURL(("https://api.twitter.com/oauth/access_token"));
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    HttpServletRequest request =
        (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    HttpServletResponse response =
        (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    request.getSession().setAttribute("twitter", twitter);
    try {
      RequestToken requestToken =
          twitter.getOAuthRequestToken(BUNDLE.getString("twt.redirect_uri"));
      request.getSession().setAttribute("requestToken", requestToken);
      LOGGER.info("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
      try {
        response.sendRedirect(requestToken.getAuthenticationURL());
      } catch (IOException e) {
        e.printStackTrace();
      }

    } catch (TwitterException e) {
      e.printStackTrace();
    }
    return "";
  }
Exemplo n.º 10
0
  /** Function to login twitter */
  private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
      builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
      twitter4j.conf.Configuration configuration = builder.build();

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

      Thread thread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {

                    requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
                    Login_Activity.this.startActivity(
                        new Intent(
                            Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              });
      thread.start();

    } else {
      // user already logged into twitter
      Toast.makeText(context, "already logged in 2222", Toast.LENGTH_SHORT).show();
    }
  }
  @Override
  public IBinder onBind(Intent intent) {
    Log.d(TAG, "onBind()");
    configurationBuilder = new ConfigurationBuilder();
    configurationBuilder
        .setDebugEnabled(true)
        .setOAuthConsumerKey("JmPCgGdftlNXuh21WQ7hFA")
        .setOAuthConsumerSecret("drMLhPvOWs2Crol2LwQuqdKVRTFCVbQlkJQOCrV8uI")
        .setOAuthAccessToken("72023528-NFWdbv2h4vDVdZC1ML2jNT0gXt9fqZLpMdvtGDjnH")
        .setOAuthAccessTokenSecret("JW7Y2e8D086oDsU1wpNKgtsPZAwF1TQl5KkMdbHdnQ");
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();

    StatusListener statusListener =
        new StatusListener() {

          @Override
          public void onException(Exception arg0) {
            Log.d(TAG, "onException: cause," + arg0.getCause() + " message," + arg0.getMessage());
          }

          @Override
          public void onDeletionNotice(StatusDeletionNotice arg0) {
            Log.d(TAG, "onDeletionNotice()");
          }

          @Override
          public void onScrubGeo(long arg0, long arg1) {
            Log.d(TAG, "onScrubGeo()");
          }

          @Override
          public void onStallWarning(StallWarning stallWarning) {
            Log.d(TAG, "onStallWarning()");
          }

          @Override
          public void onStatus(Status status) {
            Log.d(
                TAG,
                "Twitter Status Received: Geolocation?:"
                    + (status.getGeoLocation() != null)
                    + " / "
                    + status.getUser().getScreenName()
                    + ": "
                    + status.getText());
            if (status.getGeoLocation() != null) {
              addNewTwitterStatus(status);
            }
          }

          @Override
          public void onTrackLimitationNotice(int arg0) {
            Log.d(TAG, "onTrackLimitationNotice()");
          }
        };
    twitterStream.addListener(statusListener);

    return mBinder;
  }
Exemplo n.º 12
0
 /**
  * Constructor to set the Twitter Access Details The details here are from a sample account i
  * created on twitter. if you have your account you can use that instead of this.
  */
 public TwitterClient() {
   cb = new ConfigurationBuilder();
   cb.setOAuthConsumerKey("X4X5rpyaRNvbwcVnV8j5i1izh");
   cb.setOAuthConsumerSecret("dosoSEWt0DeZbl0zO3Y61fiymszTvqrOZT9xzE8ikdI9imy1rl");
   cb.setOAuthAccessToken("2807566405-1jYRRu0Vs3tj3D56YM6ww4DqjByJqhLCl9Vpru9");
   cb.setOAuthAccessTokenSecret("svKkTebpr8jBmrmnfXiaygoYQndXJMPvo6CWIVniYrDb0");
   twitter = new TwitterFactory(cb.build()).getInstance();
 }
Exemplo n.º 13
0
 public TwitterUtil() {
   ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
   configurationBuilder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY);
   configurationBuilder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET);
   Configuration configuration = configurationBuilder.build();
   twitterFactory = new TwitterFactory(configuration);
   twitter = twitterFactory.getInstance();
 }
Exemplo n.º 14
0
  private void getTweetsFromTwitter() {
    try {
      ConfigurationBuilder confbuilder = new ConfigurationBuilder();
      confbuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
      confbuilder.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);

      btnLogoutTwitter.setVisibility(View.GONE);
      btnGetTweets.setVisibility(View.GONE);
      lblUserName.setVisibility(View.GONE);
      btnShowOnMap.setVisibility(View.GONE);
      btnUsers.setVisibility(View.GONE);

      Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance(accessToken);
      List<Status> statuses = twitter.getUserTimeline(USER_ID, new Paging(1, 10));

      IDs following = twitter.getFriendsIDs(USER_ID);

      long[] followingList = following.getIDs();

      for (int i = 0; i < followingList.length; i++) {

        Toast.makeText(getApplicationContext(), twitter.showUser(followingList[i]).toString(), 100)
            .show();
      }

      int count = 0;
      // Collections.reverse(statuses); // reverse order
      ArrayList<String> arrayList = new ArrayList<String>();
      for (Status status : statuses) {
        String tweettext =
            status.getUser().getName()
                + ":"
                + status.getText()
                + "\n ("
                + status.getCreatedAt().toLocaleString()
                + ")"
                + status.getGeoLocation();
        arrayList.add(tweettext);

        // now single tweet is in tweettext
      }

      ListView lv = (ListView) findViewById(R.id.storeTweet);
      ArrayAdapter<String> arrayAdapter =
          new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);

      lv.setAdapter(arrayAdapter);
    } catch (Exception ex) {
      // failed to fetch tweet
    }
  }
Exemplo n.º 15
0
 // Initialize the config of the builder with the user credentials
 public void initConfig() {
   ConfigurationBuilder cb = new ConfigurationBuilder();
   cb.setDebugEnabled(true)
       .setOAuthConsumerKey(AppliSettings.consumerKey)
       .setOAuthConsumerSecret(AppliSettings.consumerSecret)
       .setOAuthAccessToken(AppliSettings.accessToken)
       .setOAuthAccessTokenSecret(AppliSettings.accessTokenSecret);
   TwitterFactory tf = new TwitterFactory(cb.build());
   InterfaceG.twitter = tf.getInstance();
 }
Exemplo n.º 16
0
  /** Public API */
  public static void init(String consumerKey, String consumerSecret, String urlScheme) {
    if (mIsInitialized) return;

    mURLScheme = urlScheme;
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    mConfiguration = builder.build();
    mIsInitialized = true;
  }
  /**
   * 承認情報の生成
   *
   * @param userModel
   * @param msg
   * @return
   */
  private ConfigurationBuilder getConfigurationBuilder(UserModel userModel) throws Exception {

    // 承認情報の生成
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(Constants.TWITTER_APP_API_KEY)
        .setOAuthConsumerSecret(Constants.TWITTER_APP_API_SECRET)
        .setOAuthAccessToken(userModel.getTwitterAccessToken())
        .setOAuthAccessTokenSecret(userModel.getTwitterTokenSecret());

    return cb;
  }
Exemplo n.º 18
0
  /**
   * Method that handles the Twitter streaming API. <br>
   * <b>WARNING:</b> Method does not terminate by itself, due to the fact that the streamer runs in
   * a different thread.
   *
   * @param keywords The keywords for which the streamer searches for tweets.
   * @param mongoDB A handler for the MongoDB database.
   * @param config A configuration object.
   */
  public final void retrieveTweetsWithStreamingAPI(
      String[] keywords, MongoHandler mongoDB, Config config) {

    ConfigurationBuilder cb = getAuthorization();
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    final StatusListener listener;
    listener =
        new StatusListener() {

          @Override
          public final void onStatus(Status status) {
            // Insert tweet to MongoDB
            mongoDB.insertSingleTweetIntoMongoDB(status, "NULL");
          }

          @Override
          public final void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            PrintUtilities.printInfoMessageln(
                "Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
          }

          @Override
          public final void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            PrintUtilities.printInfoMessageln(
                "Got track limitation notice:" + numberOfLimitedStatuses);
          }

          @Override
          public final void onScrubGeo(long userId, long upToStatusId) {
            PrintUtilities.printInfoMessageln(
                "Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
          }

          @Override
          public final void onStallWarning(StallWarning warning) {
            PrintUtilities.printInfoMessageln("Got stall warning:" + warning);
          }

          @Override
          public final void onException(Exception ex) {
            ex.printStackTrace(System.out);
          }
        };

    FilterQuery fq = new FilterQuery();
    fq.language("en"); // Set language of tweets to "English"
    fq.track(keywords); // Load the search terms

    twitterStream.addListener(listener); // Start listening to the stream
    twitterStream.filter(fq); // Apply the search filters
  }
  /**
   * Twitter Post
   *
   * @param userModel
   * @param msg
   * @return
   */
  private void postMessage(UserModel userModel, String msg) throws Exception {

    System.out.println(msg);

    // 承認情報の生成
    ConfigurationBuilder cb = getConfigurationBuilder(userModel);

    // Titterオブジェクトの生成
    TwitterFactory twitterFactory = new TwitterFactory(cb.build());
    Twitter twitter = twitterFactory.getInstance();

    twitter.updateStatus(msg);
  }
Exemplo n.º 20
0
 public Twitter getTwitterInstance() {
   if (twitterInstance == null) {
     ConfigurationBuilder cb = new ConfigurationBuilder();
     cb.setDebugEnabled(true) // TODO disable logging for production
         .setOAuthConsumerKey(TWITTER_KEY)
         .setOAuthConsumerSecret(TWITTER_SECRET)
         .setOAuthAccessToken(accessToken)
         .setOAuthAccessTokenSecret(accessTokenSecret);
     TwitterFactory tf = new TwitterFactory(cb.build());
     twitterInstance = tf.getInstance();
   }
   return twitterInstance;
 }
Exemplo n.º 21
0
 /**
  * Set the proxy configuration for the univ or not
  *
  * @param checked : boolean sent by the controller
  */
 public void setProxy(boolean checked) throws IOException {
   if (checked) {
     ConfigurationBuilder cb = new ConfigurationBuilder();
     cb.setDebugEnabled(true)
         .setOAuthConsumerKey(AppliSettings.consumerKey)
         .setOAuthConsumerSecret(AppliSettings.consumerSecret)
         .setOAuthAccessToken(AppliSettings.accessToken)
         .setOAuthAccessTokenSecret(AppliSettings.accessTokenSecret)
         .setHttpProxyHost(AppliSettings.proxy)
         .setHttpProxyPort(AppliSettings.port);
     TwitterFactory tf = new TwitterFactory(cb.build());
     InterfaceG.twitter = tf.getInstance();
   }
 }
Exemplo n.º 22
0
  // 6355366
  private static void testTwitterAPI() throws Exception {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("qHzxaFrfzktB7DonlQXLzQ")
        .setOAuthConsumerSecret("WTcdE2vN9U3nl3t6mQkUbfF4PNNey2t2dp78AEajp8")
        .setOAuthAccessToken("351435596-KpFoMU2mdiu5OhdBi0BRPpdd7bQgkJFakkTV6Zh6")
        .setOAuthAccessTokenSecret("80OjYaYPmmKYG6DAUCSfstJEMPl2UnnLJunF8r0GGXQ");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    // DirectMessage msg = twitter.sendDirectMessage("prakash_sandeep", "test direct message1.");
    Status status = twitter.updateStatus("This is a test message13.");
    // System.out.println(msg + " published a message.");
  }
Exemplo n.º 23
0
  public void twitt(final String msg) {

    if (mTwitter == null) {
      ConfigurationBuilder confbuilder = new ConfigurationBuilder();
      Configuration conf =
          confbuilder
              .setOAuthConsumerKey(Const.CONSUMER_KEY)
              .setOAuthConsumerSecret(Const.CONSUMER_SECRET)
              .build();
      mTwitter = new TwitterFactory(conf).getInstance();
    }

    SharedPreferences pref = context.getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
    String accessToken = pref.getString(Const.PREF_KEY_ACCESS_TOKEN, null);
    String accessTokenSecret = pref.getString(Const.PREF_KEY_ACCESS_TOKEN_SECRET, null);
    if (accessToken == null || accessTokenSecret == null) {
      Toast.makeText(activity, "please Login first", Toast.LENGTH_SHORT).show();
      return;
    }
    mTwitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                boolean success = true;
                try {
                  mTwitter.updateStatus(msg);

                } catch (TwitterException e) {
                  e.printStackTrace();
                  success = false;
                }

                final boolean finalSuccess = success;

                activity.runOnUiThread(
                    new Runnable() {
                      @Override
                      public void run() {
                        if (twitterListener != null) {
                          twitterListener.onTwittCompleted(finalSuccess);
                        }
                      }
                    });
              }
            })
        .start();
  }
Exemplo n.º 24
0
  @Override
  public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    statuses = new LinkedBlockingQueue<Status>(1000);
    this.spoutOutputCollector = collector;

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder
        .setOAuthConsumerKey(consumerKey)
        .setOAuthConsumerSecret(consumerSecret)
        .setOAuthAccessToken(accessToken)
        .setOAuthAccessTokenSecret(accessTokenSecret);

    OAuthAuthorization authAuthorization = new OAuthAuthorization(configurationBuilder.build());

    twitterStream = new TwitterStreamFactory().getInstance(authAuthorization);
    twitterStream.addListener(
        new StatusListener() {
          @Override
          public void onStatus(Status status) {
            statuses.offer(status);
          }

          @Override
          public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}

          @Override
          public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}

          @Override
          public void onScrubGeo(long userId, long upToStatusId) {}

          @Override
          public void onStallWarning(StallWarning warning) {}

          @Override
          public void onException(Exception ex) {}
        });

    twitter = new TwitterFactory().getInstance(authAuthorization);
    filterQuery = new FilterQuery();

    if (filterQuery == null) {
      twitterStream.sample();
      ;
    } else {
      twitterStream.filter(filterQuery.track(filterWords));
      twitterStream.filter(filterQuery.language(filterLanguages));
    }
  }
  public void askOAuth(Context context) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(TwitterPrivateKeyAndSecret.CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(TwitterPrivateKeyAndSecret.CONSUMER_SECRET);
    Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

    try {
      requestToken = twitter.getOAuthRequestToken(TwitterConsts.CALLBACK_URL);
      context.startActivity(
          new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
 public static TwitterStream getTwitterStream() {
   AccessToken token = AccessTokenManager.getAccessToken();
   if (token == null) {
     return null;
   }
   ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
   twitter4j.conf.Configuration conf =
       configurationBuilder
           .setOAuthConsumerKey(getConsumerKey())
           .setOAuthConsumerSecret(getConsumerSecret())
           .setOAuthAccessToken(token.getToken())
           .setOAuthAccessTokenSecret(token.getTokenSecret())
           .build();
   return new TwitterStreamFactory(conf).getInstance();
 }
Exemplo n.º 27
0
  /** Function to login twitter */
  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())));

        String status = txtUpdate.getText().toString();

        // Check for blank text
        if (status.trim().length() > 0) {
          // update status
          new updateTwitterStatus().execute(status);
        } else {
          // EditText is empty
          Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT)
              .show();
        }
      } catch (TwitterException e) {
        e.printStackTrace();
      }
    } else {
      // user already logged into twitter
      /*Toast.makeText(getApplicationContext(),
      "Already Logged into twitter", Toast.LENGTH_LONG).show();*/

      String status = txtUpdate.getText().toString();

      // Check for blank text
      if (status.trim().length() > 0) {
        // update status
        new updateTwitterStatus().execute(status);
      } else {
        // EditText is empty
        Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT)
            .show();
      }
    }
  }
Exemplo n.º 28
0
 static {
   cb.setDebugEnabled(true)
       .setOAuthConsumerKey("ZuBFtIjHubaHmaomVCN6HNRI5")
       .setOAuthConsumerSecret("Ll0LZgKPly3QvIxIYMhtAxwxeUkleHc9Xya1Q5zAPxaga2wIpD")
       .setOAuthAccessToken("3095412628-4kLyHeZWV3p4Swmqx0d2lGSfJbtNqPbl0VPuMta")
       .setOAuthAccessTokenSecret("bKdTWWUVrtg1WtTog65t2XscxdvNbHszxDQLHBpZkutIG");
 }
  /** Posta in Twitt */
  public boolean postTwitt(String sMessage) {
    try {

      if (twitter != null) {
        try {
          AccessToken a =
              new AccessToken(
                  mSharedPreferences.getString(Const.PREF_KEY_TOKEN, ""),
                  mSharedPreferences.getString(Const.PREF_KEY_SECRET, ""));
          twitter.setOAuthAccessToken(a);
          Status oStatus = twitter.updateStatus(sMessage);
          Log.i(this.getClass().getCanonicalName(), "Post Twitter OK");
          return oStatus.isRetweet();
        } catch (IllegalArgumentException e) {
          Log.e(
              this.getClass().getCanonicalName(),
              "Post Twitter error: "
                  + mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "")
                  + " "
                  + mSharedPreferences.getString(Const.PREF_KEY_SECRET, ""));
          return false;
        }
      } else {
        String oauthAccessToken = mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "");
        String oAuthAccessTokenSecret = mSharedPreferences.getString(Const.PREF_KEY_SECRET, "");

        ConfigurationBuilder confbuilder = new ConfigurationBuilder();
        Configuration configuration =
            confbuilder
                .setOAuthConsumerKey(Const.CONSUMER_KEY)
                .setOAuthConsumerSecret(Const.CONSUMER_SECRET)
                .setOAuthAccessToken(oauthAccessToken)
                .setOAuthAccessTokenSecret(oAuthAccessTokenSecret)
                .build();
        twitter = new TwitterFactory(configuration).getInstance();

        Status oStatus = twitter.updateStatus(sMessage);
        Log.i(this.getClass().getCanonicalName(), "Post Twitter OK");
        return oStatus.isRetweet();
      }
    } catch (TwitterException e) {
      Log.e(this.getClass().getCanonicalName(), e.getMessage());
    } catch (NullPointerException e) {
      Log.e(this.getClass().getCanonicalName(), e.getMessage());
    }
    return false;
  }
  /**
   * Twitter Post
   *
   * @param userModel
   * @param msg
   * @return
   */
  private void imageUpload(UserModel userModel, String msg, String imagePath) throws Exception {

    URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
    HTTPResponse fetchResponse = fetchService.fetch(new URL(imagePath));

    InputStream inputStream = new ByteArrayInputStream(fetchResponse.getContent());

    // 承認情報の生成
    ConfigurationBuilder cb = getConfigurationBuilder(userModel);

    Configuration conf = cb.setMediaProvider(MediaProvider.TWITTER.name()).build();

    // ImageUploadオブジェクトの生成
    ImageUpload imageUpload = new ImageUploadFactory(conf).getInstance();

    imageUpload.upload("plucial-image", inputStream, msg);
  }