Пример #1
0
 private static void primeiraTwittada() throws TwitterException, IOException {
   Twitter twitter = TwitterFactory.getSingleton();
   twitter.setOAuthConsumer("HSPokkXFfwsjWwTGy8kfw", "zMNRv0G9kORPiSXcJuPrnWFOBESewPirr8Lf6fRLpA");
   RequestToken requestToken = twitter.getOAuthRequestToken();
   AccessToken accessToken = null;
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   while (null == accessToken) {
     System.out.println("Open the following URL and grant access to your account:");
     System.out.println(requestToken.getAuthorizationURL());
     System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
     String pin = br.readLine();
     try {
       if (pin.length() > 0) {
         accessToken = twitter.getOAuthAccessToken(requestToken, pin);
       } else {
         accessToken = twitter.getOAuthAccessToken();
       }
     } catch (TwitterException te) {
       if (401 == te.getStatusCode()) {
         System.out.println("Unable to get the access token.");
       } else {
         te.printStackTrace();
       }
     }
   }
   // persist to the accessToken for future reference.
   storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
   Status status = twitter.updateStatus("GO GO GO");
   System.out.println("Successfully updated the status to [" + status.getText() + "].");
   System.exit(0);
 }
Пример #2
0
 @Override
 protected User doInBackground(Void... params) {
   try {
     return mTwitter.verifyCredentials();
   } catch (TwitterException e) {
     return null;
   }
 }
Пример #3
0
 @Override
 public boolean test(Twitter api) {
   try {
     api.verifyCredentials();
     return true;
   } catch (TwitterException e) {
     return false;
   }
 }
  public boolean getFollowers(Twitter twitter) {
    boolean newActivity = false;

    try {
      List<User> followers =
          twitter.getFollowersList(
              useSecondAccount
                  ? AppSettings.getInstance(context).secondScreenName
                  : AppSettings.getInstance(context).myScreenName,
              -1,
              200);
      User me = twitter.verifyCredentials();

      int oldFollowerCount = sharedPrefs.getInt("activity_follower_count_" + currentAccount, 0);
      Set<String> latestFollowers =
          sharedPrefs.getStringSet(
              "activity_latest_followers_" + currentAccount, new HashSet<String>());

      Log.v(TAG, "followers set size: " + latestFollowers.size());
      Log.v(TAG, "old follower count: " + oldFollowerCount);
      Log.v(TAG, "current follower count: " + me.getFollowersCount());

      List<User> newFollowers = new ArrayList<User>();
      if (latestFollowers.size() != 0) {
        for (int i = 0; i < followers.size(); i++) {
          if (!latestFollowers.contains(followers.get(i).getScreenName())) {
            Log.v(TAG, "inserting @" + followers.get(i).getScreenName() + " as new follower");
            newFollowers.add(followers.get(i));
            newActivity = true;
          } else {
            break;
          }
        }
      }

      insertFollowers(newFollowers);

      latestFollowers.clear();
      for (int i = 0; i < 50; i++) {
        if (i < followers.size()) {
          latestFollowers.add(followers.get(i).getScreenName());
        } else {
          break;
        }
      }

      SharedPreferences.Editor e = sharedPrefs.edit();
      e.putStringSet("activity_latest_followers_" + currentAccount, latestFollowers);
      e.putInt("activity_follower_count_" + currentAccount, me.getFollowersCount());
      e.commit();
    } catch (TwitterException e) {
      e.printStackTrace();
    }

    return newActivity;
  }
Пример #5
0
 @Override
 public void setConnectionValues(Twitter api, ConnectionValues values) {
   try {
     User user = api.verifyCredentials();
     values.setProviderUserId(Long.toString(user.getId()));
     values.setDisplayName("@" + user.getScreenName());
     values.setProfileUrl("http://twitter.com/" + user.getScreenName());
     values.setImageUrl(user.getProfileImageURL());
   } catch (TwitterException e) {
   }
 }
Пример #6
0
 @Override
 public UserProfile fetchUserProfile(Twitter api) {
   try {
     User user = api.verifyCredentials();
     return new UserProfileBuilder()
         .setName(user.getName())
         .setUsername(user.getScreenName())
         .build();
   } catch (TwitterException e) {
     return null;
   }
 }
Пример #7
0
 public List<User> getFollowing(int num) {
   try {
     List<User> b = new ArrayList<User>();
     for (twitter4j.User u : twitter.getFriendsList(twitter.verifyCredentials().getId(), -1)) {
       b.add(new TwitterUser(u));
     }
     return b;
   } catch (TwitterException e) {
     e.printStackTrace();
     return null;
   }
 }
