@Override
  public String input() throws Exception {

    if (!isEmpty(denied)) {
      // todo: inform user that authorization has been denied
      return SUCCESS;
    }

    TwitterFactory tf = new TwitterFactory(TwitterConfigFactory.getConfig());
    Twitter twitter = tf.getInstance();

    RequestToken requestToken = (RequestToken) session.get("requestToken");

    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier);

    try (GroupTwitterCredentialsDao groupTwitterCredentialsDao =
        new DbiFactory().getDbi().open(GroupTwitterCredentialsDao.class)) {
      groupTwitterCredentialsDao.createGroupTwitterCredentials(
          groupId,
          accessToken.getScreenName(),
          accessToken.getUserId(),
          accessToken.getToken(),
          accessToken.getTokenSecret());
    }

    // todo: inform user that authorization was successful
    return SUCCESS;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fun_app_with_twitter);

    mSharedPreferences = getSharedPreferences(Const.PREFERENCE_NAME, MODE_PRIVATE);
    getTweetButton = (Button) findViewById(R.id.getTweet);
    getTweetButton.setOnClickListener(this);
    buttonLogin = (Button) findViewById(R.id.twitterLogin);
    buttonLogin.setOnClickListener(this);
    keyword = (EditText) findViewById(R.id.keyword);

    if (!isConnected()) {
      buttonLogin.setText(R.string.label_connect);
    } else {
      buttonLogin.setText(R.string.label_disconnect);
    }

    /** Handle OAuth Callback */
    Uri uri = getIntent().getData();
    if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL)) {
      String verifier = uri.getQueryParameter(Const.IEXTRA_OAUTH_VERIFIER);
      try {
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        Editor e = mSharedPreferences.edit();
        e.putString(Const.PREF_KEY_TOKEN, accessToken.getToken());
        e.putString(Const.PREF_KEY_SECRET, accessToken.getTokenSecret());
        e.commit();
      } catch (Exception e) {
        // System.out.println(e.toString());
        Log.e(TAG, e.getMessage());
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      }
    }
  }
