Example usage for twitter4j Twitter getOAuthAccessToken

List of usage examples for twitter4j Twitter getOAuthAccessToken

Introduction

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

Prototype

AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;

Source Link

Document

Retrieves an access token associated with the supplied request token and sets userId.

Usage

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  . j  a va2 s. c om*/
    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   www  . j a  v  a  2 s . com
 */
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);
    }
}

From source file:com.freedomotic.plugins.devices.twitter.gateways.OAuthSetup.java

License:Open Source License

/**
 * @param args//from   w w  w.  j a v  a 2 s.c om
 */
public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();

    //insert the appropriate consumer key and consumer secret here

    twitter.setOAuthConsumer("TLGtvoeABqf2tEG4itTUaw", "nUJPxYR1qJmhX9SnWTBT0MzO7dIqUtNyVPfhg10wf0");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        System.out.println("Open the following URL and grant access to your account:");
        System.out.println(requestToken.getAuthorizationURL());
        System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    //persist to the accessToken for future reference.
    System.out.println(twitter.verifyCredentials().getId());
    System.out.println("token : " + accessToken.getToken());
    System.out.println("tokenSecret : " + accessToken.getTokenSecret());
    //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:com.google.code.sagetvaddons.sagealert.server.TwitterServiceImpl.java

License:Apache License

public TwitterSettings submitPin(String pin) throws IOException {
    HttpSession sess = this.getThreadLocalRequest().getSession(false);
    Twitter t = null;
    RequestToken rTok = null;/*ww  w.j a v  a 2  s .  c  om*/
    if (sess != null) {
        t = (Twitter) sess.getAttribute("srv");
        rTok = (RequestToken) sess.getAttribute("rTok");
    }
    if (t == null || rTok == null)
        throw new IOException("Cannot submit PIN before generating RequestToken!");
    try {
        AccessToken aTok = t.getOAuthAccessToken(rTok, pin);
        TwitterSettings settings = new TwitterSettings(aTok.getScreenName(), aTok.getToken(),
                aTok.getTokenSecret());
        DataStore.getInstance().saveReporter(settings);
        return settings;
    } catch (TwitterException e) {
        LOG.error("Twitter error", e);
        throw new IOException(e);
    }
}

From source file:com.google.minijoe.sys.Eval.java

License:Apache License

