Example usage for twitter4j.auth RequestToken getAuthorizationURL

List of usage examples for twitter4j.auth RequestToken getAuthorizationURL

Introduction

In this page you can find the example usage for twitter4j.auth RequestToken getAuthorizationURL.

Prototype

public String getAuthorizationURL() 

Source Link

Usage

From source file:net.awairo.favdler.oauth.TwitterOAuth.java

License:MIT License

private void openTwitterOAuth(RequestToken rToken) {
    Desktop.openURI(rToken.getAuthorizationURL());
}

From source file:net.catchpole.pimpmylight.twitter.TwitterClient.java

License:Apache License

private void accessTokens(String consumerKey, String secretKey) throws Exception {
    twitter.setOAuthConsumer(consumerKey, secretKey);

    RequestToken requestToken = twitter.getOAuthRequestToken();
    System.out.println("Open the following URL...");
    System.out.println(requestToken.getAuthorizationURL());

    AccessToken accessToken = null;/*from   w ww. j  av  a  2s .  c  o  m*/
    while (null == accessToken) {
        String pin = JOptionPane.showInputDialog("PIN?");
        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();
            }
        }
    }
    System.out.println("token:       " + accessToken.getToken());
    System.out.println("secretToken: " + accessToken.getTokenSecret());
    System.exit(0);
}

From source file:onl.area51.a51li.twitter.TwitterAuth.java

License:Apache License