Exemplo n.º 3
0
 public void storeAccessToken(AccessToken accessToken, String username, String loginname) {
   editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
   editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
   editor.putString(TWEET_USER_NAME, username);
   editor.putString(TWEET_LOGIN_NAME, loginname);
   editor.commit();
 }
  /**
   * 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);
    }
  }
    protected void onPostExecute(AccessToken accessToken) {

      try {
        // Shared Preferences
        SharedPreferences.Editor e = sharedPrefs.edit();

        Log.v("logging_in", "this is what the token should be: " + accessToken.getToken());

        if (sharedPrefs.getInt("current_account", 1) == 1) {
          e.putString("authentication_token_1", accessToken.getToken());
          e.putString("authentication_token_secret_1", accessToken.getTokenSecret());
          e.putBoolean("is_logged_in_1", true);
        } else {
          e.putString("authentication_token_2", accessToken.getToken());
          e.putString("authentication_token_secret_2", accessToken.getTokenSecret());
          e.putBoolean("is_logged_in_2", true);
        }

        e.commit(); // save changes

        // Hide login_activity button
        btnLoginTwitter.setText(getResources().getString(R.string.initial_sync));
        btnLoginTwitter.setEnabled(true);
        title.setText(getResources().getString(R.string.second_welcome));
        summary.setText(getResources().getString(R.string.second_info));

        hideHideWebView();

      } catch (Exception e) {
        restartLogin();
      }
    }
Exemplo n.º 6
0
  private static void storeAccessToken(User user, AccessToken accessToken) {
    DBConnection dbc = new DBConnection();
    dbc.connect();
    java.sql.Statement s = null;

    try {
      s = dbc.connection.createStatement();
      String query =
          "insert into tokens values ("
              + user.getId()
              + ",'"
              + user.getScreenName()
              + "','"
              + accessToken.getToken()
              + "','"
              + accessToken.getTokenSecret()
              + "');";
      // System.out.println("Query:" + query);
      s.execute(query);
    } catch (SQLException e) {
      System.err.println("Failed to insert token:" + e.getMessage());
      // e.printStackTrace();
    } finally {
      try {
        s.close();
      } catch (SQLException e) {
        System.err.println("Couldn't close insert statement:" + e.getMessage());
        e.printStackTrace();
      }
      dbc.disconnect();
    }
  }
 private void saveAccessToken(AccessToken at) {
   String token = at.getToken();
   String secret = at.getTokenSecret();
   Editor editor = mPrefs.edit();
   editor.putString(Const.PREF_KEY_TOKEN, token);
   editor.putString(Const.PREF_KEY_SECRET, secret);
   editor.commit();
 }
Exemplo n.º 8
0
  @SuppressLint("NewApi")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* initializing twitter parameters from string.xml */
    initTwitterConfigs();

    /* Enabling strict mode */
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    /* Setting activity layout file */
    setContentView(R.layout.activity_main);

    loginLayout = (RelativeLayout) findViewById(R.id.login_layout);

    /* register button click listeners */
    findViewById(R.id.btn_login).setOnClickListener(this);

    /* Check if required twitter keys are set */
    if (TextUtils.isEmpty(consumerKey) || TextUtils.isEmpty(consumerSecret)) {
      Toast.makeText(this, "Twitter key and secret not configured", Toast.LENGTH_SHORT).show();
      return;
    }

    /* Initialize application preferences */
    mSharedPreferences = getSharedPreferences(PREF_NAME, 0);

    boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

    /*  if already logged in, then hide login layout and show share layout */
    if (isLoggedIn) {
      Intent intent = new Intent(MainActivity.this, MenuActivity.class);
      startActivity(intent);

    } else {
      loginLayout.setVisibility(View.VISIBLE);
      Uri uri = getIntent().getData();
      if (uri != null && uri.toString().startsWith(callbackUrl)) {
        String verifier = uri.getQueryParameter(oAuthVerifier);
        try {
          /* Getting oAuth authentication token */
          AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
          /* Getting user id form access token */
          long userID = accessToken.getUserId();
          final User user = twitter.showUser(userID);
          final String username = user.getName();
          /* save updated token */
          saveTwitterInfo(accessToken);
          //       loginLayout.setVisibility(View.GONE);

        } catch (Exception e) {
          Log.e("Failed  login Twitter!!", e.getMessage());
        }
      }
    }
  }
Exemplo n.º 9
0
  /** Private API */
  private static void storeAccessTokens(AccessToken token) {
    mAccessToken = token;

    SharedPreferences.Editor editor = getPreferences().edit();
    editor
        .putString("accessToken", token.getToken())
        .putString("accessTokenSecret", token.getTokenSecret());
    editor.apply();
  }
Exemplo n.º 10
0
  private static void getTwitterProfileInfo(AccessToken accessToken2) {
    try {
      String token = accessToken2.getToken();
      Log.i(TAG, "token is " + token);
      mUserInfo.setExtra(token);
      long userId = accessToken2.getUserId();
      mUserInfo.setTwitterId(String.valueOf(userId));
      userObj = twitter.showUser(userId);
      mUserInfo.setProfilePic(userObj.getBiggerProfileImageURLHttps());
      long cursor = -1;
      IDs freinds = twitter.getFriendsIDs(userObj.getId(), cursor);
      Log.d(TAG, "IDS:" + freinds.getIDs());
      if (freinds.getIDs() != null) {
        StringBuilder builder = new StringBuilder();
        builder.append("");
        do {
          for (long i : freinds.getIDs()) {

            builder.append(i + ",");
          }
        } while (freinds.hasNext());
        String freindIds = builder.toString();
        Log.d("MSG:", "FND id:" + freindIds);
        if (freindIds.equals("")) {
          mUserInfo.setFriendsIds(freindIds);
        } else {
          freindIds = freindIds.substring(0, freindIds.length() - 1);
          mUserInfo.setFriendsIds(freindIds);
        }
      }
      if (userObj.getName() != null) {
        String name[] = userObj.getName().split(" ");
        /*
         * mUserInfo.setFirstName(name[0]); if (name[1] != null) {
         * mUserInfo.setLastName(name[1]);
         *
         * }
         */
        if (name.length >= 2) {
          mUserInfo.setFirstName(name[0]);
          mUserInfo.setLastName(name[1]);
        } else if (name.length >= 1) {
          mUserInfo.setFirstName(name[0]);
        }
      }

      mUserInfo.setExpiresIn(String.valueOf(System.currentTimeMillis() + 600000));

    } catch (TwitterException e) {
      Log.e(TAG, "Twitter login error");
    }

    twitterHandler.isExit(String.valueOf(accessToken2.getUserId()));
  }
