Esempio n. 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);
 }
  /**
   * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
   *
   * @param args message
   */
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
      System.exit(-1);
    }
    try {
      Twitter twitter = new TwitterFactory().getInstance();
      try {
        // get request token.
        // this will throw IllegalStateException if access token is already available
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        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 available) and hit enter after you granted access.[PIN]:");
          String pin = br.readLine();
          try {
            if (pin.length() > 0) {
              accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
              accessToken = twitter.getOAuthAccessToken(requestToken);
            }
          } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
              System.out.println("Unable to get the access token.");
            } else {
              te.printStackTrace();
            }
          }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());
      } catch (IllegalStateException ie) {
        // access token is already available, or consumer key/secret is not set.
        if (!twitter.getAuthorization().isEnabled()) {
          System.out.println("OAuth consumer key/secret is not set.");
          System.exit(-1);
        }
      }
      Status status = twitter.updateStatus(args[0]);
      System.out.println("Successfully updated the status to [" + status.getText() + "].");
      System.exit(0);
    } catch (TwitterException te) {
      te.printStackTrace();
      System.out.println("Failed to get timeline: " + te.getMessage());
      System.exit(-1);
    } catch (IOException ioe) {
      ioe.printStackTrace();
      System.out.println("Failed to read the system input.");
      System.exit(-1);
    }
  }
Esempio n. 3
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.twitter_add);
   accountdb = new AccountDB(this);
   twitter = new TwitterFactory().getInstance();
   twitter.setOAuthConsumer(consumerKey, consumerSecret);
   try {
     rqToken = twitter.getOAuthRequestToken(CALLBACK_URL.toString());
   } catch (TwitterException e) {
     e.printStackTrace();
   }
   token = rqToken.getToken();
   stoken = rqToken.getTokenSecret();
   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rqToken.getAuthorizationURL())));
 }
Esempio n. 4
0
  private void executeOauth() {
    // Twitetr4jの設定を読み込む
    Configuration conf = ConfigurationContext.getInstance();

    // Oauth認証オブジェクト作成
    _oauth = new OAuthAuthorization(conf);
    // Oauth認証オブジェクトにconsumerKeyとconsumerSecretを設定
    _oauth.setOAuthConsumer("iy2FEHXmSXNReJ6nYQ8FRg", "KYro4jM8BHlLSMsSdTylnTcm3pYaTCiG2UZrYK1yI4");
    // アプリの認証オブジェクト作成
    try {
      _req = _oauth.getOAuthRequestToken("Callback://CallBackActivity");
    } catch (TwitterException e) {
      e.printStackTrace();
    }
    String _uri;
    _uri = _req.getAuthorizationURL();
    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(_uri)), 0);
  }
  /**
   * Requests an access token from Twitter.
   *
   * @return
   */
  public AccessToken requestAccessToken() throws IOException, URISyntaxException {

    AccessToken accessToken = null;
    try {
      while (null == accessToken) {
        java.awt.Desktop.getDesktop().browse(new URI(myRequestToken.getAuthorizationURL()));
        String pin = javax.swing.JOptionPane.showInputDialog("Enter PIN:");
        accessToken = myTwitter.getOAuthAccessToken(myRequestToken, pin);
      }
    } catch (TwitterException te) {
      if (401 == te.getStatusCode()) {
        System.out.println("Unable to get the access token.");
      } else {
        te.printStackTrace();
      }
    }
    return accessToken;
  }
  /**
   * 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 TwitterInfo requestToken(Twitter twitter, HttpSession session) {
    RequestToken requestToken;
    try {
      session.setAttribute("token", null);
      session.setAttribute("tokenSecret", null);
      requestToken = twitter.getOAuthRequestToken();
    } catch (TwitterException e) {
      Logger.getLogger(TwitterInfo.class.getName()).severe(e.getMessage());
      return null;
    }

    session.setAttribute("requestToken", requestToken);

    Object a = requestToken.getAuthenticationURL();

    TwitterInfo result = new TwitterInfo();
    result.setLoginURL(requestToken.getAuthorizationURL());

    return result;
  }
Esempio n. 8
0
    @Override
    protected void onProgressUpdate(Void... values) {
      // Check if this task has been cancelled.
      if (checkCancellation("onProgressUpdate()")) {
        // Not load the authorization URL.
        return;
      }

      // In this implementation, onProgressUpdate() is called
      // only from authorize().

      // The authorization URL.
      String url = requestToken.getAuthorizationURL();

      if (isDebugEnabled()) {
        Log.d(TAG, "Loading the authorization URL: " + url);
      }

      // Load the authorization URL on the UI thread.
      TwitterOAuthView.this.loadUrl(url);
    }
Esempio n. 9
0
  private void executeOauth() {

    // ConfigurationBuilder
    ConfigurationBuilder cb = new ConfigurationBuilder();
    // Set Consumers
    cb.setOAuthConsumerKey("DZPpj7XHoSqWEiL736cpjw");
    cb.setOAuthConsumerSecret("H4KAPjY1N4qhIFJCpVftgIKVNVcz2bwOLX8HT8NcJAc");
    // Gen setting
    Configuration conf = cb.build();
    // Oauth認証オブジェクト作成
    _oauth = new OAuthAuthorization(conf);
    _oauth.setOAuthAccessToken(null);
    // アプリの認証オブジェクト作成
    try {
      _req = _oauth.getOAuthRequestToken("Callback://CallBackActivity");
    } catch (TwitterException e) {
      e.printStackTrace();
    }
    String _uri;
    _uri = _req.getAuthorizationURL();
    // Open Browser
    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(_uri)), 0);
  }
Esempio n. 10
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;
 }
Esempio n. 11
0
 /**
  * RequestTokenの取得
  *
  * @return RequestToken
  */
 public String getOAuthRequestURL() {
   return request != null ? request.getAuthorizationURL() : "nothing yet";
 }
Esempio n. 12
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();
    }
  }
Esempio n. 13
0
  /**
   * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
   *
   * @param args message
   */
  public static void main(String[] args) {
    File file = new File("src/twitter4j1.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;

    String oauth_consumerKey = null;
    String oauth_consumerSecret = null;
    try {
      if (file.exists()) {
        is = new FileInputStream(file);
        prop.load(is);
        oauth_consumerKey = prop.getProperty("oauth.consumerKey");
        oauth_consumerSecret = prop.getProperty("oauth.consumerSecret");
        System.out.println(oauth_consumerKey);
        System.out.println(oauth_consumerSecret);
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
      System.exit(-1);
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException ignore) {
        }
      }
      if (os != null) {
        try {
          os.close();
        } catch (IOException ignore) {
        }
      }
    }

    String oauth_requestToken = null;
    String oauth_requestTokenSecret = null;

    try {

      // OAuth有两种Token,分别是RequestToken和AccessTonke。
      // 通过OAuth Consumer的key和secret就可以获取RequestTokenKey和RequestTokenSecret:

      ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
      configurationBuilder.setOAuthConsumerKey(oauth_consumerKey);
      configurationBuilder.setOAuthConsumerSecret(oauth_consumerSecret);
      configurationBuilder.setHttpProxyHost("127.0.0.1");
      configurationBuilder.setHttpProxyPort(1080);
      Configuration configuration = configurationBuilder.build();
      Twitter twitter = new TwitterFactory(configuration).getInstance();

      //            Twitter twitter = new TwitterFactory().getInstance();
      //            twitter.setOAuthConsumer(oauth_consumerKey, oauth_consumerSecret);
      //            RequestToken requestToken = twitter.getOAuthRequestToken();
      //            RequestToken requestToken = twitter.getOAuthRequestToken();
      RequestToken requestToken = twitter.getOAuthRequestToken("http://hintdesk.com");
      System.out.println("Got request token.");
      System.out.println("Request token: " + requestToken.getToken());
      System.out.println("Request token secret: " + requestToken.getTokenSecret());
      oauth_requestToken = requestToken.getToken();
      oauth_requestTokenSecret = requestToken.getTokenSecret();

      //            //跳转到Twitter OAuth验证页面
      //            String authorizationURL = requestToken.getAuthorizationURL();
      //
      //
      // //通过requestTokenKey和requestTokenSecret获得accessToken,包含了accessTokenKey和accessTokenSecret
      //            AccessToken accessToken = twitter.getOAuthAccessToken(oauth_requestToken,
      // oauth_requestTokenSecret);
      //            //把accessToken给twitter,twitter这个实例就算登陆了,效果等同于twitter = new twitter( "name ",
      // "password ")
      //            twitter.setOAuthAccessToken(accessToken);

      // 有了ConsumerKey和ConsumerScret,还有accessToken和accessTokenSecret。
      // 下一次登陆twitter就可以直接登陆了
      /*
      twitter = new Twitter();
      twitter.setOAuthConsumer(ConsumerKey, ConsumerScret);
      AccessToken accessToken = new AccessToken(Utility.getCookie( "accessToken ", request), Utility.getCookie( "accessTokenSecret ", request));
      twitter.setOAuthAccessToken(accessToken);
      twitter.updateStatus( "OAuth登陆成功 ");
      */
      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());
        try {
          Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
        } catch (IOException ignore) {
        } catch (URISyntaxException e) {
          throw new AssertionError(e);
        }
        System.out.print(
            "Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
        String pin = br.readLine();
        try {
          if (pin.length() > 0) {
            accessToken = twitter.getOAuthAccessToken(requestToken, pin);
          } else {
            accessToken = twitter.getOAuthAccessToken(requestToken);
          }
        } catch (TwitterException te) {
          if (401 == te.getStatusCode()) {
            System.out.println("Unable to get the access token.");
          } else {
            te.printStackTrace();
          }
        }
      }
      System.out.println("Got access token.");
      System.out.println("Access token: " + accessToken.getToken());
      System.out.println("Access token secret: " + accessToken.getTokenSecret());

      try {
        prop.setProperty("oauth.accessToken", accessToken.getToken());
        prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
        os = new FileOutputStream(file);
        prop.store(os, "twitter4j1.properties");
        os.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
      } finally {
        if (os != null) {
          try {
            os.close();
          } catch (IOException ignore) {
          }
        }
      }
      System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
      System.exit(0);
    } catch (TwitterException te) {
      te.printStackTrace();
      System.out.println("Failed to get accessToken: " + te.getMessage());
      System.exit(-1);
    } catch (IOException ioe) {
      ioe.printStackTrace();
      System.out.println("Failed to read the system input.");
      System.exit(-1);
    }
  }