コード例 #1
0
  public TwitterClient(String fileName) throws IOException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
  }
コード例 #2
0
ファイル: MainServlet.java プロジェクト: MengyuWu/tweetMapWeb
 static {
   cb.setDebugEnabled(true)
       .setOAuthConsumerKey("ZuBFtIjHubaHmaomVCN6HNRI5")
       .setOAuthConsumerSecret("Ll0LZgKPly3QvIxIYMhtAxwxeUkleHc9Xya1Q5zAPxaga2wIpD")
       .setOAuthAccessToken("3095412628-4kLyHeZWV3p4Swmqx0d2lGSfJbtNqPbl0VPuMta")
       .setOAuthAccessTokenSecret("bKdTWWUVrtg1WtTog65t2XscxdvNbHszxDQLHBpZkutIG");
 }
コード例 #3
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);
    }
  }
コード例 #4
0
  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 "";
  }
コード例 #5
0
  @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;
  }
コード例 #6
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();
 }
コード例 #7
0
ファイル: TwitterTest.java プロジェクト: nAk123/iwa-project
  // construct Twitter instance using configuration
  static {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
    cb.setOAuthAccessToken(ACCESS_TOKEN);
    cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);

    Configuration conf = cb.build();

    twitter = new TwitterFactory(conf).getInstance();
    auth = new OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  }
コード例 #8
0
ファイル: Session.java プロジェクト: huluwa/TwitterLists
 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;
 }
コード例 #9
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();
   }
 }
コード例 #10
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.");
  }