Пример #8
0
    @Override
    protected FetchUserTaskOutput doInBackground(FetchUserTaskInput... inputArray) {

      TwitterUser result = null;
      FetchUserTaskInput input = inputArray[0];

      if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) {
        return new FetchUserTaskOutput(
            new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()),
            input.mCallbackHandle,
            null);
      }

      String errorDescription = null;
      Twitter twitter = getTwitterInstance();
      if (twitter != null) {
        try {
          User user = null;
          if (input.mVerifyCredentials != null && input.mVerifyCredentials.booleanValue()) {
            Log.d("api-call", "verifyCredentials");
            user = twitter.verifyCredentials();
          } else {
            Log.d("api-call", "showUser");
            if (input.mUserId != null) {
              user = twitter.showUser(input.mUserId);
            } else if (input.mScreenName != null) {
              user = twitter.showUser(input.mScreenName);
            }
          }
          result = new TwitterUser(user);
          setUser(result);
        } catch (TwitterException e) {
          e.printStackTrace();
          errorDescription = e.getErrorMessage();
          Log.e("api-call", errorDescription, e);
          if (e.getRateLimitStatus() != null && e.getRateLimitStatus().getRemaining() <= 0) {
            errorDescription +=
                "\nTry again in " + e.getRateLimitStatus().getSecondsUntilReset() + " " + "seconds";
          }
        }
      } else {
        AppdotnetApi api = getAppdotnetApi();
        if (api != null && input.mUserId != null) {
          result = api.getAdnUser(input.mUserId);
          setUser(result);
        }
      }

      return new FetchUserTaskOutput(
          new TwitterFetchResult(errorDescription == null, errorDescription),
          input.mCallbackHandle,
          result);
    }
Пример #9
0
  public User getAuthenticatedUser() {
    User u = null;
    for (int i = 0; i < 5; i++) {
      try {
        u = new TwitterUser(twitter.verifyCredentials());
        return u;
      } catch (TwitterException e) {
        System.out.printf("Failed to get authenticated user; attempt %d%n", i);
        try {
          Thread.sleep(500);
        } catch (InterruptedException e2) {;
        }
      }
    }

    return u;
  }
  // 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;
  }
    protected Void doInBackground(Void... arg0) {
      try {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET);

        SharedPreferences mSharedPreferences =
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        // Access Token
        String access_token =
            mSharedPreferences.getString(ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN, "");
        // Access Token Secret
        String access_token_secret =
            mSharedPreferences.getString(ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET, "");

        AccessToken accessToken = new AccessToken(access_token, access_token_secret);
        Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
        User user = twitter.verifyCredentials();

        statuses = twitter.getHomeTimeline();

        String temp = "";
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (twitter4j.Status status : statuses) {
          System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
          temp = "@" + status.getUser().getScreenName() + " - " + status.getText() + "\n";

          tweetList.add(temp);
        }

      } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        // System.exit(-1);
      }
      return null;
    }
  /**
   * ユーザー情報取得用トークン取得メソッド
   *
   * @author 北山知輝
   * @since 2015/03/16
   * @return result 結果
   * @throws TwitterException
   * @throws IOException
   */
  public String[] loginOAuth(HttpServletResponse response, HttpServletRequest request)
      throws TwitterException, IOException {

    HttpSession session = request.getSession();
    Twitter twitter = (Twitter) session.getAttribute("Twitter");
    String verifier = request.getParameter("oauth_verifier");
    AccessToken accessToken = null;
    String userData[] = new String[2];

    try {
      // RequestTokenからAccessTokenを取得
      if (session.getAttribute("RequestToken") != null) {
        accessToken =
            twitter.getOAuthAccessToken(
                (RequestToken) session.getAttribute("RequestToken"), verifier);
      } else {
        userData[0] = "ゲスト";
        userData[1] = "ゲスト";
        return userData;
      }
    } catch (Exception e) {

    }

    if (accessToken != null) {
      // AccessTokenをセッションに保持
      session.setAttribute("AccessToken", accessToken.getToken());
      session.setAttribute("AccessTokenSecret", accessToken.getTokenSecret());
    }

    User user = twitter.verifyCredentials();

    userData[0] = user.getName();
    userData[1] = user.getScreenName();
    return userData;
  }
