Example usage for twitter4j Twitter getOAuthRequestToken

List of usage examples for twitter4j Twitter getOAuthRequestToken

Introduction

In this page you can find the example usage for twitter4j Twitter getOAuthRequestToken.

Prototype

RequestToken getOAuthRequestToken() throws TwitterException;

Source Link

Document

Retrieves a request token

Usage

From source file:com.aldebaran.demo.picture.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message//from w w  w .  j  a v a 2s  .co  m
 */
public static void main(String[] args) {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        if (args.length < 2) {
            if (null == prop.getProperty("oauth.consumerKey")
                    && null == prop.getProperty("oauth.consumerSecret")) {
                // consumer key/secret are not set in twitter4j.properties
                System.out.println(
                        "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                System.exit(-1);
            }
        } else {
            prop.setProperty("oauth.consumerKey", args[0]);
            prop.setProperty("oauth.consumerSecret", args[1]);
            os = new FileOutputStream("twitter4j.properties");
            prop.store(os, "twitter4j.properties");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        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());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (UnsupportedOperationException ignore) {
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            }
            System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
            try {
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                }
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());

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

From source file:com.allenzheng.twittersyn.utility.impl.TwitterAPIImpl.java

License:Apache License

    public String getAuthorisationUrl() throws TwitterException{
      Properties prop = loadProperties();
      //from w w w . j a v  a  2s  . co m
         Twitter twitter = new TwitterFactory().getInstance();
         twitter.setOAuthConsumer(prop.getProperty("twitter.consumerkey"), 
               prop.getProperty("twitter.consumersecret"));
         try {
            RequestToken requestToken;
            if (callbackUrl == null) {
               requestToken = twitter.getOAuthRequestToken();
            } else {
               requestToken = twitter
                     .getOAuthRequestToken(callbackUrl);
            }
            String authorisationUrl = requestToken
                  .getAuthorizationURL();
//            session.setAttribute(ATTR_TWITTER, twitter);
//            session.setAttribute(ATTR_REQUEST_TOKEN, requestToken);

            logger.debug("Redirecting user to " + authorisationUrl);
//            response.sendRedirect(authorisationUrl);
            return authorisationUrl;
         } catch (TwitterException e) {
            logger.error("Sign in with Twitter failed - "
                  + e.getMessage());
            e.printStackTrace();
            throw new TwitterException(e);
         }
      
      
   }

From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java

License:Open Source License

@Command(name = "twituser", desc = "Add your twitter account so you can tweet from IRC")
@Usage(".twituser <twitter username>")
public CommandResult twituser(CommandSource source, CommandContext context) {
    if (source.getSource() != CommandSource.Source.USER) {
        return get(ReturnType.MESSAGE, "Muse be done from IRC.", source, context);
    }/* ww w.  ja va2s. c  om*/

    if (context.getPrefix() == null || !context.getPrefix().equals(".")) {
        return null;
    }

    if (context.getArgs() == null || context.getArgs().length < 1) {
        return get(ReturnType.MESSAGE, "Correct usage is .twituser <twitter username>", source, context);
    }

    String username = context.getArgs()[0];
    CyborgUser permsAccount = getUser(source.getUser());

    if (getUser(source.getUser()) == null) {
        return get(ReturnType.NOTICE,
                "You have not registered with me! You need to register to add a twitter account! Type .register for help!",
                source, context);
    }

    TwitterUser twitterUser = getDatabase().select(TwitterUser.class).where()
            .equal("permUser", permsAccount.getName()).execute().findOne();
    if (twitterUser != null) {
        return get(ReturnType.NOTICE, "You already have an twitter user associated with your account!", source,
                context);
    }

    if (tokenMap.get(permsAccount.getName()) != null) {
        return get(ReturnType.NOTICE,
                "You already have twitter OAuth URL! Get your pin and type .twitpin <pin>", source, context);
    }

    Twitter twitter = defaultTwitterFactory.getInstance();
    try {
        RequestToken token = twitter.getOAuthRequestToken();
        tokenMap.put(permsAccount.getName(), token);
        StringBuilder body = new StringBuilder();
        body.append("Here is your OAuth Auth URL: ").append(token.getAuthorizationURL()).append(lineBreak)
                .append("Go to it. Sign in to twitter and Authorize this Bot. After granting access, it will give you a pin.")
                .append(lineBreak).append("Execute this command to finish the registration: .twitpin <pin>");
        return get(ReturnType.NOTICE, body.toString(), source, context);
    } catch (TwitterException e) {
        e.printStackTrace();
        return get(ReturnType.MESSAGE, "Internal Twitter Exception httpcode:" + e.getStatusCode(), source,
                context);
    }
}

From source file:com.amandine.twitterpostforcoucou.Tweet.java

private void publishStatusUpdateWithMedia(String message) throws MalformedURLException, IOException {
    Status status = null;/*  w  w  w.  jav a 2 s .  c o m*/
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            RequestToken requestToken = twitter.getOAuthRequestToken();
            AccessToken accessToken = null;
            while (null == accessToken) {
                logger.fine("Open the following URL and grant access to your account:");
                logger.fine(requestToken.getAuthorizationURL());
                try {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                } catch (TwitterException te) {
                    if (401 == te.getStatusCode()) {
                        logger.severe("Unable to get the access token.");
                    } else {
                        te.printStackTrace();
                    }
                }
            }
            logger.log(Level.INFO, "Got access token.");
            logger.log(Level.INFO, "Access token: {0}", accessToken.getToken());
            logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                logger.severe("OAuth consumer key/secret is not set.");
                return;
            }
        }
        //Instantiate and initialize a new twitter status update
        StatusUpdate statusUpdate = new StatusUpdate(message);
        //attach any media, if you want to
        statusUpdate.setMedia(
                //title of media
                "Amandine Leforestier Spring Summer 2015 white",
                new URL("https://issuu.com/kadiemurphy/docs/volume_xxi_issuu/52?e=0").openStream());
        //tweet or update status
        status = twitter.updateStatus(statusUpdate);

        //Status status = twitter.updateStatus(message);
        logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText());
    } catch (TwitterException te) {
        te.printStackTrace();
        logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage());
    }
}