Exemplo n.º 11
0
 private static void storeAccessToken(long useId, AccessToken accessToken) {
   try (BufferedWriter writer =
       Files.newBufferedWriter(Paths.get("token.txt"), Charset.forName("UTF-8"))) {
     writer.append(accessToken.getToken());
     writer.append("\n");
     writer.append(accessToken.getTokenSecret());
     writer.append("\n");
     writer.append(accessToken.getUserId() + "");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 12
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 oAuthAccessToken = twitter.getOAuthAccessToken(requestToken, verifier);
      request.getSession().removeAttribute("requestToken");

      String cookie = UUID.randomUUID().toString();
      Cookie c = new Cookie(SigninServlet.COOKIE_NAME, cookie);
      c.setMaxAge(365 * 24 * 60 * 60); // one year
      response.addCookie(c);

      UserTransaction ut =
          (UserTransaction) new InitialContext().lookup("java:jboss/UserTransaction");
      ut.begin();

      User user = entityManager.find(User.class, twitter.getScreenName());
      if (user == null) {
        user = new User();
        user.setScreenName(twitter.getScreenName());
        // user.setAccessToken(oAuthAccessToken.getToken());
        // user.setAccessTokenSecret(oAuthAccessToken.getTokenSecret());
        entityManager.persist(user);

        twitterCredentialManager.setAccessToken(
            user, oAuthAccessToken.getToken(), oAuthAccessToken.getTokenSecret());
      } else {
        user.getFeeds().size();
        user.getCircles().size();
        user.getTweeters().size();
        user.getSentStories().size();

        if (twitterCredentialManager.getAccessToken(user) == null) {
          twitterCredentialManager.setAccessToken(
              user, oAuthAccessToken.getToken(), oAuthAccessToken.getTokenSecret());
        }
      }

      Login login = new Login();
      login.setCookie(cookie);
      login.setUser(user);
      entityManager.persist(login);

      request.getSession().setAttribute("user", user);
      ut.commit();
    } catch (Exception e) {
      throw new ServletException(e);
    }
    response.sendRedirect(request.getContextPath() + "/");
  }
Exemplo n.º 13
0
 @Override
 public void accessToken(Uri uri) {
   if (requestToken != null) {
     String verifier = uri.getQueryParameter(INTENT_OAUTH_VERIFIER);
     try {
       AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
       PersistUtils.getInstance(context)
           .persistAccessToken(accessToken.getToken(), accessToken.getTokenSecret());
     } catch (TwitterException e) {
       e.printStackTrace();
     }
   }
 }
  /**
   * 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() + "].");
  }
 /** Handle OAuth Callback */
 public void handleOauthCallback(Uri uri) {
   if (uri != null && uri.toString().startsWith(TwitterConsts.CALLBACK_URL)) {
     String verifier = uri.getQueryParameter(TwitterConsts.IEXTRA_OAUTH_VERIFIER);
     try {
       AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
       Editor ed = sharedPreferences.edit();
       ed.putString(TwitterConsts.PREF_KEY_TOKEN, accessToken.getToken());
       ed.putString(TwitterConsts.PREF_KEY_SECRET, accessToken.getTokenSecret());
       ed.commit();
     } catch (Exception e) {
       Log.e("TwitterHelper", e.getMessage());
     }
   }
 }
 /*
  *	Called after authenticating with Acess Token from the Twitter
  */
 protected void onNewIntent(Intent intent) {
   Uri uri = intent.getData();
   if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
     final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
     try {
       AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
       AUTH_TOKEN = accessToken.getToken();
       AUTH_TOKEN_SECRET = accessToken.getTokenSecret();
     } catch (Exception ex) {
       Log.d("SN", ex.getMessage());
     }
     super.onNewIntent(intent);
   }
 }