コード例 #11
0
  /**
   * 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() + "].");
  }
コード例 #12
0
  @PostConstruct
  public void init() {

    if (config.getTransportType() != TransportType.Twitter) {
      return;
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey(config.getTwitterConsumerKey())
        .setOAuthConsumerSecret(config.getTwitterConsumerSecret())
        .setOAuthAccessToken(config.getTwitterAccessToken())
        .setOAuthAccessTokenSecret(config.getTwitterAccessTokenSecret())
        .setIncludeEntitiesEnabled(true);

    twitter = new TwitterFactory(cb.build()).getInstance();
  }
コード例 #13
0
  private static Twitter getTwitter(HandlerContext handlerContext) {
    Twitter res = (Twitter) handlerContext.get("twitter");
    if (res == null) {
      TwitterLinksHandlerConfig twitterLinksHandlerConfig =
          (TwitterLinksHandlerConfig) handlerContext.getHandlerConfig();
      ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
      configurationBuilder
          .setDebugEnabled(true)
          .setOAuthConsumerKey(twitterLinksHandlerConfig.getOauthConsumerKey());
      configurationBuilder.setOAuthConsumerSecret(
          twitterLinksHandlerConfig.getOauthConsumerSecret());
      configurationBuilder.setOAuthAccessToken(twitterLinksHandlerConfig.getOauthAccessToken());
      configurationBuilder.setOAuthAccessTokenSecret(
          twitterLinksHandlerConfig.getOauthAccessTokenSecret());
      TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());
      res = twitterFactory.getInstance();

      handlerContext.put("twitter", res);
    }
    return res;
  }
コード例 #14
0
  public static void main(String[] args) {
    try {
      ConfigurationBuilder cb = new ConfigurationBuilder();
      cb.setDebugEnabled(true).setOAuthConsumerKey("fSjrQedRpuRcUv3AmzUqkicCR");
      cb.setDebugEnabled(true)
          .setOAuthConsumerSecret("nGY8pyGD1CsYXaBb8SpeqoHHWYHE8pWeNmiR8Kc7UfWK5bJvTe");
      cb.setDebugEnabled(true)
          .setOAuthAccessToken("98946486-yZqWgilcljm4oVkT82euEDTl0UNna7t8R3F9rGEKZ");
      cb.setDebugEnabled(true)
          .setOAuthAccessTokenSecret("4GKOaU5OAksbNRz5rJy8uGxDM7vtzD3mJBCVJ2uU4qyNa");
      TwitterFactory tf = new TwitterFactory(cb.build());
      Twitter twitter = tf.getInstance();

      ArrayList<TwitterUser> users = new ArrayList<>();

      RateLimitStatus followers = twitter.getRateLimitStatus("followers").get("/followers/ids");
      System.out.println("followers " + followers.getRemaining());
      RateLimitStatus following = twitter.getRateLimitStatus("friends").get("/friends/ids");
      System.out.println("following " + following.getRemaining());

      if (followers.getRemaining() < 2 && following.getRemaining() < 2) {
        System.out.println("Durmiendo por aqui...");
        Thread.sleep(900000);
      }
      TwitterUser me = new TwitterUser(twitter);
      me.setUserID(twitter.getId());
      me.setFollowers(); // 1 follower
      me.setFollowings(); // 1 following
      users.add(me);

      for (int i = 0; i < 10; i++) { // 20 requests
        if (followers.getRemaining() < 2 && following.getRemaining() < 2) {
          System.out.println("Durmiendo por aqui... I=" + i);
          Thread.sleep(900000);
        }
        TwitterUser userX = new TwitterUser(me.getFollowers()[i], twitter);
        userX.setFollowers();
        userX.setFollowings();
        users.add(userX);
        for (int j = 0; j < 10; j++) {
          if (followers.getRemaining() < 2 && following.getRemaining() < 2) {
            System.out.println("Durmiendo por aqui... I=" + i + "J=" + j);
            Thread.sleep(900000);
          }
          TwitterUser userX_1 = new TwitterUser(userX.getFollowers()[j], twitter);
          userX_1.setFollowers();
          userX_1.setFollowings();
          users.add(userX_1);
        }
      }

      for (int i = 0; i < 10; i++) { // 20 requests
        if (followers.getRemaining() < 2 && following.getRemaining() < 2) {
          System.out.println("Durmiendo por aqui... I=" + i);
          Thread.sleep(900000);
        }
        TwitterUser userX = new TwitterUser(me.getFollowings()[i], twitter);
        userX.setFollowers();
        userX.setFollowings();
        users.add(userX);
        for (int j = 0; j < 10; j++) {
          if (followers.getRemaining() < 2 && following.getRemaining() < 2) {
            System.out.println("Durmiendo por aqui... I=" + i + "J=" + j);
            Thread.sleep(900000);
          }
          TwitterUser userX_1 = new TwitterUser(userX.getFollowings()[j], twitter);
          userX_1.setFollowers();
          userX_1.setFollowings();
          users.add(userX_1);
        }
      }

      String content = "";
      for (TwitterUser user : users) {
        content += user.toString();
      }
      File file = new File("/users/cbanegas/Desktop/filename.txt");
      if (!file.exists()) {
        file.createNewFile();
      }
      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(content);
      bw.close();
      System.out.println("Done");
    } catch (TwitterException te) {
      Logger.getLogger(TwitterUser.class.getName()).log(Level.SEVERE, null, te);
      System.out.println("twitter basura");
    } catch (IOException ex) {
      Logger.getLogger(TwitterGraph.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
      Logger.getLogger(TwitterGraph.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #15
0
  public void loadMenu() throws InterruptedException {

    System.out.print("Please choose a name for your stream:\t");

    Scanner input = new Scanner(System.in);
    String keyword = input.nextLine();

    connectdb(keyword);

    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("XXX");
    cb.setOAuthConsumerSecret("XXX");
    cb.setOAuthAccessToken("XXX");
    cb.setOAuthAccessTokenSecret("XXX");

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener =
        new StatusListener() {

          public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());

            BasicDBObject basicObj = new BasicDBObject();
            basicObj.put("user_name", status.getUser().getScreenName());
            basicObj.put("retweet_count", status.getRetweetCount());
            basicObj.put("tweet_followers_count", status.getUser().getFollowersCount());
            basicObj.put("source", status.getSource());
            // basicObj.put("coordinates",tweet.getGeoLocation());

            UserMentionEntity[] mentioned = status.getUserMentionEntities();
            basicObj.put("tweet_mentioned_count", mentioned.length);
            basicObj.put("tweet_ID", status.getId());
            basicObj.put("tweet_text", status.getText());

            try {
              items.insert(basicObj);
            } catch (Exception e) {
              System.out.println("MongoDB Connection Error : " + e.getMessage());
            }
          }

          public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println(
                "Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
          }

          public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
          }

          public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println(
                "Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
          }

          @Override
          public void onStallWarning(StallWarning stallWarning) {
            // To change body of implemented methods use File | Settings | File Templates.
          }

          public void onException(Exception ex) {
            ex.printStackTrace();
          }
        };

    FilterQuery fq = new FilterQuery();
    String keywords[] = {"Germany"};

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
  }
コード例 #16
0
  public static void main(String[] args) {

    PropertyConfigurator.configure(Constants.LOG4J_PROPERTIES_FILE_PATH);

    try {

      ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
      configurationBuilder
          .setDebugEnabled(true)
          .setOAuthConsumerKey(Constants.OAUTH_CONSUMER_KEY)
          .setOAuthConsumerSecret(Constants.OAUTH_CONSUMER_SECRET)
          .setOAuthAccessToken(Constants.OAUTH_ACCESS_TOKEN)
          .setOAuthAccessTokenSecret(Constants.OAUTH_ACCESS_TOKEN_SECRET);
      TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());

      LinkedBlockingQueue<String> categoryFetchingQueue = new LinkedBlockingQueue<String>();
      PriorityBlockingQueue<UserCategoryMessage> userFetchingQueue =
          new PriorityBlockingQueue<UserCategoryMessage>();
      LinkedBlockingQueue<TweetCategoryMessage> tweetStorageQueue =
          new LinkedBlockingQueue<TweetCategoryMessage>();

      Thread suggestedCategoryThread =
          new GetSuggestedUserCategoriesThread(twitterFactory, categoryFetchingQueue);
      Thread usersInCategoryThread =
          new GetUserSuggestionsForSlugThread(
              twitterFactory,
              categoryFetchingQueue,
              userFetchingQueue,
              GlobalConstants.USER_LAST_TWEET_ID_TABLE_NAME);
      Thread tweetsForUserThread =
          new GetUserTimelineThread(
              twitterFactory,
              userFetchingQueue,
              tweetStorageQueue,
              GlobalConstants.USER_LAST_TWEET_ID_TABLE_NAME);
      Thread tweetStorageThread =
          new TweetStorageThread(
              tweetStorageQueue, GlobalConstants.CATEGORY_TWEET_STORAGE_TABLE_NAME);

      Thread queueMeasurementThread =
          new QueueMeasurementThread(categoryFetchingQueue, userFetchingQueue, tweetStorageQueue);

      suggestedCategoryThread.start();
      usersInCategoryThread.start();
      tweetsForUserThread.start();
      tweetStorageThread.start();
      queueMeasurementThread.start();

      suggestedCategoryThread.join();
      usersInCategoryThread.join();
      tweetsForUserThread.join();
      tweetStorageThread.join();
      queueMeasurementThread.join();

    } catch (InterruptedException interruptedException) {
      logger.warn("Exception while collector threads are joining", interruptedException);
    } catch (Exception unknownException) {
      logger.error("Unknown Exception while starting collector_categories", unknownException);
      crisisMailer.sendEmailAlert(unknownException);
    }

    logger.error("CategoryCollectorDriver has stopped of own free will");
    crisisMailer.sendEmailAlert(
        "collector_categories: CategoryCollectorDriver has stopped of own free will");
  }
コード例 #17
0
ファイル: TweetGetter.java プロジェクト: vthacker/pigskin
  public static void main(String[] args)
      throws IOException, TwitterException, FileNotFoundException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("vGsMAca82HjVYYm7wQlN5Q")
        .setOAuthConsumerSecret("6mpRAAlMI6sIWruQNpomBzN1kIfodHexYBrKWPKmsuM")
        .setOAuthAccessToken("776768857-hCnK0Eu3orKK6qP98W7LyTF29QXadxydL21gIuon")
        .setOAuthAccessTokenSecret("V3VAJgO2x1zWO2JMHsRRrWLzYOeXxmlittF1pBBNWA4");

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    System.out.println("time " + System.currentTimeMillis());

    StatusListener listener =
        new StatusListener() {
          int counter = 0;
          FileWriter fstream = new FileWriter("/Users/jacobportnoff/Desktop/week7SunJ.txt");
          BufferedWriter out = new BufferedWriter(fstream);
          long start = System.currentTimeMillis();
          double elapsedTimeSec = 0.0;

          public void onStatus(Status status) {
            HashtagEntity[] hashtags = status.getHashtagEntities();
            String hashes = "";
            if (hashtags.length == 0) {
              hashes = "null";
            } else {
              for (HashtagEntity hash : hashtags) {
                hashes = hashes + hash.getText() + " ";
              }
            }
            String tweet =
                status.getCreatedAt()
                    + "\t"
                    + status.getUser().getScreenName()
                    + "\t"
                    + status.getText()
                    + "\t"
                    + status.getGeoLocation()
                    + "\t"
                    + hashes
                    + "\n";
            // System.out.print(tweet);
            try {
              out.write(tweet);
            } catch (Exception e) { // Catch exception if any
              System.err.println("Error: " + e.getMessage());
            }
          }

          public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}

          public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}

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

          public void onException(Exception ex) {
            ex.printStackTrace();
          }
        };
    twitterStream.addListener(listener);
    twitterStream.sample();
  }
コード例 #18
0
  Autorizacion() throws IOException, TwitterException { // Constructor de la clase
    ConfigurationBuilder configBuilder = new ConfigurationBuilder();
    configBuilder
        .setDebugEnabled(true)
        .setOAuthConsumerKey(new Tokens().OAuthConsumerKey)
        .setOAuthConsumerSecret(new Tokens().OAuthConsumerSecret);
    Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
    RequestToken requestToken = null;
    AccessToken accessToken = null;
    String url = null;
    do {
      try {
        requestToken = OAuthTwitter.getOAuthRequestToken();
        System.out.println("Request Tokens obtenidos con éxito.");
        /*System.out.println("Request Token: " + requestToken.getToken());
        System.out.println("Request Token secret: " + requestToken.getTokenSecret());*/
        url = requestToken.getAuthorizationURL();
      } catch (TwitterException ex) {
        Logger.getLogger(twittApp_java.class.getName()).log(Level.SEVERE, null, ex);
      }
      BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in));
      // Abro el navegador.

      Runtime runtime = Runtime.getRuntime();
      try {
        runtime.exec("firefox " + url);
      } catch (Exception e) {
      }
      // Nos avisa de que introduciremos el PIN a continuación
      System.out.print("Introduce el PIN del navegador y pulsa intro.\n\n PIN: ");
      // Leemos el PIN
      String pin = lectorTeclado.readLine();

      if (pin.length() > 0) {
        accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin);
      } else {
        accessToken = OAuthTwitter.getOAuthAccessToken(requestToken);
      }

    } while (accessToken == null);

    System.out.println("\n\nAccess Tokens obtenidos con éxito.");
    /*System.out.println("Access Token: " + accessToken.getToken());
    System.out.println("Access Token secret: " + accessToken.getTokenSecret());*/
    FileOutputStream fileOS = null;
    File file;
    String content = accessToken.getToken() + "\n" + accessToken.getTokenSecret();
    try {
      file = new File(System.getProperty("user.home") + "/auth_file.txt".replace("\\", "/"));
      fileOS = new FileOutputStream(file);
      // Si el archivo no existe, se crea
      if (!file.exists()) {
        file.createNewFile();
      }
      // Se obtiene el contenido en Bytes
      byte[] contentInBytes = content.getBytes();
      fileOS.write(contentInBytes);
      fileOS.flush();
      fileOS.close();
      System.out.println("Escritura realizada con éxito.");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileOS != null) {
          fileOS.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      twittApp_java cliente = new twittApp_java();
    }
  }