Пример #13
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    try {
      AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
      request.getSession().removeAttribute("requestToken");

      User user = twitter.verifyCredentials();
      // Store Access Token so that we can constantly poll twitter
      CallbackServlet.storeAccessToken(user, accessToken);

      response.sendRedirect(
          request.getContextPath()
              + "/enqueueTweets?twitterId="
              + user.getId()
              + "&twitterHandle="
              + user.getScreenName());
    } catch (TwitterException e) {
      throw new ServletException(e);
    }
    // response.sendRedirect(request.getContextPath() + "/");
  }
Пример #14
0
 private AccessToken requestToken() {
   RequestToken requestToken = null;
   try {
     requestToken = twitter.getOAuthRequestToken();
   } catch (TwitterException e) {
     e.printStackTrace();
   }
   AccessToken accessToken = null;
   Scanner scanner = new Scanner(System.in);
   while (null == accessToken) {
     System.out.println("Open the following URL and grant access to your account:");
     System.out.println(requestToken.getAuthorizationURL());
     System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:");
     String pin = scanner.nextLine();
     try {
       if (pin.length() > 0) {
         accessToken = twitter.getOAuthAccessToken(requestToken, pin);
       } else {
         accessToken = twitter.getOAuthAccessToken();
       }
     } catch (TwitterException te) {
       if (401 == te.getStatusCode()) {
         System.out.println("Unable to get the access token.");
       } else {
         te.printStackTrace();
       }
     }
   }
   // persist to the accessToken for future reference.
   try {
     storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
   } catch (TwitterException e) {
     e.printStackTrace();
   }
   return accessToken;
 }