public static void main(String args[]) throws Exception {
    final String consumerKey = args[0];
    final String consumerSecret = args[1];

    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*  w w w.j a v a2s .c  o m*/
    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(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:org.fenixedu.bennu.social.domain.api.TwitterAPI.java

License:Open Source License

@Override
public String getAuthenticationUrlForUser(User user) {

    try {//from  www  .j  a  v a 2  s. c o  m
        TwitterFactory tf = new TwitterFactory();
        Twitter twitter = tf.getInstance();
        twitter.setOAuthConsumer(getClientId(), getClientSecret());

        RequestToken oauthRequestToken = twitter.getOAuthRequestToken(getCallbackURL());

        String oauthToken = oauthRequestToken.getToken();
        String oauthTokenSecret = oauthRequestToken.getTokenSecret();
        String authorizationURL = oauthRequestToken.getAuthorizationURL();

        LOGGER.info("Received OauthToken. Token: " + oauthToken + ", TokenSecret: " + oauthTokenSecret
                + ", AuthenticationURL: " + authorizationURL);

        TwitterUser twitterUser = new TwitterService().getAuthenticatedUser(user);
        twitterUser.setOauthToken(oauthToken);
        twitterUser.setOauthTokenSecret(oauthTokenSecret);

        return authorizationURL;

    } catch (TwitterException e) {
        LOGGER.error("Received TwitterException:" + e.getErrorMessage());
        e.printStackTrace();
        return "";
    }
}

From source file:org.getlantern.firetweet.util.OAuthPasswordAuthenticator.java

License:Open Source License

public AccessToken getOAuthAccessToken(final String username, final String password)
        throws AuthenticationException {
    final RequestToken requestToken;
    try {//from  ww w . j a  v  a2  s  . c o m
        requestToken = twitter.getOAuthRequestToken(OAUTH_CALLBACK_OOB);
    } catch (final TwitterException e) {
        if (e.isCausedByNetworkIssue())
            throw new AuthenticationException(e);
        throw new AuthenticityTokenException();
    }
    try {
        final String oauthToken = requestToken.getToken();
        final String authorizationUrl = requestToken.getAuthorizationURL();
        final HashMap<String, String> inputMap = new HashMap<>();
        final HttpResponse authorizePage = client.get(authorizationUrl, authorizationUrl, null, null, null);
        final List<String> cookieHeaders = authorizePage.getResponseHeaders("Set-Cookie");
        readInputFromHtml(authorizePage.asReader(), inputMap, INPUT_AUTHENTICITY_TOKEN,
                INPUT_REDIRECT_AFTER_LOGIN);
        final Configuration conf = twitter.getConfiguration();
        final List<HttpParameter> params = new ArrayList<>();
        params.add(new HttpParameter("oauth_token", oauthToken));
        params.add(new HttpParameter(INPUT_AUTHENTICITY_TOKEN, inputMap.get(INPUT_AUTHENTICITY_TOKEN)));
        if (inputMap.containsKey(INPUT_REDIRECT_AFTER_LOGIN)) {
            params.add(new HttpParameter(INPUT_REDIRECT_AFTER_LOGIN, inputMap.get(INPUT_REDIRECT_AFTER_LOGIN)));
        }
        params.add(new HttpParameter("session[username_or_email]", username));
        params.add(new HttpParameter("session[password]", password));
        final HeaderMap requestHeaders = new HeaderMap();
        requestHeaders.addHeader("Origin", "https://twitter.com");
        requestHeaders.addHeader("Referer",
                "https://twitter.com/oauth/authorize?oauth_token=" + requestToken.getToken());
        requestHeaders.put("Cookie", cookieHeaders);
        final String oAuthAuthorizationUrl = conf.getOAuthAuthorizationURL();
        final String oauthPin = readOAuthPINFromHtml(client.post(oAuthAuthorizationUrl, oAuthAuthorizationUrl,
                params.toArray(new HttpParameter[params.size()]), requestHeaders).asReader());
        if (isEmpty(oauthPin))
            throw new WrongUserPassException();
        return twitter.getOAuthAccessToken(requestToken, oauthPin);
    } catch (final IOException | TwitterException | NullPointerException | XmlPullParserException e) {
        throw new AuthenticationException(e);
    }
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void requestAccessToken(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();//w ww  .j  a  v a 2s.c  o  m

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg;
    String lCallbackURL = aToken.getString("callbackURL");
    try {
        if (!mCheckAuth(lResponse)) {
            mLog.error(lResponse.getString("msg"));
        } else {
            // get a new Twitter object for the user
            TwitterFactory lTwitterFactory = new TwitterFactory();
            Twitter lTwitter = lTwitterFactory.getInstance();
            lTwitter.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret());

            // pass callback URL to Twitter API if given
            RequestToken lReqToken = (lCallbackURL != null ? lTwitter.getOAuthRequestToken(lCallbackURL)
                    : lTwitter.getOAuthRequestToken());

            String lAuthenticationURL = lReqToken.getAuthenticationURL();
            String lAuthorizationURL = lReqToken.getAuthorizationURL();

            lResponse.setString("authenticationURL", lAuthenticationURL);
            lResponse.setString("authorizationURL", lAuthorizationURL);
            lMsg = "authenticationURL: " + lAuthenticationURL + ", authorizationURL: " + lAuthorizationURL;
            lResponse.setString("msg", lMsg);
            if (mLog.isInfoEnabled()) {
                mLog.info(lMsg);
            }

            aConnector.setVar(OAUTH_REQUEST_TOKEN, lReqToken);
            aConnector.setVar(TWITTER_VAR, lTwitter);
        }
    } catch (Exception lEx) {
        lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.luwrain.app.twitter.Auth.java

License:Open Source License

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("You must provide consumer key and consumer secret");
        return;/*w ww . ja  va 2 s  .c o  m*/
    }
    Twitter twitter = null;
    try {
        ConfigurationLuwrain conf = new ConfigurationLuwrain(args[0], args[1], null, null);
        twitter = new TwitterFactory(conf).getInstance();
        final 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 (accessToken == null) {
            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 (te.getStatusCode() == 401) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        } //while();
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());
    } catch (IllegalStateException e) {
        if (!twitter.getAuthorization().isEnabled())
            System.out.println("OAuth consumer key/secret is not set.");
        else
            e.printStackTrace();
    } catch (TwitterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.mariotaku.twidere.activity.AuthorizeActivity.java

License:Open Source License

@Override
public void onLoadFinished(final Loader<RequestToken> loader, final RequestToken data) {
    setSupportProgressBarIndeterminateVisibility(false);
    mRequestToken = data;//from   ww  w. j  a v  a2  s .  co  m
    if (data == null || mWebView == null) {
        Toast.makeText(this, R.string.error_occurred, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    mWebView.loadUrl(mAuthUrl = data.getAuthorizationURL());
}

From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java

License:Open Source License

public AccessToken getOAuthAccessToken(final String username, final String password)
        throws AuthenticationException {
    final RequestToken requestToken;
    try {/*from   w  w  w . ja v  a 2 s . c o m*/
        requestToken = twitter.getOAuthRequestToken(OAUTH_CALLBACK_OOB);
    } catch (final TwitterException e) {
        if (e.isCausedByNetworkIssue())
            throw new AuthenticationException(e);
        throw new AuthenticityTokenException();
    }
    HttpResponse authorizePage = null, authorizeResult = null;
    try {
        final String oauthToken = requestToken.getToken();
        final String authorizationUrl = requestToken.getAuthorizationURL();
        final HashMap<String, String> inputMap = new HashMap<>();
        authorizePage = client.get(authorizationUrl, authorizationUrl, null, null, null);
        final List<String> cookieHeaders = authorizePage.getResponseHeaders("Set-Cookie");
        readInputFromHtml(authorizePage.asReader(), inputMap, INPUT_AUTHENTICITY_TOKEN,
                INPUT_REDIRECT_AFTER_LOGIN);
        final Configuration conf = twitter.getConfiguration();
        final List<HttpParameter> params = new ArrayList<>();
        params.add(new HttpParameter("oauth_token", oauthToken));
        params.add(new HttpParameter(INPUT_AUTHENTICITY_TOKEN, inputMap.get(INPUT_AUTHENTICITY_TOKEN)));
        if (inputMap.containsKey(INPUT_REDIRECT_AFTER_LOGIN)) {
            params.add(new HttpParameter(INPUT_REDIRECT_AFTER_LOGIN, inputMap.get(INPUT_REDIRECT_AFTER_LOGIN)));
        }
        params.add(new HttpParameter("session[username_or_email]", username));
        params.add(new HttpParameter("session[password]", password));
        final HeaderMap requestHeaders = new HeaderMap();
        requestHeaders.addHeader("Origin", "https://twitter.com");
        requestHeaders.addHeader("Referer",
                "https://twitter.com/oauth/authorize?oauth_token=" + requestToken.getToken());
        final List<String> modifiedCookieHeaders = new ArrayList<>();
        final String oAuthAuthorizationUrl = conf.getOAuthAuthorizationURL();

        final String host = parseUrlHost(oAuthAuthorizationUrl);
        for (String cookieHeader : cookieHeaders) {
            for (HttpCookie cookie : HttpCookie.parse(cookieHeader)) {
                if (HttpCookie.domainMatches(cookie.getDomain(), host)) {
                    cookie.setVersion(1);
                    cookie.setDomain("twitter.com");
                }
                modifiedCookieHeaders.add(cookie.toString());
            }
        }
        requestHeaders.put("Cookie", modifiedCookieHeaders);
        authorizeResult = client.post(oAuthAuthorizationUrl, oAuthAuthorizationUrl,
                params.toArray(new HttpParameter[params.size()]), requestHeaders);
        final String oauthPin = readOAuthPINFromHtml(authorizeResult.asReader());
        if (isEmpty(oauthPin))
            throw new WrongUserPassException();
        return twitter.getOAuthAccessToken(requestToken, oauthPin);
    } catch (final IOException | TwitterException | NullPointerException | XmlPullParserException e) {
        throw new AuthenticationException(e);
    } finally {
        if (authorizePage != null) {
            try {
                authorizePage.disconnect();
            } catch (IOException ignore) {
            }
        }
        if (authorizeResult != null) {
            try {
                authorizeResult.disconnect();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:org.n52.twitter.TwitterAccessTokenRetriever.java

License:Open Source License

public static void main(String args[]) throws Exception {
    String[] props = readProperties();
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(props[0], props[1]);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//  ww w. ja v a2s. c  o  m
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        LOGGER.info("Open the following URL and grant access to your account:");
        LOGGER.info(requestToken.getAuthorizationURL());
        LOGGER.info("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()) {
                LOGGER.error("Unable to get the access token.");
            } else {
                LOGGER.error(te.getErrorMessage(), te);
            }
        }
    }
    storeAccessToken(accessToken.getToken(), accessToken.getTokenSecret());
}