コード例 #19
0
  private static ArrayList<String> ProcessTimeLine(String user)
      throws InterruptedException, TwitterException {
    ArrayList<String> Tweets = new ArrayList<String>();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey(KEY)
        .setOAuthConsumerSecret(SECRET)
        .setOAuthAccessToken(ACCESSTOKEN)
        .setOAuthAccessTokenSecret(ACCESSSECRET);
    cb.setJSONStoreEnabled(true);

    // gets Twitter instance with default credentials
    boolean bWait = true;
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    do {
      try {
        Map<String, RateLimitStatus> oRT = twitter.getRateLimitStatus();
        RateLimitStatus rateLimit = oRT.get("/statuses/user_timeline");
        int remaining = rateLimit.getRemaining();
        System.out.print("(Remaining API calls: " + remaining + ")");
        int remainingTime = rateLimit.getSecondsUntilReset();

        if (remaining <= NUM_TWEETS / 200 + 1) {
          System.out.println("Waiting " + remainingTime + " seconds");
          Thread.sleep(remainingTime * 1000);
        } else bWait = false;

      } catch (Exception te) {
        if (te.toString().toLowerCase().contains("rate limit")
            && !te.toString().toLowerCase().contains("bad authentication data")) {
          System.out.println("Waiting 60s");
          Thread.sleep(60 * 1000);
        } else {
          bWait = false;
        }
      }
    } while (bWait);

    try {
      Detector detector = DetectorFactory.create();
      List<Status> statuses;

      int iPage = 1;
      int iTweets = 0;
      do {

        int iPageSize = 0;
        if (iTweets + 200 < NUM_TWEETS) {
          iPageSize = 200;
        } else {
          iPageSize = NUM_TWEETS - iTweets;
        }
        statuses = twitter.getUserTimeline(user, new Paging(iPage, iPageSize));

        for (Status status : statuses) {

          String sStatusId = "-1";
          try {
            if ((status.getRetweetedStatus() != null)
                && (status.getRetweetedStatus().getUser() != null)) {
              continue;
            }

            try {
              detector.append(Simplify(status.getText()));
              if (detector.detect().equalsIgnoreCase("es")) {
                String sStatusJSON = DataObjectFactory.getRawJSON(status);
                Tweets.add(sStatusJSON);
              }
            } catch (Exception exl) {
            }
          } catch (Exception ex) {
            System.out.println("ERROR in status id " + sStatusId);
          }

          iTweets++;
        }
        iPage++;
      } while (statuses.size() > 0 && iTweets < NUM_TWEETS);

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

    }

    System.out.println("..." + Tweets.size() + " tweets.");

    return Tweets;
  }