Exemplo n.º 17
0
  public void storeData(Intent intent) {
    AccessToken accessToken = null;
    try {
      String oauthVerifier = intent.getExtras().getString(Const.IEXTRA_OAUTH_VERIFIER);
      accessToken = mTwitter.getOAuthAccessToken(mRequestToken, oauthVerifier);
      SharedPreferences pref = context.getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = pref.edit();
      editor.putString(Const.PREF_KEY_ACCESS_TOKEN, accessToken.getToken());
      editor.putString(Const.PREF_KEY_ACCESS_TOKEN_SECRET, accessToken.getTokenSecret());
      editor.commit();

    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
 public static TwitterStream getTwitterStream() {
   AccessToken token = AccessTokenManager.getAccessToken();
   if (token == null) {
     return null;
   }
   ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
   twitter4j.conf.Configuration conf =
       configurationBuilder
           .setOAuthConsumerKey(getConsumerKey())
           .setOAuthConsumerSecret(getConsumerSecret())
           .setOAuthAccessToken(token.getToken())
           .setOAuthAccessTokenSecret(token.getTokenSecret())
           .build();
   return new TwitterStreamFactory(conf).getInstance();
 }
Exemplo n.º 19
0
    private AccessToken getAccessToken() {
      try {
        // Get an access token. This triggers network access.
        AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);

        if (isDebugEnabled()) {
          Log.d(TAG, "Got an access token for " + token.getScreenName());
        }

        return token;
      } catch (TwitterException e) {
        // Failed to get an access token.
        e.printStackTrace();
        Log.e(TAG, "Failed to get an access token.", e);

        // No access token.
        return null;
      }
    }
Exemplo n.º 20
0
    @Override
    protected Bundle doInBackground(Bundle... params) {
      String verifier = params[0].getString(PARAM_VERIFIER);

      Bundle result = new Bundle();

      try {
        twitter4j.auth.AccessToken accessToken =
            mTwitter.getOAuthAccessToken(mRequestToken, verifier);

        result.putString(RESULT_TOKEN, accessToken.getToken());
        result.putString(RESULT_SECRET, accessToken.getTokenSecret());
        result.putLong(RESULT_USER_ID, accessToken.getUserId());
      } catch (Exception e) {
        result.putString(RESULT_ERROR, e.getMessage() == null ? "canceled" : e.getMessage());
      }

      return result;
    }
  public boolean tryConnect() {

    /** Handle OAuth Callback */
    Uri uri = oIntent.getData();
    if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL)) {
      String verifier = uri.getQueryParameter(Const.IEXTRA_OAUTH_VERIFIER);
      try {
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        Editor e = mSharedPreferences.edit();
        e.putString(Const.PREF_KEY_TOKEN, accessToken.getToken());
        e.putString(Const.PREF_KEY_SECRET, accessToken.getTokenSecret());
        e.commit();
        Log.v(
            this.getClass().getCanonicalName(),
            "tryConnect-> Twitter KEY:"
                + accessToken.getToken()
                + " SEGRET"
                + accessToken.getTokenSecret());
        return true;
      } catch (Exception e) {
        Log.e(this.getClass().getCanonicalName(), e.getMessage());
        return false;
      }
    } else {
      Log.v(this.getClass().getCanonicalName(), "tryConnect-> Twitter KEY no");
      SharedPreferences mSharedPreferences =
          oContext.getSharedPreferences(Const.PREFERENCE_NAME, Context.MODE_PRIVATE);
      String oauthAccessToken = mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "");
      String oAuthAccessTokenSecret = mSharedPreferences.getString(Const.PREF_KEY_SECRET, "");

      Log.v(
          this.getClass().getCanonicalName(),
          "oauthAccessToken: "
              + oauthAccessToken
              + " oAuthAccessTokenSecret:"
              + oAuthAccessTokenSecret);
      if (mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "").length() == 0) {
        askOAuth();
      }
      // checkConnected();
      return false;
    }
  }