public void evalNative(int index, JsArray stack, int sp, int parCount) {
    switch (index) {
    case ID_HTTP_GET:
        try {/* w ww  . j a v a  2s.c om*/
            String url = stack.getString(sp + 2);
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            stack.setObject(sp, response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        break;

    case ID_POST_JSON:
        try {
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                    stack.getString(sp + 3));
            Request request = new Request.Builder().url(stack.getString(sp + 2)).post(body).build();
            Response response = client.newCall(request).execute();
            stack.setObject(sp, response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        break;

    case ID_CRAWLER:
        try {
            Crawler.startCrawler(stack.getString(sp + 2));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        break;

    case ID_CURL:
        new Thread(new Curl()).start();
        break;

    case ID_EXTRACT_HTML:

        try {
            Readability readability = new Readability(new URL(stack.getString(sp + 2)), stack.getInt(sp + 3));
            readability.init();
            stack.setObject(sp, readability.outerHtml());
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        break;

    case ID_EVAL:
        try {
            stack.setObject(sp, eval(stack.getString(sp + 2),
                    stack.isNull(sp + 3) ? stack.getJsObject(sp) : stack.getJsObject(sp + 3)));
        } catch (Exception e) {
            throw new RuntimeException("" + e);
        }

        break;

    case ID_COMPILE:
        try {
            File file = new File(stack.getString(sp + 2));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            byte[] data = new byte[(int) file.length()];
            dis.readFully(data);
            String code = new String(data, "UTF-8");
            Eval.compile(code, System.out);
            dis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LOAD:
        try {
            File file = new File(stack.getString(sp + 2));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            byte[] data = new byte[(int) file.length()];
            dis.readFully(data);
            String code = new String(data, "UTF-8");
            //xxx.js
            Eval.eval(code, Eval.createGlobal());
            dis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_GEN_SITEMAP:

        try {
            // create web sitemap for web http://www.javavids.com
            WebSitemapGenerator webSitemapGenerator = new WebSitemapGenerator("http://www.javavids.com");
            // add some URLs
            webSitemapGenerator.addPage(new WebPage().setName("index.php").setPriority(1.0)
                    .setChangeFreq(ChangeFreq.NEVER).setLastMod(new Date()));
            webSitemapGenerator.addPage(new WebPage().setName("latest.php"));
            webSitemapGenerator.addPage(new WebPage().setName("contact.php"));
            // generate sitemap and save it to file /var/www/sitemap.xml
            File file = new File("/var/www/sitemap.xml");
            webSitemapGenerator.constructAndSaveSitemap(file);
            // inform Google that this sitemap has changed
            webSitemapGenerator.pingGoogle();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_WHOIS:
        try {
            stack.setObject(sp, Whois.getRawWhoisResults(stack.getString(sp + 2)));
        } catch (WhoisException e) {
            stack.setObject(sp, "Whois Exception " + e.getMessage());
        } catch (HostNameValidationException e) {
            stack.setObject(sp, "Whois host name invalid " + e.getMessage());
        }
        break;

    case ID_PAGERANK:
        stack.setObject(sp, PageRank.getPR(stack.getString(sp + 2)));
        break;

    case ID_SEND_TWITTER:
        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(stack.getString(sp + 2));
            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);
        }
        break;

    case ID_EXTRACT_TEXT:
        try {
            String url = stack.getString(sp + 2);
            String selector = stack.getString(sp + 3);

            Document doc = Jsoup.connect(url).userAgent("okhttp").timeout(5 * 1000).get();

            HtmlToPlainText formatter = new HtmlToPlainText();

            if (selector != null) {
                Elements elements = doc.select(selector);
                StringBuffer sb = new StringBuffer();
                for (Element element : elements) {
                    String plainText = formatter.getPlainText(element);
                    sb.append(plainText);
                }
                stack.setObject(sp, sb.toString());
            } else {
                stack.setObject(sp, formatter.getPlainText(doc));

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LIST_LINKS:
        try {
            String url = stack.getString(sp + 2);
            print("Fetching %s...", url);

            Document doc = Jsoup.connect(url).get();
            Elements links = doc.select("a[href]");
            Elements media = doc.select("[src]");
            Elements imports = doc.select("link[href]");

            print("\nMedia: (%d)", media.size());
            for (Element src : media) {
                if (src.tagName().equals("img"))
                    print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"),
                            src.attr("height"), trim(src.attr("alt"), 20));
                else
                    print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
            }

            print("\nImports: (%d)", imports.size());
            for (Element link : imports) {
                print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel"));
            }

            print("\nLinks: (%d)", links.size());
            for (Element link : links) {
                print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LOG:
        log.info(stack.getString(sp + 2));
        break;

    case ID_SEND_MAIL:
        try {
            // put your e-mail address here
            final String yourAddress = "guilherme.@gmail.com";

            // configure programatically your mail server info
            EmailTransportConfiguration.configure("smtp.server.com", true, false, "username", "password");

            // and go!
            new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress)
                    .withSubject("Fluent Mail API").withAttachment("file_name").withBody("Demo message").send();

        } catch (Exception ex) {
            stack.setObject(sp, "[ERROR]" + ex.getMessage());
        }
        break;

    case ID_SNAPPY:
        try {
            String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of "
                    + "Snappy, a fast compresser/decompresser.";
            byte[] compressed = Snappy.compress(input.getBytes("UTF-8"));
            byte[] uncompressed = Snappy.uncompress(compressed, 0, compressed.length);

            String result = new String(uncompressed, "UTF-8");
            System.out.println(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_OPENBROWSER:
        new Thread(new Runnable() {
            public void run() {
                openBrowser();
            }
        }).start();
        break;

    case ID_HELP:
        Enumeration ex = this.keys();
        while (ex.hasMoreElements()) {
            String key = (String) ex.nextElement();
            Object val = this.getRawInPrototypeChain(key);
            if (val instanceof JsFunction) {
                System.out.println(key + "---" + ((JsFunction) val).description);
            } else {
                System.out.println(key + "---" + val);
            }
        }
        break;

    default:
        super.evalNative(index, stack, sp, parCount);
    }
}

From source file:com.ikungolf.java.javatwitter.twitterCmd.java

public void updateStatus(String msg) {
    if (msg == null) {
        System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
        System.exit(-1);/*  w ww .j  a  v  a2s.  co m*/
    }
    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(msg);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    } 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:com.metadot.book.connectr.server.servlets.LoginTwitterCallbackServlet.java

License:Apache License

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

    Twitter twitter = new TwitterFactory().getInstance();
    String key = AuthenticationProvider.getProp("twitter-consumer-key");
    String secret = AuthenticationProvider.getProp("twitter-consumer-secret");

    RequestToken token = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    twitter.setOAuthConsumer(key, secret);

    try {/*  w ww .j a  v a 2  s.  c  o m*/
        twitter.getOAuthAccessToken(token, verifier);
        User user = twitter.verifyCredentials();
        log.info("Twitter user found:" + user.getName());
        request.getSession().removeAttribute("requestToken");
        String sid = ((Integer) user.getId()).toString();

        UserAccount u = new UserAccount(sid, AuthenticationProvider.TWITTER);
        // use screen name for uid
        u.setName(user.getScreenName());
        UserAccount connectr = new LoginHelper().loginStarts(request.getSession(), u);
        log.info("User id:" + connectr.getId().toString());

    } catch (TwitterException e) {
        e.printStackTrace();
    }

    response.sendRedirect(LoginHelper.getApplitionURL(request));
}

From source file:com.michaelfitzmaurice.clocktwerk.apps.TwitterPropertiesTool.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args// ww w  .  ja v a 2 s  .co  m
 */
public static void main(String[] args) {

    File file = new File(TWITTER4J_PROPERTIES_FILE_NAME);
    Properties prop = new Properties();
    InputStream is = null;

    try {
        if (file.exists()) {
            System.out.println("Using existing twitter4j.properties file: " + file.getAbsolutePath());
            is = new FileInputStream(file);
            prop.load(is);
        }

        if (args.length < 2) {
            verifyOAuthProperties(prop);
        } else {
            createSkeletonPropertiesFile(args[0], args[1], prop);
        }
    } catch (IOException ioe) {
        printStackTraceAndExitSystem(ioe, null);
    } finally {
        if (is != null) {
            try {
                is.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 in an authenticated " + "Twitter session as the target user:");
            System.out.println(requestToken.getAuthorizationURL());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            } catch (UnsupportedOperationException ignore) {
            }

            System.out.print("Enter the authorization PIN and hit enter:");
            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());

        OutputStream os = null;
        try {
            prop.setProperty(OAUTH_ACCESS_TOKEN_PROPERTY, accessToken.getToken());
            prop.setProperty(OAUTH_ACCESS_TOKEN_SECRET_PROPERTY, accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, TWITTER4J_PROPERTIES_FILE_NAME);
        } catch (IOException ioe) {
            printStackTraceAndExitSystem(ioe, null);
        } 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) {
        printStackTraceAndExitSystem(te, "Failed to get accessToken: " + te.getMessage());
    } catch (IOException ioe) {
        printStackTraceAndExitSystem(ioe, "Failed to read the system input.");
    }
}

From source file:com.michaelstark.twitteroauth.OAuthCallbackServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w w w .ja  v  a 2 s. c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String verificationToken = request.getParameter("oauth_verifier");

    HttpSession session = request.getSession(true);

    // Get the stored Twitter client from LoginServlet.
    Twitter twitter = (Twitter) session.getAttribute("twitterClient");

    // Get the saved request token.
    RequestToken requestToken = (RequestToken) session.getAttribute("requestToken");

    try {
        // Get an access token so we can do stuff.
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verificationToken);

        // Store the access token for later.
        session.setAttribute("accessToken", accessToken);

        // Configure the Twitter client to use our access token.
        twitter.setOAuthAccessToken(accessToken);

        // Get the current user info from Twitter and store it in the session.
        session.setAttribute("user", twitter.showUser(twitter.getScreenName()));
    } catch (TwitterException e) {
        logger.log(Level.SEVERE, "Could not get the user info: ", e);
    }

    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

License:Apache License

protected Task<AccessToken> doGetAccessToken(final Twitter instance, Bundle bundle) {
    final Task<AccessToken>.TaskCompletionSource source = Task.create();

    new AsyncTask<Bundle, Void, Object>() {

        @Override//from  w  w w  .j  a  va  2  s  . co m
        protected Object doInBackground(Bundle... params) {
            try {
                Bundle result = params[0];

                RequestToken token = (RequestToken) result.getSerializable("request_token");
                String verifier = result.getString("oauth_verifier");

                AccessToken accessToken = instance.getOAuthAccessToken(token, verifier);
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getScreenName() = " + accessToken.getScreenName());
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getUserId() = " + accessToken.getUserId());
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getToken() = " + accessToken.getToken());
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getTokenSecret() = " + accessToken.getTokenSecret());

                return accessToken;
            } catch (TwitterException e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o instanceof AccessToken) {
                source.trySetResult((AccessToken) o);
            } else {
                source.trySetError((Exception) o);
            }

        }
    }.execute(bundle);
    return source.getTask();
}