Пример #15
0
  @Override
  public void authenticate() {
    if (httpServletRequest == null) {
      throw new IllegalStateException("http request not available");
    }
    if (httpServletResponse == null) {
      throw new IllegalStateException("http response not available");
    }
    if (configuration == null) {
      throw new IllegalStateException("configuration not available");
    }
    HttpSession session = httpServletRequest.getSession();

    ServletContext servletContext = httpServletRequest.getServletContext();

    String clientID = configuration.getClientID();
    String clientSecret = configuration.getClientSecret();
    String returnURL = configuration.getReturnURL();

    Principal principal = null;
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(clientID, clientSecret);

    // See if we are a callback
    String verifier = httpServletRequest.getParameter("oauth_verifier");
    RequestToken requestToken =
        (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    if (verifier != null && requestToken == null) {
      // Let us fall back
      String twitterSentRequestToken = httpServletRequest.getParameter("oauth_token");
      if (twitterSentRequestToken != null) {
        requestToken = (RequestToken) servletContext.getAttribute(twitterSentRequestToken);
      }
      if (requestToken == null) {
        throw new IllegalStateException("Verifier present but request token null");
      }
      // Discard the stored request tokens
      servletContext.removeAttribute(twitterSentRequestToken);
      session.removeAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    }
    if (requestToken != null && verifier != null) {
      try {
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        session.setAttribute("accessToken", accessToken);
        session.removeAttribute("requestToken");
      } catch (TwitterException e) {
        throw new AuthenticationException("Twitter Login:"******"Twitter Login:"******"Twitter Login:", e);
    }
    if (principal != null) {
      setStatus(AuthenticationStatus.SUCCESS);
      setAccount(new User(principal.getName()));
    }
  }
Пример #16
0
    @GET
    public Response authResponse(
        @QueryParam("state") String state,
        @QueryParam("denied") String denied,
        @QueryParam("oauth_verifier") String verifier) {

      try {
        Twitter twitter = new TwitterFactory().getInstance();

        twitter.setOAuthConsumer(getConfig().getClientId(), getConfig().getClientSecret());

        ClientSessionModel clientSession = parseClientSessionCode(state).getClientSession();

        String twitterToken = clientSession.getNote("twitter_token");
        String twitterSecret = clientSession.getNote("twitter_tokenSecret");

        RequestToken requestToken = new RequestToken(twitterToken, twitterSecret);

        AccessToken oAuthAccessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        twitter4j.User twitterUser = twitter.verifyCredentials();

        BrokeredIdentityContext identity =
            new BrokeredIdentityContext(Long.toString(twitterUser.getId()));
        identity.setIdp(TwitterIdentityProvider.this);

        identity.setUsername(twitterUser.getScreenName());
        identity.setName(twitterUser.getName());

        StringBuilder tokenBuilder = new StringBuilder();

        tokenBuilder.append("{");
        tokenBuilder
            .append("\"oauth_token\":")
            .append("\"")
            .append(oAuthAccessToken.getToken())
            .append("\"")
            .append(",");
        tokenBuilder
            .append("\"oauth_token_secret\":")
            .append("\"")
            .append(oAuthAccessToken.getTokenSecret())
            .append("\"")
            .append(",");
        tokenBuilder
            .append("\"screen_name\":")
            .append("\"")
            .append(oAuthAccessToken.getScreenName())
            .append("\"")
            .append(",");
        tokenBuilder
            .append("\"user_id\":")
            .append("\"")
            .append(oAuthAccessToken.getUserId())
            .append("\"");
        tokenBuilder.append("}");

        identity.setToken(tokenBuilder.toString());
        identity.setCode(state);
        identity.setIdpConfig(getConfig());

        return callback.authenticated(identity);
      } catch (Exception e) {
        logger.error("Could get user profile from twitter.", e);
      }
      EventBuilder event = new EventBuilder(realm, session, clientConnection);
      event.event(EventType.LOGIN);
      event.error("twitter_login_failed");
      return ErrorPage.error(session, Messages.UNEXPECTED_ERROR_HANDLING_RESPONSE);
    }
Пример #17
0
  public static void main(String[] args) {

    try {

      meet myobj = new meet();

      // load jsiconfig.txt
      ArrayList<String> myconfiglist = new ArrayList<String>();
      myconfiglist = myobj.loadArray("jsiconfig.txt");

      // The text uri
      // "mongodb://*****:*****@ds023288.mongolab.com:23288/sample";
      String textUri = myconfiglist.get(0);

      // Create MongoClientURI object from which you get MongoClient obj
      MongoClientURI uri = new MongoClientURI(textUri);

      // Connect to that uri
      MongoClient m = new MongoClient(uri);

      // get the database named sample
      String DBname = myconfiglist.get(1);
      DB d = m.getDB(DBname);

      // get the collection mycollection in sample
      String collectionName = myconfiglist.get(2);
      DBCollection collection = d.getCollection(collectionName);

      // System.out.println("Config: "+textUri+":"+DBname+":"+collectionName);

      // twitter4j
      // Twitter twitter = new TwitterFactory().getInstance();
      Twitter twitter = new TwitterFactory().getSingleton();
      User user = twitter.verifyCredentials();

      // Twitter collection of latest tweets into the home account - defaulted to latest 20 tweets//
      //////////////////////////////////////////////////////////////

      ArrayList<String> mylatesttweetslist = new ArrayList<String>();
      // get list of tweets from a user or the next tweet listed
      try {
        long actid = 0;
        // twitter.createFriendship(actid);

        // The factory instance is re-useable and thread safe.
        // Twitter twitter = TwitterFactory.getSingleton();
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing home timeline.");

        for (Status status : statuses) {

          // System.out.println(status.getUser().getName() + ":" +status.getText());
          // Addes timeline to an array
          String mytweets = status.getUser().getName() + ":" + status.getText();
          mylatesttweetslist.add(mytweets);
        }
        ;

      } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
      }

      // MongoDB Insert Below //
      //////////////////////////

      // System Date
      Date sd = new Date();
      String sysdate = sd.toString();

      // Toggle the below to display and insert the transactions as required
      boolean showtrans = true;
      boolean inserttrans = true;

      // checkArray - loads args to a text string to allow the contains function
      String checkString = "";
      for (int ck = 0; ck < args.length; ck++) {
        checkString = checkString + args[ck];
      }
      ;

      // display transactions flag on runnning jsimongo eg: java jsimongo -d  will NOT display
      // transactions
      // insert transactions flag on runnning jsimongo eg: java jsimongo -i  will NOT insert
      // transactions

      if (args.length > 0) {
        if (checkString.contains("-d")) showtrans = false;
        if (checkString.contains("-i")) inserttrans = false;
      }
      ;

      int x = 0;
      for (String atweet : mylatesttweetslist) {
        x++;
        // Display tweets to console
        if (showtrans == true) {
          System.out.println("tweet : " + atweet);
          System.out.println("Created_DateTime : " + sysdate); // was sysdate
        }
        ;

        // Insert JSON into MongoDB
        if (inserttrans == true) {
          BasicDBObject b = new BasicDBObject();
          System.out.println("tweet : " + atweet);
          System.out.println("Created_DateTime : " + sysdate); // was sysdate

          // Insert the JSON object into the chosen collection
          collection.insert(b);
        }
        ;
        Thread.sleep(1);
      }
      ;

      System.out.println("End, the number of tweets inserted at this time was: " + x);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }