Example usage for twitter4j.auth RequestToken getAuthenticationURL

List of usage examples for twitter4j.auth RequestToken getAuthenticationURL

Introduction

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

Prototype

public String getAuthenticationURL() 

Source Link

Usage

From source file:com.stronquens.amgtwitter.ControllerOAuth.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w  w  . j  a v a2s  .  co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Parametros del request
        HttpSession sesion = request.getSession();
        String verifier = request.getParameter("verifier");
        String op = request.getParameter("op");

        // Definimos variables
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        Twitter OAuthTwitter = null;
        String url = null;

        // Devolemos la url generada          
        if ((verifier == null || verifier == "") && "url".equalsIgnoreCase(op)) {
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                    .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
            OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
            sesion.setAttribute("twitter", OAuthTwitter);
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                sesion.setAttribute("requestToken", requestToken);
                url = requestToken.getAuthenticationURL();
                out.println("{\"url\":\"" + url + "\"}");
            } catch (TwitterException ex) {
            }
        }

        // Devolvemos el acces token generado
        if (verifier != null && verifier.length() > 0) {
            OAuthTwitter = (Twitter) sesion.getAttribute("twitter");
            requestToken = (RequestToken) sesion.getAttribute("requestToken");
            accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, verifier);
            sesion.setAttribute("accesToken", accessToken);
            sesion.removeAttribute("twitter");
            sesion.removeAttribute("requestToken");
            out.println("{\"token\":\"" + accessToken.getToken() + "\",\"secret\":\""
                    + accessToken.getTokenSecret() + "\"}");
        }

    }
}

From source file:com.twitstreet.servlet.SigninServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    response.setHeader("Pragma", "no-cache"); //HTTP 1.0
    response.setDateHeader("Expires", 0); //prevents caching at the proxy server

    Twitter twitter = new TwitterFactory().getInstance();
    try {/*from   w  w w  . ja  va2 s  .  co  m*/
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");
        logger.debug("Callback url is: " + callbackURL.toString());
        twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret());
        logger.debug("Consumer Key: " + configMgr.getConsumerKey() + ", Consumer Secret: "
                + configMgr.getConsumerSecret());
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute(CallBackServlet.REQUEST_TOKEN, requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());
        logger.debug("Redirect sent to authentication URL: " + requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:com.twitt4droid.activity.WebLoginActivity.java

License:Apache License

/** Sets up Twitter async listeners. */
private void setUpTwitter() {
    twitter = Twitt4droid.getAsyncTwitter(this);
    twitter.addListener(new TwitterAdapter() {
        @Override/*from w  w  w  . j av  a  2s. com*/
        public void verifiedCredentials(final User user) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    handleUserValidation(user);
                }
            });
        }

        @Override
        public void gotOAuthRequestToken(final RequestToken token) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    String url = token.getAuthenticationURL();
                    urlTextView.setText(url);
                    webView.loadUrl(url);
                }
            });
        }

        @Override
        public void gotOAuthAccessToken(final AccessToken token) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Twitt4droid.saveAuthenticationInfo(getApplicationContext(), token);
                }
            });
        }

        @Override
        public void onException(TwitterException te, TwitterMethod method) {
            Log.e(TAG, "Twitter error in " + method, te);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    showErrorAlertDialog();
                }
            });
        }
    });
}

From source file:de.hoesel.dav.buv.twitter.preferences.TwitterPreferencePage.java

License:Open Source License

private void createNewTwitterAuthentication(Composite parent) {

    RequestToken authRequestToken = null;
    try {/*from   w w  w  . ja  v a2s  .  com*/
        authRequestToken = twitter.getOAuthRequestToken();
    } catch (TwitterException e2) {
        e2.printStackTrace();
        throw new IllegalArgumentException(e2);
    }

    Composite composite = new Composite(parent, SWT.NONE);
    GridLayoutFactory.fillDefaults().numColumns(3).applyTo(composite);

    final String authRequest = authRequestToken.getAuthenticationURL();
    Link link = new Link(composite, SWT.NONE);
    GridDataFactory.fillDefaults().span(3, 1).applyTo(link);
    link.setText(
            "Klicken Sie auf den folgenden Link und gewhren Sie der Anwendung Zugriff auf Ihr Twitter Konto:\n<A href=\""
                    + authRequest + "\">" + authRequest + "</A>");

    link.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                // Open default external browser
                PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser()
                        .openURL(new URL(authRequest));
                setErrorMessage(null);
            } catch (PartInitException ex) {
                setErrorMessage(ex.getLocalizedMessage());
                Activator.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getLocalizedMessage()));
            } catch (MalformedURLException ex) {
                setErrorMessage(ex.getLocalizedMessage());
                Activator.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getLocalizedMessage()));
            }
        }
    });

    Label pinLabel = new Label(composite, SWT.NONE);
    pinLabel.setText("Twitter PIN:");
    GridDataFactory.fillDefaults().grab(false, false).applyTo(pinLabel);
    final Text pinText = new Text(composite, SWT.BORDER);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(pinText);

    final Button pinCheck = new Button(composite, SWT.PUSH);
    pinCheck.setText("Valdieren");
    GridDataFactory.fillDefaults().grab(false, false).applyTo(pinCheck);
    pinCheck.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                accessToken = twitter.getOAuthAccessToken(pinText.getText());
                if (accessToken != null) {
                    pinCheck.setEnabled(false);
                    pinText.setEnabled(false);
                    setMessage("Twitter Anmeldung erfolgreich.", PreferencePage.INFORMATION);
                } else {
                    pinCheck.setEnabled(true);
                    pinText.setEnabled(true);
                    setMessage("Twitter Anmeldung fehlgeschlagen.", PreferencePage.ERROR);
                }
            } catch (TwitterException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                pinCheck.setEnabled(true);
                pinText.setEnabled(true);
                setMessage("Twitter Anmeldung fehlgeschlagen. " + e1.getErrorMessage(), PreferencePage.ERROR);
            }

        }

    });
}

From source file:edu.stanford.muse.slant.SigninServlet.java

License:Apache License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  w  w w. j  ava  2s  .  c  o m*/
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(OAuth_consumerKey, OAuth_consumerSecret);
        request.getSession().setAttribute("twitter", twitter);
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (Exception e) {
        System.out.println(e);
    }

}

From source file:ens.demo.twitter.SigninServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w .ja v  a  2  s  . c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:hashimotonet.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 * /*w  w  w. j ava2  s . c o m*/
 * @param args
 *            message
 */
public static void main(String[] args) {
    /*
          try {
             new UpdateStatus().connectTwitter();
          } catch(Exception e) {
             e.printStackTrace();
          }
    */

    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
        System.exit(-1);
    }

    String message = "";
    for (int i = 0; i < args.length; i++) {
        message += args[i] + " ";
    }

    try {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            // get request token.
            // this will throw IllegalStateException if access token is
            // already available
            RequestToken requestToken = twitter.getOAuthRequestToken();

            //            RequestToken requestToken = new RequestToken(Globals.KEY,Globals.SECRET);
            String url = requestToken.getAuthenticationURL();
            System.out.println("url = " + url);

            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(message);
        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);
    }
}

From source file:net.codestory.http.filters.twitter.TwitterAuthenticator.java

License:Apache License

@Override
public URI getAuthenticateURI(String callbackUri) {
    Twitter twitter = twitterFactory.getInstance();
    try {//from w  w w  .  j  a  v a2  s.co  m
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUri);
        oauthRequestByToken.put(requestToken.getToken(), requestToken);
        return URI.create(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        throw new AuthenticationException(e);
    }
}

From source file:net.firejack.platform.web.security.twitter.TwitterAuthenticationProcessor.java

License:Apache License

@Override
public void processAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    if (StringUtils.isBlank(getTwitterConsumerKey()) || StringUtils.isBlank(getTwitterConsumerSecret())) {
        logger.error("Twitter consumer key or consumer secret configs were not set.");
        response.sendRedirect(getDefaultPageUrl());
    } else {//from   w  w  w.  ja v a  2s  . c  om
        HttpSession httpSession = request.getSession(true);
        Twitter twitter = (Twitter) httpSession.getAttribute(ATTR_TWITTER_API);
        if (twitter == null) {
            twitter = populateTwitterService();
            httpSession.setAttribute(ATTR_TWITTER_API, twitter);
        }
        if (isRequestTokenCase(request)) {
            RequestToken requestToken;
            try {
                requestToken = twitter.getOAuthRequestToken(getCallbackUrl());
                httpSession.setAttribute(ATTR_TWITTER_REQUEST_TOKEN, requestToken);
                response.sendRedirect(requestToken.getAuthenticationURL());//show twitter authentication form
            } catch (TwitterException e) {//service is unavailable
                logger.error("Twitter service is unavailable.");
                logger.error(e.getMessage(), e);
                cleanSessionInformation(httpSession);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Twitter service is unavailable.");
            } catch (IllegalStateException e) {//access token is already available
                logger.error("access token is already available");
                cleanSessionInformation(httpSession);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Twitter processor already having information about access token.");
            }
        } else if (isAuthenticationCallback(request)) {
            RequestToken requestToken = (RequestToken) httpSession.getAttribute(ATTR_TWITTER_REQUEST_TOKEN);

            String verifier = request.getParameter("oauth_verifier");
            try {
                twitter.getOAuthAccessToken(requestToken, verifier);
                httpSession.removeAttribute(ATTR_TWITTER_REQUEST_TOKEN);

                String browserIpAddress = request.getRemoteAddr();
                AuthenticationToken authenticationToken = this.getOpenFlameToken(twitter, browserIpAddress);

                if (authenticationToken == null) {
                    logger.error("Authentication token is null.");
                }
                getSignInProcessor().processSignInInternal(request, response, authenticationToken);
            } catch (TwitterException e) {
                logger.error(e.getMessage(), e);
                cleanSessionInformation(httpSession);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        }
    }
}

From source file:net.jeremybrooks.suprsetr.twitter.TwitterHelper.java

License:Open Source License

/**
 * Authenticates the user.// www .ja v  a 2 s  . c o m
 * <p/>
 * <p>This method will use the OAuth method of authentication. The user's
 * browser will be opened, and they will be prompted for the PIN. The
 * authentication token data will then be saved in the database.</p>
 *
 * @throws Exception if there are any errors.
 */
public static void authenticate() throws Exception {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("net.jeremybrooks.suprsetr.misc");
    twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(Main.getPrivateProperty("TWITTER_CONSUMER_KEY"),
            Main.getPrivateProperty("TWITTER_CONSUMER_SECRET"));
    try {
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken;
        String url = requestToken.getAuthenticationURL();
        java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));

        String pin = JOptionPane.showInputDialog(null,
                resourceBundle.getString("TwitterHelper.dialog.pin.message"),
                resourceBundle.getString("TwitterHelper.dialog.pin.title"), JOptionPane.INFORMATION_MESSAGE);
        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        // Save the access token
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_USERID, Long.toString(accessToken.getUserId()));
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_USERNAME,
                twitter.verifyCredentials().getName());
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_TOKEN, accessToken.getToken());
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_TOKEN_SECRET, accessToken.getTokenSecret());
    } catch (Exception e) {
        twitter = null;
        throw e;
    }
}