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 "";
  }
  public RequestToken getRequestToken(String type) {
    if (requestToken == null) {
      Log.d("===", "requestToken = NULL ");
      try {
        if (type.equals("PIC")) {
          Log.d("===", "PIC");
          requestToken =
              twitterFactory
                  .getInstance()
                  .getOAuthRequestToken(ConstantValues.TWITTER_CALLBACK_URL_PIC);
          Log.d("===", "requestToken.getToken() = " + requestToken.getToken());
          Log.d("===", "requestToken.getTokenSecret: " + requestToken.getTokenSecret());
        } else {
          requestToken =
              twitterFactory
                  .getInstance()
                  .getOAuthRequestToken(ConstantValues.TWITTER_CALLBACK_URL_VIDEO);
        }

      } catch (TwitterException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
    return requestToken;
  }
  private void askOAuth() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(Const.CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(Const.CONSUMER_SECRET);
    Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

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

      // Intent dialogIntent = new Intent(Intent.ACTION_VIEW,
      // Uri.parse(requestToken.getAuthenticationURL()));
      // oActivity.startActivity(dialogIntent);
      // oActivity.startActivityForResult(dialogIntent,0);
      Intent intent = ActivityHelper.createActivityIntent(oActivity, TwitterAuthActivity.class);
      intent.putExtra("auth_twitter_url", requestToken.getAuthenticationURL());
      // oActivity.startActivity(intent);
      oActivity.startActivityForResult(intent, 0);
      Log.v(
          this.getClass().getCanonicalName(),
          "askOAuth-> After:" + requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
示例#4
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);
    }
  }
示例#6
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())));
 }
 @Override
 public String getAuthenticationUrl() {
   if (requestToken != null) {
     return requestToken.getAuthenticationURL();
   }
   return null;
 }
  private void loginToTwitter() {
    boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

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

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

      try {
        requestToken = twitter.getOAuthRequestToken(callbackUrl);

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

      } catch (TwitterException e) {
        e.printStackTrace();
      }
    } else {
      Intent intent = new Intent(MainActivity.this, MenuActivity.class);
      startActivity(intent);
    }
  }
 @Override
 public void handleMessage(Message msg) {
   int id = msg.what;
   switch (id) {
     case 0:
       showLoginDialog(requestToken.getAuthenticationURL());
       break;
   }
 }
  /**
   * 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;
  }
  private void loginNewUser() {
    try {
      Log.i(this.getClass().getCanonicalName(), "Request App Authentication");
      mReqToken = oTwitter.getOAuthRequestToken(Const.CALLBACK_URL);

      Log.i(this.getClass().getCanonicalName(), "Starting Webview to login to twitter");

      oWeb.loadUrl(mReqToken.getAuthenticationURL());
      oWeb.setWebViewClient(
          new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
              // do your handling codes here, which url is the requested url
              // probably you need to open that url rather than redirect:
              view.loadUrl(url);
              Log.i(this.getClass().getCanonicalName(), "Webview url: " + url);
              Uri uri = Uri.parse(url);
              if (uri != null
                  && uri.toString()
                      .startsWith(Const.CALLBACK_URL)) { // If the user has just logged in
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");

                authoriseNewUser(oauthVerifier);

                try {
                  ActivityHelper.startOriginalActivityAndFinish(TwitterAuthActivity.this);
                } catch (NullPointerException e) {
                  // ActivityHelper.startOriginalActivityAndFinish(getParent());
                  Intent intentMain =
                      ActivityHelper.createActivityIntent(
                          TwitterAuthActivity.this, MainTrainerActivity.class);
                  // startActivity(intent);
                  ActivityHelper.startNewActivityAndFinish(TwitterAuthActivity.this, intentMain);
                  // Log.e(this.getClass().getCanonicalName(),"Error back");
                }
              }
              return false; // then it is not handled by default action
            }
          });

    } catch (TwitterException e) {
      try {
        Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_LONG).show();
        ActivityHelper.startOriginalActivityAndFinish(this);
      } catch (NullPointerException e1) {
        // ActivityHelper.startOriginalActivityAndFinish(getParent());
        Intent intentMain = ActivityHelper.createActivityIntent(this, MainTrainerActivity.class);
        // startActivity(intent);
        ActivityHelper.startNewActivityAndFinish(this, intentMain);
        // Log.e(this.getClass().getCanonicalName(),"Error back");
      } catch (RuntimeException e2) {
        Log.e(this.getClass().getCanonicalName(), "Runtime error twitter");
      }
    }
  }
  @Override
  public Response performLogin(AuthenticationRequest request) {
    try {
      Twitter twitter = new TwitterFactory().getInstance();
      twitter.setOAuthConsumer(getConfig().getClientId(), getConfig().getClientSecret());

      URI uri = new URI(request.getRedirectUri() + "?state=" + request.getState());

      RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString());
      ClientSessionModel clientSession = request.getClientSession();

      clientSession.setNote("twitter_token", requestToken.getToken());
      clientSession.setNote("twitter_tokenSecret", requestToken.getTokenSecret());

      URI authenticationUrl = URI.create(requestToken.getAuthenticationURL());

      return Response.temporaryRedirect(authenticationUrl).build();
    } catch (Exception e) {
      throw new IdentityBrokerException("Could send authentication request to twitter.", e);
    }
  }
示例#14
0
        /**
         * Called when the request token has arrived from Twitter
         *
         * @param requestToken The request token to use to complete OAuth process
         */
        @Override
        public void gotOAuthRequestToken(RequestToken requestToken) {
          mainRequestToken = requestToken;

          Intent intent = new Intent(WeakRefParentActivity.get(), SoomlaTwitterActivity.class);

          intent.putExtra("url", mainRequestToken.getAuthenticationURL());
          WeakRefParentActivity.get().startActivity(intent);

          // Web browser version bad idea (take out of program)
          // startActivity(new Intent(Intent.ACTION_VIEW,
          // Uri.parse(mainRequestToken.getAuthenticationURL())));
        }
