Example usage for twitter4j Twitter setOAuthConsumer

List of usage examples for twitter4j Twitter setOAuthConsumer

Introduction

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

Prototype

void setOAuthConsumer(String consumerKey, String consumerSecret);

Source Link

Document

sets the OAuth consumer key and consumer secret

Usage

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

License:Open Source License

/**
 * @param args//from   ww w  . j a  va  2 s  .com
 */
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.freshdigitable.udonroad.module.TwitterApiModule.java

License:Apache License

@Singleton
@Provides/*from w w w. ja  v a 2  s  .  c  o  m*/
public Twitter provideTwitter() {
    final TwitterFactory twitterFactory = new TwitterFactory();
    final Twitter twitter = twitterFactory.getInstance();
    final String key = context.getString(R.string.consumer_key);
    final String secret = context.getString(R.string.consumer_secret);
    twitter.setOAuthConsumer(key, secret);
    return twitter;
}

From source file:com.github.checkstyle.publishers.TwitterPublisher.java

License:Open Source License

/**
 * Publish post./* ww w  .  j ava  2s .  co  m*/
 * @throws TwitterException if an error occurs while publishing.
 * @throws IOException if there are problems with reading file with the post text.
 */
public void publish() throws TwitterException, IOException {
    final Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    final AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitter.setOAuthAccessToken(token);
    final String post = new String(Files.readAllBytes(Paths.get(postFilename)), StandardCharsets.UTF_8);
    twitter.updateStatus(post);
}

From source file:com.gmail.altakey.joanne.service.TwitterAuthService.java

License:Apache License

@Override
public void onHandleIntent(Intent data) {
    final Twitter tw = TwitterFactory.getSingleton();
    try {/*from  w  w  w.jav  a  2 s  .  com*/
        tw.setOAuthConsumer(getString(R.string.consumer_key), getString(R.string.consumer_secret));
    } catch (IllegalStateException e) {
    }

    final String action = data.getAction();

    if (ACTION_AUTH.equals(action)) {
        authenticate(tw);
    } else if (ACTION_AUTH_VERIFY.equals(action)) {
        final String verifier = data.getStringExtra(EXTRA_VERIFIER);
        authenticateDone(tw, verifier);
    }
    stopSelf();
}

From source file:com.google.code.sagetvaddons.sagealert.server.TwitterServiceImpl.java

License:Apache License

public String getPinUrl() throws IOException {
    HttpSession sess = this.getThreadLocalRequest().getSession();
    RequestToken rTok = null;/*from w  w  w.j  a  v  a  2  s . c o  m*/
    Twitter t = new TwitterFactory().getInstance();
    t.setOAuthConsumer(TwitterServer.C_KEY, TwitterServer.C_HUSH);
    try {
        rTok = t.getOAuthRequestToken();
        sess.setAttribute("rTok", rTok);
        sess.setAttribute("srv", t);
    } catch (TwitterException e) {
        LOG.error("Twitter error", e);
        throw new IOException(e);
    }
    return rTok.getAuthenticationURL();
}

From source file:com.isitbusythere.reporter.TwitterSessionStore.java

License:Apache License

public static boolean restore(Twitter session, Context context) {
    SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);

    session.setOAuthConsumer(context.getString(R.string.TWITTER_APP_KEY),
            context.getString(R.string.TWITTER_APP_SECRET));

    String userToken = savedSession.getString(TOKEN, null);

    if (userToken == null) {
        session = null;/*from w  w w.  j a v  a 2  s . c om*/
        return false;
    }

    try {
        session.setOAuthAccessToken(new AccessToken(userToken, savedSession.getString(SECRET, null)));

    } catch (IllegalStateException e) {
        //I don't care
    }

    return true;
}

From source file:com.jeanchampemont.wtfdyum.service.impl.TwitterServiceImpl.java

License:Apache License

private Twitter twitter() {
    final Twitter instance = twitterFactory.getInstance();
    instance.setOAuthConsumer(appId, appSecret);
    return instance;
}

From source file:com.mastfrog.acteur.twitter.TwitterSign.java

