private void tweet(String tweetText) {
    // SharedPreferencesからtokenとtoken secretの取得
    SharedPreferences spObj = getSharedPreferences("token", MODE_PRIVATE);
    String tokenStr = spObj.getString("token", "");
    String tokenSecretStr = spObj.getString("token_seacret", "");

    // twitterオブジェクトの作成
    Twitter tw = new TwitterFactory().getInstance();

    // AccessTokenオブジェクトの作成
    AccessToken at = new AccessToken(tokenStr, tokenSecretStr);

    // Consumer keyとConsumer key seacretの設定
    tw.setOAuthConsumer("iy2FEHXmSXNReJ6nYQ8FRg", "KYro4jM8BHlLSMsSdTylnTcm3pYaTCiG2UZrYK1yI4");

    // AccessTokenオブジェクトを設定
    tw.setOAuthAccessToken(at);

    // ツイート送信
    try {
      tw.updateStatus(tweetText);
    } catch (TwitterException e) {
      e.printStackTrace();
      Toast.makeText(this, "ネットーワークの問題です", Toast.LENGTH_LONG);
    }
  }
Beispiel #2
0
 public Collection<Tweet> requestTweetsByUser(String otherUser) {
   List<Tweet> tweets = new ArrayList<Tweet>();
   try {
     // The factory instance is re-useable and thread safe.
     Twitter twitter = new TwitterFactory().getInstance();
     AccessToken accessToken = loadAccessToken(1);
     twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
     twitter.setOAuthAccessToken(accessToken);
     System.out.println("Fetching latest 100 tweets for [" + otherUser + "]");
     // First param of Paging() is the page number, second is the number per page (this is capped
     // around 200 I think.
     Paging paging = new Paging(1, 100);
     List<Status> statuses = twitter.getUserTimeline(otherUser, paging);
     for (Status status : statuses) {
       tweets.add(
           new Tweet(
               otherUser,
               status.getText(),
               (status.getGeoLocation() != null
                   ? status.getGeoLocation().getLatitude()
                       + ","
                       + status.getGeoLocation().getLongitude()
                   : "")));
       System.out.println(
           status.getUser().getName() + "(" + status.getGeoLocation() + "):" + status.getText());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   }
   return tweets;
 }
  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;
  }
  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();
    }
  }
 private void initTwitter() {
   mTwitter = TwitterFactory.getSingleton();
   mTwitter.setOAuthConsumer(
       Configuration.INSTANCE.consumerToken, Configuration.INSTANCE.consumerSecret);
   mTwitter.setOAuthAccessToken(
       new AccessToken(Configuration.INSTANCE.accessToken, Configuration.INSTANCE.accessSecret));
 }
  @RequestMapping(value = "/{username}/accountInfo", method = RequestMethod.GET)
  public ResponseEntity<TwitterAccountInfo> getAccountInfo(@PathVariable String username) {

    TwitterAccountInfo twitterAccountInfo = new TwitterAccountInfo();

    TwitterCredentials twitterCredentials =
        twitterCredentialsService.getTwitterCredentialsForUsername(username);
    Twitter twitter = TwitterAppFactory.getTwitterInstance();
    AccessToken accessTokenObj =
        new AccessToken(
            twitterCredentials.getAccessToken(), twitterCredentials.getAccessTokenSecret());

    twitter.setOAuthAccessToken(accessTokenObj);

    try {
      String twitterScreenName = twitter.getScreenName();
      User twitterUser = twitter.showUser(twitterScreenName);

      twitterAccountInfo.setUsername(twitterScreenName);
      twitterAccountInfo.setFullName(twitterUser.getName());
      twitterAccountInfo.setProfileImageUrl(twitterUser.getProfileImageURL());
      twitterAccountInfo.setFollowersCount(twitterUser.getFollowersCount());
      twitterAccountInfo.setFriendsCount(twitterUser.getFriendsCount());

    } catch (Exception e) {
      LOG.warn(e.getMessage());
      return new ResponseEntity<TwitterAccountInfo>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<TwitterAccountInfo>(twitterAccountInfo, HttpStatus.OK);
  }
 /**
  * AccessTokenを設定します
  *
  * @param access AccessToken
  * @return 成功したか
  */
 public boolean setAccessToken(AccessToken access) {
   if (access == null) {
     return false;
   }
   this.access = access;
   twitter.setOAuthAccessToken(access);
   return true;
 }
  public Twitter getTwitter() {
    twitter = (new TwitterFactory()).getInstance();
    twitter.setOAuthConsumer(
        TwitterPrivateKeyAndSecret.CONSUMER_KEY, TwitterPrivateKeyAndSecret.CONSUMER_SECRET);

    twitter.setOAuthAccessToken(loadAccessToken());

    return twitter;
  }
  private ArrayAdapter<String> getTimeline() {
    SharedPreferences sp = getSharedPreferences("token", MODE_PRIVATE);
    String token = sp.getString("token", "");
    String tokenSecret = sp.getString("token_seacret", "");

    // twitterオブジェクトの作成
    Twitter tw = new TwitterFactory().getInstance();

    // AccessTokenオブジェクトの作成
    AccessToken at = new AccessToken(token, tokenSecret);

    // Consumer keyとConsumer key seacretの設定
    tw.setOAuthConsumer("iy2FEHXmSXNReJ6nYQ8FRg", "KYro4jM8BHlLSMsSdTylnTcm3pYaTCiG2UZrYK1yI4");

    // AccessTokenオブジェクトを設定
    tw.setOAuthAccessToken(at);

    try {
      // TLの取得
      ResponseList<Status> homeTl = tw.getHomeTimeline();

      ArrayAdapter<String> adapter =
          new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1);

      for (Status status : homeTl) {
        // つぶやきのユーザーIDの取得
        String userName = status.getUser().getScreenName();
        // つぶやきの取得
        String tweet = status.getText();
        adapter.add("ユーザーID:" + userName + "\r\n" + "tweet:" + tweet);
      }
      Status s = homeTl.get(homeTl.size());
      Paging p = new Paging();
      p.setMaxId(s.getId());

      homeTl = null;
      homeTl = tw.getHomeTimeline(p);

      for (Status status : homeTl) {
        // つぶやきのユーザーIDの取得
        String userName = status.getUser().getScreenName();
        // つぶやきの取得
        String tweet = status.getText();
        adapter.add("ユーザーID:" + userName + "\r\n" + "tweet:" + tweet);
      }

      return adapter;
    } catch (TwitterException e) {
      e.printStackTrace();
      if (e.isCausedByNetworkIssue()) {
        Toast.makeText(getApplicationContext(), "ネットワークに接続して下さい", Toast.LENGTH_LONG);
      } else {
        Toast.makeText(getApplicationContext(), "エラーが発生しました。", Toast.LENGTH_LONG);
      }
    }
    return null;
  }
  @Override
  public void publishUuid(TwitterStatusMessage message) throws Exception {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);

    AccessToken accessToken = new AccessToken(accessTokenStr, accessTokenSecretStr);
    twitter.setOAuthAccessToken(accessToken);

    twitter.updateStatus(message.getTwitterPublicationString());
  }