From source file:com.amandine.twitterpostforcoucou.Tweet.java

public Twitter getTwitter() {
    Twitter twitter = new TwitterFactory().getInstance();
    try {/*  ww w  .  ja v a 2s  .c om*/
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken = null;
        while (null == accessToken) {
            logger.fine("Open the following URL and grant access to your account:");
            logger.fine(requestToken.getAuthorizationURL());
            try {
                accessToken = twitter.getOAuthAccessToken(requestToken);
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    logger.severe("Unable to get the access token.");
                } else {
                    logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage());
                }
            }
        }
        logger.log(Level.INFO, "Got access token.");
        logger.log(Level.INFO, "Access token: {0}", accessToken.getToken());
        logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret());
    } catch (IllegalStateException ie) {
        // access token is already available, or consumer key/secret is not set.
        if (!twitter.getAuthorization().isEnabled()) {
            logger.log(Level.SEVERE, "OAuth consumer key/secret is not set: {0}", ie.getMessage());
            return null;
        }
    } catch (TwitterException te) {
        logger.log(Level.SEVERE, "OAuth request token: {0}", te.getMessage());
    }
    return twitter;
}

From source file:com.appspot.bitlyminous.standalone.TwitterExample.java

License:Apache License

/**
 * The main method.//w w w.j  av a2  s.  c  om
 * 
 * @param args the arguments
 * 
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer("671O1zUicFBCYHHYVp0XA", "cP7WvfAtxXGSaf1Sz0ksZtWGcENosFcRr46WR7a9jU");
    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 available) 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.
    System.out.println("Screen name:" + accessToken.getScreenName());
    System.out.println("Token:" + accessToken.getToken());
    System.out.println("Secret:" + accessToken.getTokenSecret());

    IDs friendsIDs = twitter.getFriendsIDs("gapinginfinity");
    System.out.println(Arrays.toString(friendsIDs.getIDs()));

    ResponseList<Status> favorites = twitter.getFavorites("gapinginfinity");
    System.out.println(favorites.size());
    System.exit(0);
}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/login.arihant15")
public void doLogin(HttpServletRequest req, HttpServletResponse res) {
    try {//w  w  w  .  ja  v a2  s . c  o m
        ConfigurationBuilder configuration = new ConfigurationBuilder();
        configuration.setOAuthConsumerKey(ConsumerKey);
        configuration.setOAuthConsumerSecret(ConsumerSecret);
        TwitterFactory twitterfactory = new TwitterFactory(configuration.build());
        Twitter twitter = twitterfactory.getInstance();
        req.getSession().setAttribute("t", twitter);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        req.getSession().setAttribute("rToken", requestToken);
        res.sendRedirect(requestToken.getAuthenticationURL());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java

License:Apache License

public static AccessToken getAccessToken(String username) {
    AccessToken accessToken = null;//from   w w w .  java  2  s .  co  m
    if (Prefs.get(username + "/accessToken").isEmpty()) {
        Twitter twitter = factory.getInstance();
        twitter.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret"));
        RequestToken requestToken;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            requestToken = twitter.getOAuthRequestToken();
            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 ex) {
                    if (401 == ex.getStatusCode()) {
                        System.out.println("Unable to get the access token.");
                    } else {
                        logger.log(Level.SEVERE, "Unable to get the Access Token", ex);
                    }
                }
            }
        } catch (IOException | TwitterException ex) {
            logger.log(Level.SEVERE, "Unable to get the Access Token", ex);
        }
        Prefs.put(username + "/accessToken", accessToken.getToken());
        Prefs.put(username + "/accessTokenSecret", accessToken.getTokenSecret());
    }
    logger.finest("Token&Secret: " + Prefs.get(username + "/accessToken") + " "
            + Prefs.get(username + "/accessTokenSecret"));
    logger.finest("OauthConsum&Secret: " + Prefs.get("OAuthConsumerKey") + " " + Prefs.get("consumerSecret"));

    accessToken = new AccessToken(Prefs.get(username + "/accessToken"),
            Prefs.get(username + "/accessTokenSecret"));
    return accessToken;
}

From source file:com.esri.gpt.framework.security.identity.open.OpenidConsumerServlet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestContext context = null;/*from w w  w .ja va  2s  . co m*/
    boolean useFacade = false;
    String err = "";
    try {
        LOGGER.finer("Query string=" + request.getQueryString());

        String op = request.getParameter("op");
        context = RequestContext.extract(request);
        OpenProviders providers = context.getIdentityConfiguration().getOpenProviders();
        if ((providers == null) || (providers.size() == 0)) {
            return;
        }
        String baseContextPath = RequestContext.resolveBaseContextPath(request);
        String callbackUrl = baseContextPath + "/openid";
        String realm = baseContextPath;
        HttpSession session = request.getSession();

        // process a response from an Openid provider
        if (op == null) {
            String identity = null;
            String username = null;
            String email = null;

            // determine the callback info
            String cbinfo = Val.chkStr((String) session.getAttribute(ATTR_CBINFO));
            session.setAttribute(ATTR_CBINFO, null);
            if (cbinfo.length() == 0) {
                throw new ServletException("Invalid openid callback info.");
            }

            int idx = cbinfo.indexOf(",");
            long millis = Long.parseLong(cbinfo.substring(0, idx));
            cbinfo = cbinfo.substring(idx + 1);
            idx = cbinfo.indexOf(",");
            String cbid = cbinfo.substring(0, idx);
            cbinfo = cbinfo.substring(idx + 1);
            idx = cbinfo.indexOf(",");
            op = cbinfo.substring(0, idx);
            String fwd = cbinfo.substring(idx + 1);
            LOGGER.finer("cbinfo retrieved: " + cbinfo);

            // determine the provider
            OpenProvider provider = providers.get(op);
            if (provider == null) {
                throw new ServletException("Invalid openid op parameter on callback: " + op);
            }
            boolean isTwitter = provider.getName().equalsIgnoreCase("Twitter");

            // determine the authenticated user attributes
            if (useFacade) {
                identity = "http://openidfacade/user123";
                email = "user123@openidfacade.com";
                username = email;

                // Twitter callback
            } else if (isTwitter) {
                try {
                    LOGGER.finer("Determining user attributes for: " + op);
                    String token = (String) session.getAttribute(ATTR_TOKEN);
                    String tokenSecret = (String) session.getAttribute(ATTR_TOKEN_SECRET);
                    Twitter twitter = new Twitter();
                    twitter.setOAuthConsumer(provider.getConsumerKey(), provider.getConsumerSecret());
                    AccessToken accessToken = twitter.getOAuthAccessToken(token, tokenSecret);
                    twitter.setOAuthAccessToken(accessToken);
                    twitter4j.User tUser = twitter.verifyCredentials();
                    String screenName = Val.chkStr(tUser.getScreenName());
                    if (screenName.length() > 0) {
                        username = screenName + "@twitter";
                        identity = "twitter:" + screenName;
                    }
                } catch (Exception e) {
                    err = "oAuth authentication failed.";
                    LOGGER.log(Level.WARNING, err, e);
                }

                // Openid callback
            } else {
                try {

                    // determine the callback UUID
                    String cbidParam = Val.chkStr(request.getParameter("cbid"));
                    if (cbidParam.length() == 0) {
                        throw new ServletException("Empty cbid parameter on callback.");
                    }

                    if (!cbid.equals(cbidParam)) {
                        throw new ServletException("Invalid openid cbid parameter on callback.");
                    }
                    callbackUrl += "?cbid=" + java.net.URLEncoder.encode(cbid, "UTF-8");
                    LOGGER.finer("cbinfo based callback: " + cbinfo);
                    LOGGER.finer("Determining user attributes for: " + op);

                    OpenIdManager manager = new OpenIdManager();
                    manager.setRealm(realm);
                    manager.setReturnTo(callbackUrl);

                    checkNonce(request.getParameter("openid.response_nonce"));
                    byte[] mac_key = (byte[]) session.getAttribute(ATTR_MAC);
                    String alias = (String) session.getAttribute(ATTR_ALIAS);
                    Authentication authentication = manager.getAuthentication(request, mac_key, alias);
                    identity = authentication.getIdentity();
                    email = authentication.getEmail();
                    username = email;
                } catch (Exception e) {
                    err = "Openid authentication suceeded, creating local user reference failed.";
                    LOGGER.log(Level.WARNING, err, e);
                }
            }

            // check the parameters
            identity = Val.chkStr(identity);
            username = Val.chkStr(username);
            email = Val.chkStr(email);
            LOGGER.finer(
                    "User attributes: identity=" + identity + ", username=" + username + ", email=" + email);
            if (identity.length() == 0) {
                err = "Your openid idenitfier was not determined.";
            } else if (username.length() == 0) {
                if (isTwitter) {
                    err = "Your opennid screen name was not determined.";
                } else {
                    err = "Your opennid email address was not determined.";
                }
            } else {

                // establish the user
                identity = "urn:openid:" + identity;
                User user = context.getUser();
                user.reset();
                user.setKey(identity);
                user.setDistinguishedName(identity);
                user.setName(username);
                user.getProfile().setUsername(username);
                if (email.length() > 0) {
                    user.getProfile().setEmailAddress(email);
                }
                user.getAuthenticationStatus().setWasAuthenticated(true);

                // ensure a local reference for the user
                try {
                    LocalDao localDao = new LocalDao(context);
                    localDao.ensureReferenceToRemoteUser(user);
                } catch (Exception e) {
                    user.reset();
                    err = "Openid authentication suceeded, creating local user reference failed.";
                    LOGGER.log(Level.SEVERE, err, e);
                }
            }

            // redirect to the originating page
            String url = fwd;
            err = Val.chkStr(err);
            if (err.length() > 0) {
                if (url.indexOf("?") == -1)
                    fwd += "?";
                else
                    url += "&";
                url += "err=" + URLEncoder.encode(err, "UTF-8");
            }
            response.sendRedirect(url);

            // process a request to enter Openid credentials
        } else if (op.length() > 0) {
            session.setAttribute(ATTR_CBINFO, null);

            // determine the provider
            OpenProvider provider = providers.get(op);
            if (provider == null) {
                throw new ServletException("Invalid openid op parameter: " + op);
            }
            boolean isTwitter = provider.getName().equalsIgnoreCase("Twitter");

            // determine the active Geoportal page (forward URL)
            String fwd = Val.chkStr(request.getParameter("fwd"));
            if (fwd.length() == 0) {
                throw new ServletException("Empty openid fwd parameter.");
            }

            // store the callback info
            String cbid = UUID.randomUUID().toString();
            long millis = System.currentTimeMillis();
            String cbinfo = millis + "," + cbid + "," + op + "," + fwd;
            session.setAttribute(ATTR_CBINFO, cbinfo);

            // determine the Openid Authentication URL
            String url = null;
            if (useFacade) {
                PrintWriter pw = response.getWriter();
                pw.println("<html><head><title>Openid Facade</title></head><body><h1>Openid Facade</h1>");
                pw.println("<a href=\"" + callbackUrl + "\">Supply credentials step</a>");
                pw.println("</body></html>");
                pw.flush();
                return;

                // Twitter
            } else if (isTwitter) {
                try {
                    LOGGER.fine("Initiating oAuth request for: " + op + ", callback=" + callbackUrl);
                    Twitter twitter = new Twitter();
                    twitter.setOAuthConsumer(provider.getConsumerKey(), provider.getConsumerSecret());
                    RequestToken requestToken = twitter.getOAuthRequestToken();
                    String token = requestToken.getToken();
                    String tokenSecret = requestToken.getTokenSecret();
                    session.setAttribute(ATTR_TOKEN, token);
                    session.setAttribute(ATTR_TOKEN_SECRET, tokenSecret);
                    url = requestToken.getAuthorizationURL();
                } catch (TwitterException e) {
                    err = "Unable to determine endpoint for: " + op;
                    LOGGER.log(Level.SEVERE, err, e);
                }

                // Openid
            } else {
                try {
                    callbackUrl += "?cbid=" + java.net.URLEncoder.encode(cbid, "UTF-8");
                    LOGGER.finer("Initiating openid request for: " + op + ", callback=" + callbackUrl);
                    OpenIdManager manager = new OpenIdManager();
                    manager.setRealm(realm);
                    manager.setReturnTo(callbackUrl);

                    // There is an issue here. It seems that the only way to set the endpoint
                    // alias is through the jopenid-1.07.jar openid-providers.properties,
                    // but we would to to configure the provider properties through gpt.xml

                    //Endpoint endpoint = manager.lookupEndpoint(provider.getAuthenticationUrl());
                    Endpoint endpoint = manager.lookupEndpoint(op);

                    Association association = manager.lookupAssociation(endpoint);
                    request.getSession().setAttribute(ATTR_MAC, association.getRawMacKey());
                    request.getSession().setAttribute(ATTR_ALIAS, endpoint.getAlias());
                    url = manager.getAuthenticationUrl(endpoint, association);
                } catch (Exception e) {
                    err = "Unable to determine Openid endpoint for: " + op;
                    LOGGER.log(Level.SEVERE, err, e);
                }

            }

            // redirect to the authentication endpoint or to originating page
            err = Val.chkStr(err);
            if (err.length() > 0) {
                url = fwd;
                if (url.indexOf("?") == -1)
                    fwd += "?";
                else
                    url += "&";
                url += "err=" + URLEncoder.encode(err, "UTF-8");
            }
            LOGGER.finer("Redirecting for authentication: " + url);
            response.sendRedirect(url);

        } else {
            throw new ServletException("Empty openid op parameter.");
        }
    } finally {
        if (context != null)
            context.onExecutionPhaseCompleted();
    }
}

From source file:com.esz.thaifloodreporter.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 *
 * @param args message/*from w  w w . j  a v a  2  s  .  c  o m*/
 */
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);
    }
}