@SuppressWarnings("unchecked")
RemoteUserInfo zgetUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential,
        AuthorizationResponse auth)//from   ww  w  .j a  v  a  2 s. c  o  m
        throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException {
    System.setProperty("twitter4j.http.useSSL", "false");

    Twitter twitter = TwitterFactory.getSingleton();
    try {
        // Idiotic - shutdown does not clear state
        twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    } catch (Exception e) {
        e.printStackTrace();
    }
    twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret));
    OAuthAuthorization a = new OAuthAuthorization(twitter.getConfiguration());
    a.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);

    URL url = URL.builder(Protocols.HTTPS)
            //        URL url = URL.builder(Protocols.HTTP) // XXX NOT UNENCRYPTED!  JUST FOR DEBUGING
            .setHost(Host.parse("api.twitter.com")).setPath("1.1/account/verify_credentials.json").create();

    String hdr = new SigBuilder().add(oauth_token, auth.accessToken).add(OAuthHeaders.oauth_nonce, oauth_nonce)
            .toHeader(Method.GET, url.getPathAndQuery(), auth); // XXX encode URL?

    String franken = a.xgenerateAuthorizationHeader(oauth_nonce, "GET", "/1.1/account/verify_credentials.json",
            new HttpParameter[0], new twitter4j.auth.AccessToken(auth.accessToken, auth.accessTokenSecret));

    OAuthAuthorization oa = new OAuthAuthorization(twitter.getConfiguration());
    oa.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    oa.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret));

    twitter4j.internal.http.HttpRequest r = new twitter4j.internal.http.HttpRequest(RequestMethod.GET,
            "https://api.twitter.com/twitter4j.internal.http.HttpRequest", new HttpParameter[0], oa,
            Collections.<String, String>emptyMap());

    ResponseLatch latch = new ResponseLatch();
    RH rh = new RH();
    client.get().setURL(url).addHeader(Headers.stringHeader("Authorization"), hdr)
            .addHeader(Headers.stringHeader("X-Twitter-Client-URL"),
                    "http://twitter4j.org/en/twitter4j-3.0.4-SNAPSHOT.xml")
            .addHeader(Headers.stringHeader("X-Twitter-Client"), "Twitter4J")
            .addHeader(Headers.stringHeader("Accept-Encoding"), "gzip")
            .addHeader(Headers.stringHeader("X-Twitter-Client-Version"), "3.0.4-SNAPSHOT")
            .addHeader(Headers.stringHeader("Accept"), "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
            //                .addHeader(Headers.stringHeader("Accept"), "*/*")
            //                .addHeader(Headers.stringHeader("Connection"), "keep-alive")
            .noDateHeader()
            //                .noConnectionHeader()
            //                .addHeader(Headers.stringHeader("Content-Type"), "application/x-www-form-urlencoded")
            //                .setBody("screen_name=kablosna", MediaType.PLAIN_TEXT_UTF_8)
            .on(StateType.Closed, latch).on(StateType.Timeout, latch).execute(rh);
    rh.await(1, TimeUnit.MINUTES);
    latch.latch.await(1, TimeUnit.MINUTES);

    String responseBody = rh.getResponse();

    RUI rui = new RUI();
    if (responseBody == null) {
        //            System.out.println("NULL RESPONSE BODY.");
        throw new IOException(rh.toString());
    }
    rui.putAll(new ObjectMapper().readValue(responseBody, Map.class));
    return rui;
}

From source file:com.mastfrog.acteur.twitter.TwitterSign.java

RemoteUserInfo getUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential,
        AuthorizationResponse auth)/*from w  ww .j a  v  a  2  s  .  c  om*/
        throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException {
    //        System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.StdOutLogger");
    System.setProperty("twitter4j.debug", "true");
    System.setProperty("twitter4j.http.useSSL", "false");

    Twitter twitter = TwitterFactory.getSingleton();
    try {
        // Idiotic 
        twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    } catch (Exception e) {
        e.printStackTrace();
    }
    twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret));
    try {
        User user = twitter.verifyCredentials();

        RUI rui = new RUI();
        rui.put("displayName", user.getName());
        rui.put("name", user.getScreenName() + "@api.twitter.com");
        rui.put("screen_name", user.getScreenName());

        rui.put("picture", user.getProfileImageURLHttps());
        rui.put("pictureLarge", user.getBiggerProfileImageURLHttps());
        rui.put("id", user.getId());
        return rui;
    } catch (TwitterException ex) {
        throw new IOException(ex);
    } finally {
        twitter.shutdown();
    }
}

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 {//from  ww w  .  ja  v a2 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));
}