Beispiel #11
0
 private static void twittarAlgo() throws TwitterException {
   TwitterFactory factory = new TwitterFactory();
   AccessToken accessToken = loadAccessToken();
   Twitter twitter = factory.getInstance();
   twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
   twitter.setOAuthAccessToken(accessToken);
   Status status = twitter.updateStatus("go go go go");
   System.out.println("Successfully updated the status to [" + status.getText() + "].");
   System.exit(0);
 }
Beispiel #12
0
  public Twitter getTwitterProxy() throws TwitterException {
    if (twitter == null) {

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

      twitter.setOAuthConsumer(getConsumerKey(), getConsumerSecret());
      twitter.setOAuthAccessToken(new AccessToken(getAccessToken(), getAccessTokenSecret()));
    }
    return twitter;
  }
  /**
   * The user had previously given our app permission to use Twitter</br> Therefore we retrieve
   * these credentials and fill out the Twitter4j helper
   */
  private void loginAuthorisedUser() {
    String token = mPrefs.getString(Const.PREF_KEY_TOKEN, null);
    String secret = mPrefs.getString(Const.PREF_KEY_SECRET, null);

    // Create the twitter access token from the credentials we got previously
    AccessToken at = new AccessToken(token, secret);

    oTwitter.setOAuthAccessToken(at);

    Toast.makeText(this, "Welcome back Twitter", Toast.LENGTH_SHORT).show();
  }
 public void tweetNote(String symbol) {
   HttpSession session = super.getThreadLocalRequest().getSession();
   Twitter twitter = new TwitterFactory().getInstance();
   twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
   AccessToken accessToken = (AccessToken) session.getAttribute("accessToken");
   twitter.setOAuthAccessToken(accessToken);
   try {
     Status status = twitter.updateStatus(symbol);
   } catch (TwitterException e) {
     e.printStackTrace();
   }
 }