Exemplo n.º 22
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.callback);

    AccessToken token = null;

    // Twitterの認証画面から発行されるIntentを取得
    Uri uri = getIntent().getData();

    if (uri != null && uri.toString().startsWith("Callback://CallBackActivity")) {
      // oauth_verifierを取得する
      String verifier = uri.getQueryParameter("oauth_verifier");
      try {
        // AccessTokenオブジェクトを取得
        token = OauthSample3._oauth.getOAuthAccessToken(OauthSample3._req, verifier);
      } catch (TwitterException e) {
        e.printStackTrace();
      }
    }

    // SharedPreferencesにtokenとtoken seacretを保存
    SharedPreferences spObj = getSharedPreferences("token", MODE_PRIVATE);
    SharedPreferences.Editor editor = spObj.edit();
    editor.putString("token", token.getToken());
    editor.putString("token_seacret", token.getTokenSecret());
    editor.commit();

    // ツイートボタン押下時処理
    Button btn = (Button) findViewById(R.id.tweetButton);
    btn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            EditText ed = (EditText) findViewById(R.id.tweetText);
            if (!(ed.getText().toString().equals(""))) {
              tweet(ed.getText().toString());
            }
          }
        });
  }
  /**
   * Grava a autorização para o programa acessar a conta do twitter gerando um token, tokenSecret.
   */
  @RequestMapping(value = "/{id}/autorizacaoTwitter")
  public String autorizacaoTwitter(
      @PathVariable("id") Integer id, @Valid Pin pin, ModelMap modelMap) {

    AutorizacaoTwitterRequest autorizacaoTwitterRequest =
        autorizacaoTwitterRequestService.find(AutorizacaoTwitterRequest.class, id);
    Usuario usuarioAutorizado =
        usuarioService.getUsuarioByLogin(
            SecurityContextHolder.getContext().getAuthentication().getName());
    Twitter twitter = autorizacaoTwitterRequest.getTwitter();
    RequestToken requestToken = autorizacaoTwitterRequest.getRequestToken();
    AccessToken accessToken = null;

    try {
      if (pin.getPin().length() > 0) {
        System.out.println(pin.getPin());
        accessToken = twitter.getOAuthAccessToken(requestToken, pin.getPin());
      } else {
        accessToken = twitter.getOAuthAccessToken();
      }
    } catch (TwitterException te) {
      if (401 == te.getStatusCode()) {
        System.out.println("Não foi possível obter o token de acesso." + te.getMessage());
      } else {
        te.printStackTrace();
      }
    }

    AutorizacaoTwitter autorizacaoTwitter = new AutorizacaoTwitter();
    autorizacaoTwitter.setId((int) accessToken.getUserId());
    autorizacaoTwitter.setToken(accessToken.getToken());
    autorizacaoTwitter.setTokenSecret(accessToken.getTokenSecret());
    autorizacaoTwitter.setUsuario(usuarioAutorizado);
    autorizacaoTwitterService.save(autorizacaoTwitter);

    usuarioAutorizado.setAutorizacaoTwitter(autorizacaoTwitter);
    usuarioService.update(usuarioAutorizado);

    autorizacaoTwitterRequestService.delete(autorizacaoTwitterRequest);
    modelMap.addAttribute("usuario", usuarioAutorizado);
    return "redirect:/usuario/listar";
  }
Exemplo n.º 24
0
  /**
   * Saving user information, after user is authenticated for the first time. You don't need to show
   * user to login, until user has a valid access toen
   */
  private void saveTwitterInfo(AccessToken accessToken) {

    long userID = accessToken.getUserId();

    User user;
    try {
      user = twitter.showUser(userID);

      String username = user.getName();

      /* Storing oAuth tokens to shared preferences */
      Editor e = mSharedPreferences.edit();
      e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
      e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
      e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
      e.putString(PREF_USER_NAME, username);
      e.commit();

    } catch (TwitterException e1) {
      e1.printStackTrace();
    }
  }