示例#15
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;
 }
  public void askOAuth(Context context) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(TwitterPrivateKeyAndSecret.CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(TwitterPrivateKeyAndSecret.CONSUMER_SECRET);
    Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

    try {
      requestToken = twitter.getOAuthRequestToken(TwitterConsts.CALLBACK_URL);
      context.startActivity(
          new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
示例#17
0
  /** Function to login twitter */
  private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
      builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
      Configuration configuration = builder.build();

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

      try {
        requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
        this.startActivity(
            new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));

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

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

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

      // Check for blank text
      if (status.trim().length() > 0) {
        // update status
        new updateTwitterStatus().execute(status);
      } else {
        // EditText is empty
        Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT)
            .show();
      }
    }
  }
  private void askOAuth() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(Const.CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(Const.CONSUMER_SECRET);
    Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

    try {
      requestToken = twitter.getOAuthRequestToken(Const.CALLBACK_URL);
      // System.out.println(requestToken.toString());
      Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
      this.startActivity(
          new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
 /**
  * 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();
   }
 }
示例#20
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;
  }
示例#22
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);
    }
  /** Function to login twitter */
  private void loginToTwitter() {
    Log.d(TAG, "loginToTwitter!");
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
      Log.d(TAG, "no already logged!");
      // Check is we already have tokens
      boolean already_have_tokens = already_have_twitter_tokens();
      if (already_have_tokens == true) {
        Log.d(TAG, "Already have twitter tokens -> Log in!");
        Intent i = new Intent(LoginActivity.this, MainActivity.class);
        startActivityForResult(i, REQUEST_CODE_TWITTER_LOGIN);
      } else {
        Log.d(TAG, "Starting twitter external auth!");

        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

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

        try {
          requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
          this.startActivity(
              new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
          e.printStackTrace();
        }
      }
    } else {
      // user already logged into twitter
      Log.d(TAG, "Already Logged into twitter");

      Intent i = new Intent(LoginActivity.this, MainActivity.class);
      startActivityForResult(i, REQUEST_CODE_TWITTER_LOGIN);
    }
  }
示例#24
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);
  }
示例#25
0
 /** Function to login twitter */
 private void loginToTwitter() {
   // Check if already logged in
   if (!isTwitterLoggedInAlready()) {
     ConfigurationBuilder builder = new ConfigurationBuilder();
     builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
     builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
     Configuration configuration = builder.build();
     TwitterFactory factory = new TwitterFactory(configuration);
     twitter = factory.getInstance();
     try {
       requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
       this.startActivity(
           new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
     } catch (TwitterException e) {
       e.printStackTrace();
     }
   } else {
     // user already logged into twitter
     Toast toast =
         Toast.makeText(MainActivity.this, "Already Logged into twitter", Toast.LENGTH_LONG);
     toast.setGravity(Gravity.CENTER, 0, 0);
     toast.show();
   }
 }
 public String getAuthenticationURL() {
   return requestToken.getAuthenticationURL();
 }
  @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()));
    }
  }
示例#28
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();
    }
  }
示例#29
0
 public String getAuthenticationUrl() throws TwitterException {
   RequestToken token = getRequestToken();
   return token.getAuthenticationURL();
 }
示例#30
0
 /**
  * RequestTokenの取得
  *
  * @return RequestToken
  */
 public String getOAuthRequestURL() {
   return request != null ? request.getAuthorizationURL() : "nothing yet";
 }