Beispiel #15
0
 private static List<Status> buscarTag(String tag) throws TwitterException {
   TwitterFactory factory = new TwitterFactory();
   AccessToken accessToken = loadAccessToken();
   Twitter twitter = factory.getInstance();
   twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
   twitter.setOAuthAccessToken(accessToken);
   Query query = new Query(tag);
   query.setCount(100);
   QueryResult result = twitter.search(query);
   // printResultadosConsulta(result);
   return result.getTweets();
 }
  public static Twitter getTwitter() {
    if (mTwitter != null) {
      return mTwitter;
    }
    Twitter twitter = getTwitterInstance();

    AccessToken token = AccessTokenManager.getAccessToken();
    if (token != null) {
      twitter.setOAuthAccessToken(token);
      // アクセストークンまである時だけキャッシュしておく
      mTwitter = twitter;
    }
    return twitter;
  }
  /**
   * Posts a status to Twitter.
   *
   * @param statusText Text of the messsage.
   * @param at AccessToken to validate with
   * @throws Exception
   */
  public void updateStatus(String statusText, AccessToken at) throws Exception {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(ourConsumerKey);
    cb.setOAuthConsumerSecret(ourConsumerSecret);
    cb.setOAuthAccessToken(at.getToken());
    cb.setOAuthAccessTokenSecret(at.getTokenSecret());

    myTwitter.setOAuthAccessToken(at);

    Status status = myTwitter.updateStatus(statusText);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
  }
  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();
  }
  public void LoginTwitter() {
    confbuilder = new ConfigurationBuilder();
    conf =
        confbuilder
            .setOAuthConsumerKey(Const.CONSUMER_KEY)
            .setOAuthConsumerSecret(Const.CONSUMER_SECRET)
            .build();
    mTwitter = new TwitterFactory(conf).getInstance();
    mTwitter.setOAuthAccessToken(null);

    new AsyncTask<Void, Void, RequestToken>() {
      protected void onPreExecute() {
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Loading...");
        pDialog.show();
      };

      @Override
      protected RequestToken doInBackground(Void... params) {
        // TODO Auto-generated method stub
        try {
          mRequestToken = mTwitter.getOAuthRequestToken(Const.CALLBACK_URL);
        } catch (TwitterException e) {
          e.printStackTrace();
        }
        return mRequestToken;
      }

      protected void onPostExecute(RequestToken mRequestToken) {
        if (pDialog.isShowing()) {

          pDialog.dismiss();
          pDialog = null;
        }
        if (mRequestToken != null && mRequestToken.getAuthorizationURL() != null) {
          Intent intent = new Intent(activity, TwitterLogin.class);
          intent.putExtra(Const.IEXTRA_AUTH_URL, mRequestToken.getAuthorizationURL());
          activity.startActivityForResult(intent, 0);
        } else {
          Toast.makeText(
                  activity,
                  "not able to connect this time due to low internet conntection...",
                  Toast.LENGTH_SHORT)
              .show();
        }
      };
    }.execute();
  }