Exemplo n.º 25
0
    @Override
    protected User doInBackground(String... params) {

      String verifier = params[0];

      // Get the access token
      AccessToken accessToken = null;
      User user = null;
      try {
        accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

        // Shared Preferences
        SharedPreferences.Editor e = mSharedPreferences.edit();

        // After getting access token, access token secret
        // store them in application preferences
        e.putString(PREF_KEY_ACCESS_TOKEN, accessToken.getToken());
        e.putString(PREF_KEY_ACCESS_SECRET, accessToken.getTokenSecret());
        // Store login status - true
        e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);

        Log.d(TAG, "Twitter OAuth Token: " + accessToken.getToken());

        // Getting user details from twitter
        // For now i am getting his name only
        long userID = accessToken.getUserId();
        user = twitter.showUser(userID);

        e.putString(PREF_KEY_USER_NAME, user.getName());
        e.putString(PREF_KEY_USER_PROFILE, user.getProfileBackgroundImageURL());
        e.commit(); // save changes

      } catch (TwitterException e) {
        Log.e(TAG, "Twitter Login Error: " + e.getMessage());
        e.printStackTrace();
      }

      return user;
    }
Exemplo n.º 26
0
        /**
         * Called when OAuth authentication has been finalized and an Access Token and Access Token
         * Secret have been provided
         *
         * @param accessToken The access token to use to do REST calls
         */
        @Override
        public void gotOAuthAccessToken(AccessToken accessToken) {
          SoomlaUtils.LogDebug(TAG, "login/onComplete");

          twitter.setOAuthAccessToken(accessToken);

          // Keep in storage for logging in without web-authentication
          KeyValueStorage.setValue(
              getTwitterStorageKey(TWITTER_OAUTH_TOKEN), accessToken.getToken());
          KeyValueStorage.setValue(
              getTwitterStorageKey(TWITTER_OAUTH_SECRET), accessToken.getTokenSecret());

          // Keep screen name since Twitter4J does not have it when
          // logging in using authenticated tokens
          KeyValueStorage.setValue(
              getTwitterStorageKey(TWITTER_SCREEN_NAME), accessToken.getScreenName());

          twitterScreenName = accessToken.getScreenName();

          RefLoginListener.success(RefProvider);

          clearListener(ACTION_LOGIN);
        }
  /**
   * ユーザー情報取得用トークン取得メソッド
   *
   * @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;
  }
Exemplo n.º 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();
    }
  }
Exemplo n.º 29
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    cd = new ConnectionDetector(getApplicationContext());
    if (!cd.isConnectingToInternet()) {
      // Internet Connection is not present
      alert.showAlertDialog(
          MainActivity.this,
          "Internet Connection Error",
          "Please connect to working Internet connection and re launch application",
          false);
      // stop executing code by return
      // finish();
    } else {

      // setContentView(R.layout.login);
      applFirstRunPref = getApplicationContext().getSharedPreferences("applFirstRunPref", 0);
      boolean firstTime = applFirstRunPref.getBoolean("firstTime", true);
      if (firstTime) {
        SharedPreferences.Editor editor = applFirstRunPref.edit();
        editor.putBoolean("firstTime", false);
        editor.commit();
        populateTableTeam();
        System.out.println("================================ first time load appl");
      }

      mPrefs = getPreferences(MODE_PRIVATE);
      // Session class instance
      session = new SessionManager(getApplicationContext());

      // initialise facebook
      facebook = new Facebook(APP_ID);
      mAsyncRunner = new AsyncFacebookRunner(facebook);

      boolean isLoggedIn = session.isLoggedIn();
      // if isloggged in go to list page directly
      if (isLoggedIn) {
        Intent i = new Intent(getApplicationContext(), MainContainerActivity.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // Staring Login Activity
        getApplicationContext().startActivity(i);
        finish();
      } else {
        // if not already logged in delete facebook token if in session
        Editor editorFbk = mPrefs.edit();
        editorFbk.remove("access_token");
        editorFbk.remove("access_expires");
        editorFbk.commit();

        // -------------- FACEBOOK ----------------
        btnLoginFbk = (Button) findViewById(R.id.btnFbk);
        btnLoginFbk.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                try {
                  if (connectionUtility.hasWifi(getBaseContext())) {
                    loginToFacebook();
                  } else {
                    connectionUtility.showToast(MainActivity.this);
                    connectionUtility.setUtilityListener(
                        new ConnectionUtilityListener() {
                          @Override
                          public void onInternetEnabled(boolean result) {
                            loginToFacebook();
                          }

                          @Override
                          public void exitApplication(boolean result) {
                            onDestroy();
                            finish();
                          }
                        });
                  }
                } finally {

                }
              }
            });

        // ------------- TWITTER -------------------
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        cd = new ConnectionDetector(getApplicationContext());
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
          // Internet Connection is not present
          alert.showAlertDialog(
              MainActivity.this,
              "Internet Connection Error",
              "Please connect to working Internet connection",
              false);
          // stop executing code by return
          return;
        }
        // Check if twitter keys are set
        if (TWITTER_CONSUMER_KEY.trim().length() == 0
            || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
          // Internet Connection is not present
          alert.showAlertDialog(
              MainActivity.this,
              "Twitter oAuth tokens",
              "Please set your twitter oauth tokens first!",
              false);
          // stop executing code by return
          return;
        }
        // All UI elements
        btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
        // Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

        btnLoginTwitter.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View arg0) {
                try {
                  if (connectionUtility.hasWifi(getBaseContext())) {
                    // Call login twitter function
                    loginToTwitter();
                  } else {
                    connectionUtility.showToast(MainActivity.this);
                    connectionUtility.setUtilityListener(
                        new ConnectionUtilityListener() {
                          @Override
                          public void onInternetEnabled(boolean result) {
                            // Call login twitter function
                            loginToTwitter();
                          }

                          @Override
                          public void exitApplication(boolean result) {
                            onDestroy();
                            finish();
                          }
                        });
                  }
                } finally {

                }
              }
            });
        if (!isTwitterLoggedInAlready()) {
          Uri uri = getIntent().getData();
          if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
            try {
              // Get the access token
              AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
              // Getting user details from twitter
              long userID = accessToken.getUserId();
              userDto = new UserDTO(String.valueOf(userID), "", "", "", "", 0, "");
              completeRegistration(userDto, accessToken);
            } catch (Exception e) {
              // Check log for login errors
              Log.e("Twitter Login Error", "> " + e.getMessage());
            }
          }
        }
        if (isTwitterLoggedInAlready()) {
          Intent gameList = new Intent(getApplicationContext(), MainContainerActivity.class);
          // Close all views before launching matchList
          gameList.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(gameList);
        }
        // -------------------- NORMAL -------------------------------
        txtUserName = (EditText) findViewById(R.id.txt_username);
        txtPassword = (EditText) findViewById(R.id.txt_pwd);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (TextView) findViewById(R.id.btnRegister);
        btnLinkToRegister.setMovementMethod(LinkMovementMethod.getInstance());
        rememberMe = (CheckBox) findViewById(R.id.chkRemeber);
        btnLostPwd = (TextView) findViewById(R.id.btnLostPwd);
        btnLostPwd.setMovementMethod(LinkMovementMethod.getInstance());

        // Login button Click Event (normal)
        btnLogin.setOnClickListener(
            new View.OnClickListener() {
              public void onClick(View view) {

                if ((txtUserName.length() == 0 || txtUserName.equals("") || txtUserName == null)
                    || (txtPassword.length() == 0
                        || txtPassword.equals("")
                        || txtPassword == null)) {
                  Toast toast =
                      Toast.makeText(
                          MainActivity.this, "Please fill in all the fields", Toast.LENGTH_LONG);
                  toast.setGravity(Gravity.CENTER, 0, 0);
                  toast.show();
                } else {
                  final String userName = txtUserName.getText().toString();
                  final String password = txtPassword.getText().toString();
                  final UserDTO user = new UserDTO(userName, "", "", "", password, 0, "");

                  try {
                    if (connectionUtility.hasWifi(getBaseContext())) {
                      progressDialog = new ProgressDialog(MainActivity.this);
                      progressDialog.setMessage("Loading ...");

                      login(user);
                    } else {
                      connectionUtility.showToast(MainActivity.this);
                      connectionUtility.setUtilityListener(
                          new ConnectionUtilityListener() {
                            @Override
                            public void onInternetEnabled(boolean result) {
                              progressDialog = new ProgressDialog(MainActivity.this);
                              progressDialog.setMessage("Loading ...");
                              login(user);
                            }

                            @Override
                            public void exitApplication(boolean result) {
                              onDestroy();
                              finish();
                            }
                          });
                    }
                  } finally {

                  }
                }
              }
            });
        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(
            new View.OnClickListener() {
              public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(i);
                finish();
              }
            });

        // Link to Register Screen
        btnLostPwd.setOnClickListener(
            new View.OnClickListener() {
              public void onClick(View view) {
                // Create custom dialog object
                dialog = new Dialog(MainActivity.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setCanceledOnTouchOutside(false);
                // Include dialog.xml file
                dialog.setContentView(R.layout.lost_password);

                Button cancle_btn = (Button) dialog.findViewById(R.id.btbPwdCancel);
                cancle_btn.setOnClickListener(
                    new View.OnClickListener() {

                      @Override
                      public void onClick(View v) {
                        // Perform button logic
                        dialog.dismiss();
                      }
                    });

                Button send_pwd_btn = (Button) dialog.findViewById(R.id.btnPwdSave);
                final EditText editTextLostPwd =
                    (EditText) dialog.findViewById(R.id.editTextLostPwd);
                send_pwd_btn.setOnClickListener(
                    new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                        String email = editTextLostPwd.getText().toString();

                        if ((email.length() == 0 || email.equals("") || email == null)) {
                          Toast toast =
                              Toast.makeText(
                                  MainActivity.this, "Enter your email address", Toast.LENGTH_LONG);
                          toast.setGravity(Gravity.CENTER, 0, 0);
                          toast.show();
                        } else {
                          sendEmailLostPwd(email);
                        }
                      }
                    });
                dialog.show();
              }
            });
      }
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate!");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    if (savedInstanceState == null) {
      getSupportFragmentManager()
          .beginTransaction()
          .add(R.id.login_activitycontainer, new LoginActivityFragment())
          .commit();
    }

    // GOOGLE
    mGoogleApiClient =
        new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN)
            .build();

    // FACEBOOK
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    // TWITTER
    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
      // Internet Connection is not present
      alert.showAlertDialog(
          LoginActivity.this,
          "Twitter oAuth tokens",
          "Please set your twitter oauth tokens first!",
          false);
      // stop executing code by return
      return;
    }

    // TODO: please us threads correctly!
    if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

    // Check if Internet present
    cd = new ConnectionDetector(getApplicationContext());
    if (!cd.isConnectingToInternet()) {
      // Internet Connection is not present
      alert.showAlertDialog(
          LoginActivity.this,
          "Internet Connection Error",
          "Please connect to working Internet connection",
          false);
      // stop executing code by return
      return;
    }

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("AndroidSocialTemplate", 0);

    /**
     * This if conditions is tested once is redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     */
    if (!isTwitterLoggedInAlready()) {
      Uri uri = getIntent().getData();
      if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
        // oAuth verifier
        String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

        try {
          // Get the access token
          AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

          // Shared Preferences
          Editor e = mSharedPreferences.edit();

          // After getting access token, access token secret
          // store them in application preferences
          e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
          e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
          // Store login status - true
          e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
          e.commit(); // save changes

          Log.d("Twitter OAuth Token", "> " + accessToken.getToken());

          Intent i = new Intent(LoginActivity.this, MainActivity.class);
          startActivityForResult(i, REQUEST_CODE_TWITTER_LOGIN);
        } catch (Exception e) {
          // Check log for login errors
          Log.e("Twitter Login Error", "> " + e.getMessage());
        }
      }
    }
  }