Beispiel #20
0
  public void tweet(String tweet) {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
    AccessToken oathAccessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    twitter.setOAuthAccessToken(oathAccessToken);

    try {
      LoggerUtils.info("Tweeting: " + tweet);
      twitter.updateStatus(tweet);
    } catch (TwitterException ex) {
      LoggerUtils.warning(plugin, "Failed to Submit Tweet.");
    }

    LoggerUtils.info(plugin, "Tweet Successfully Sent");
  }
  /** 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;
  }
  private void loginWithTwitterWeb() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
    builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
    twitter4j.conf.Configuration configuration = builder.build();

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

    CookieSyncManager.createInstance(mContext);
    CookieManager cookiemanager = CookieManager.getInstance();
    cookiemanager.removeSessionCookie();
    twitter.setOAuthAccessToken(null);

    mTwitterWebDialog = new WebDialog(mContext, twitter);
    mTwitterWebDialog.show();
  }
  private List<User> getUserDataFromTwitterID(long[] userIdList, String userName) {
    if (userIdList != null) {
      try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        AccessToken accessToken = new AccessToken(accessTokenStr, accessTokenSecretStr);
        twitter.setOAuthAccessToken(accessToken);

        ResponseList<User> list = twitter.lookupUsers(userIdList);
        logger.info("Successfully looked up in Twitter by ID, size of list: " + list.size());
        return (list != null ? list : new ArrayList<User>());
      } catch (Exception e) {
        logger.error("Exception while getting user Data from TwitterId for user: " + userName, e);
      }
    }
    return new ArrayList<User>();
  }
  /**
   * Create an access token for this new user</br> Fill out the Twitter4j helper</br> And save these
   * credentials so we can log the user straight in next time
   *
   * @param oauthVerifier
   */
  private void authoriseNewUser(String oauthVerifier) {
    try {
      AccessToken at = oTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
      oTwitter.setOAuthAccessToken(at);

      saveAccessToken(at);

      // Set the content view back after we changed to a webview
      setContentView(R.layout.new_user_details);

    } catch (TwitterException e) {
      Log.e(this.getClass().getCanonicalName(), "Twitter auth error");
    } catch (IllegalStateException e) {
      Log.e(this.getClass().getCanonicalName(), "Twitter IllegalStateException error");
    } catch (NullPointerException e) {
      Log.e(this.getClass().getCanonicalName(), "Twitter NullPointerException error");
    }
  }
 /**
  * Gets a request token
  *
  * <p>If we decided that we need to do OAuth again to sign in, we get a request token from Twitter
  * via this call.
  */
 private static void requestToken(Context context) {
   Log.d(TAG, "Requesting token");
   isLoggedIn = false;
   try {
     /**
      * We say that we don't have an access token and then ask for a request token. We also tell
      * Twitter to redirect us to the callback url when the user finishes signing in via the
      * browser. Twitter gives us the request token and a url to redirect the user to for them to
      * sign in. This is all part of the OAuth process.
      */
     twitter.setOAuthAccessToken(null);
     requestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
     context.startActivity(
         new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
   } catch (TwitterException e) {
     e.printStackTrace();
   }
 }
  /**
   * Verifica se o programa já tem acesso a conta do usuario, caso negativo redireciona para pagina,
   * que gera uma autorização.
   *
   * @throws TwitterException
   * @throws IllegalStateException
   */
  @RequestMapping(value = "/verificaAcessoTwitter")
  public String verificaAcessoTwitter(ModelMap modelMap)
      throws IllegalStateException, TwitterException {
    Usuario usuarioAutorizado =
        usuarioService.getUsuarioByLogin(
            SecurityContextHolder.getContext().getAuthentication().getName());
    Twitter twitter = null;
    RequestToken requestToken = null;
    if (usuarioAutorizado.getAutorizacaoTwitter() != null) {
      twitter = new TwitterFactory().getInstance();
      twitter.setOAuthConsumer(
          "bVqAzGbuR5jsOTDstph9XB1dM", "vi9xVqIc1oMQAydQYIVgbo0GvO4XWwPjdhtJpjAUk6yv19vdDO");
      AccessToken accessToken =
          new AccessToken(
              usuarioAutorizado.getAutorizacaoTwitter().getToken(),
              usuarioAutorizado.getAutorizacaoTwitter().getTokenSecret());
      twitter.setOAuthAccessToken(accessToken);
      cadastroIdTwitterAmigos1E2Grau(usuarioAutorizado, twitter);

      return "redirect:/usuario/listar";
    }

    try {
      twitter = new TwitterFactory().getInstance();
      twitter.setOAuthConsumer(
          "bVqAzGbuR5jsOTDstph9XB1dM", "vi9xVqIc1oMQAydQYIVgbo0GvO4XWwPjdhtJpjAUk6yv19vdDO");
      requestToken = twitter.getOAuthRequestToken();
    } catch (TwitterException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // AccessToken accessToken = null;
    String url = requestToken.getAuthorizationURL();
    // System.out.println(twitter.getId());
    AutorizacaoTwitterRequest autorizacaoTwitterRequest = new AutorizacaoTwitterRequest();
    autorizacaoTwitterRequest.setRequestToken(requestToken);
    autorizacaoTwitterRequest.setTwitter(twitter);
    autorizacaoTwitterRequestService.save(autorizacaoTwitterRequest);
    modelMap.addAttribute("url", url);
    modelMap.addAttribute("id", autorizacaoTwitterRequest.getId());
    modelMap.addAttribute("pin", new Pin());
    return "usuario/autorizacaoTwitter";
  }
  private String getLatestTweet(String searchingFor) {

    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken =
        new AccessToken(
            "2453751158-IVD2VGZsvwZiRKxNe3Gs2lMjg30nvSkV1xSuPFf",
            "vBa5PjKfuMTK1LLBG51nCUI9r5d6Ph5cAHrS73spg6Nvu");
    twitter.setOAuthConsumer(
        "YqeZdD2hYxOKv4QOkmp0i2djN", "6XUB1r8KXBvd8Pk9HHW3NgphMxHvHWBLAr5TihnckMU0ttyGST");
    twitter.setOAuthAccessToken(accessToken);

    Query query = new Query(searchingFor);
    try {
      QueryResult result = twitter.search(query);
      return result.getTweets().get(0).getText();
    } catch (Exception e) {
      System.err.print(e.getMessage());
      return "What the heck is that?";
    }
  }
Beispiel #28
0
  @Override
  public void initialize(final URL location, final ResourceBundle resources) {
    String consumerKey = OAuth.getConsumerKey();
    String consumerKeySec = OAuth.getConsumerKeySec(); // 外部テキストから読み込む(直接入力でも可)
    twitter.setOAuthConsumer(consumerKey, consumerKeySec);
    AccessToken accessToken = OAuth.loadAccessToken();

    // OAuth認証
    if (accessToken == null) {
      accessToken = OAuth.getOAuthAccessToken(twitter);
      OAuth.storeAccessToken(accessToken);
    } else {
      twitter.setOAuthAccessToken(accessToken);
    }

    // ユーザ情報の管理
    try {
      reloadHomeTL(lastStatusId);
    } catch (TwitterException e) {
      e.printStackTrace();
    }
    /*
    for(UserInfo userInfo : userInfoList){
    	observableList.add(0, userInfo);
    }
    listView.setItems(observableList);
    */
    lastStatusId = homeTL.get(0).getId();

    // API制限の確認(コンソール)
    rateLimit = homeTL.getRateLimitStatus();

    // セル生成
    listView.setCellFactory(
        new Callback<ListView<UserInfo>, ListCell<UserInfo>>() {
          @Override
          public ListCell<UserInfo> call(ListView<UserInfo> list) {
            return new UserInfoCell();
          }
        });
  }
  // make sure to enable read, write, direct permission and
  // check the allow applications on settings
  protected User getUserLogin(Twitter twitter, HttpSession session, String oauthVerifier) {
    // try to get credentials
    User user = null;

    if (session.getAttribute("requestToken") != null) {

      try {
        RequestToken requestToken = (RequestToken) session.getAttribute("requestToken");
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier);
        session.setAttribute("accessToken", accessToken);
        twitter.setOAuthAccessToken(accessToken);
        user = twitter.verifyCredentials();
      } catch (TwitterException e) {
        if (e.getStatusCode() == 401) {
          Logger.getLogger(TwitterInfo.class.getName()).info(e.getMessage());
        } else {
          Logger.getLogger(TwitterInfo.class.getName()).severe(e.getMessage());
        }
      }
    }
    return user;
  }
 private void configureToken() {
   if (accessToken != null) {
     twitter.setOAuthConsumer(consumerKey, secretKey);
     twitter.setOAuthAccessToken(accessToken);
   }
 }