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.tuncaysenturk.jira.plugins.compatibility.servlet.TwitterLoginServlet.java

private void twitterCallback(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> context) {
    if (null == req.getParameter("denied") && null != req.getParameter("oauth_verifier")) {
        String verifier = req.getParameter("oauth_verifier").toString();

        PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet();
        propSet.setString("accessTokenVerifier", verifier);

        Twitter twitter = new TwitterFactory().getInstance();

        twitter.setOAuthConsumer(propSet.getString("consumerKey"), propSet.getString("consumerSecret"));
        RequestToken requestToken = new RequestToken(propSet.getString("requestToken"),
                propSet.getString("requestTokenSecret"));

        propSet.remove("requestToken");
        propSet.remove("requestTokenSecret");

        try {//from w ww .j a  v  a  2 s  . c o m
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            propSet.setString("accessToken", accessToken.getToken());
            propSet.setString("accessTokenSecret", accessToken.getTokenSecret());
            User user = twitter.verifyCredentials();
            logger.info(JTPConstants.LOG_PRE + "User :" + user.getScreenName() + " logged in successfully");
            restartListener(req, resp, context);
        } catch (TwitterException e) {
            logger.error(JTPConstants.LOG_PRE + "Error while streaming", e);
            ExceptionMessagesUtil.addExceptionMessage("Error while streaming : ", e);
        }
    } else {
        logger.warn(JTPConstants.LOG_PRE + "User denied Twitter authorization, plugin will not work properly");
        ExceptionMessagesUtil
                .addExceptionMessage("User denied Twitter authorization, plugin will not work properly");
    }

}

From source file:com.tuncaysenturk.jira.plugins.compatibility.servlet.TwitterLoginServlet.java

public void login(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> context) {
    Twitter twitter = new TwitterFactory().getInstance();

    try {//from  ww w  .  java 2  s  . c  o m
        PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet();
        URI servletConfigureTwitter = URI
                .create(applicationProperties.getBaseUrl() + JTPConstants.URL_CONFIGURE_TWITTER);
        String callbackURL = servletConfigureTwitter + QUESTION_MARK + IS_CALLBACK + EQUALS + TRUE;
        twitter.setOAuthConsumer(propSet.getString("consumerKey"), propSet.getString("consumerSecret"));
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);

        String requestToken_token = requestToken.getToken();
        String requestToken_secret = requestToken.getTokenSecret();

        propSet.setString("requestToken", requestToken_token);
        propSet.setString("requestTokenSecret", requestToken_secret);

        String redirectUrl = requestToken.getAuthorizationURL();
        resp.sendRedirect(redirectUrl);

    } catch (TwitterException e) {
        logger.error(JTPConstants.LOG_PRE + "Exception while logging to Twitter", e);
        @SuppressWarnings("unchecked")
        List<String> errorMessages = (List<String>) context.get("errorMessages");
        errorMessages.add(e.getMessage());
    } catch (IOException e) {
        logger.error(JTPConstants.LOG_PRE + "Exception while logging to Twitter", e);
    }
}

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

License:Open Source License

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();
    twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret());

    RequestToken requestToken = (RequestToken) request.getSession().getAttribute(REQUEST_TOKEN);
    String verifier = request.getParameter(OAUTH_VERIFIER);
    try {/*  w w  w .  j av  a  2s .  c o m*/
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        long userId = accessToken.getUserId();
        String screenName = accessToken.getScreenName();
        String oauthToken = accessToken.getToken();
        String oauthTokenSecret = accessToken.getTokenSecret();
        User user = null;
        user = userMgr.getUserById(userId);
        //new user
        if (user == null) {
            twitter4j.User twUser = twitter.showUser(userId);
            user = new User();
            user.setId(userId);
            user.setUserName(screenName);
            user.setLastIp(request.getRemoteAddr());
            user.setOauthToken(oauthToken);
            user.setOauthTokenSecret(oauthTokenSecret);
            user.setCash(configMgr.getInitialMoney());
            user.setPictureUrl(twUser.getProfileImageURL().toExternalForm());

            user.setDescription(twUser.getDescription());
            user.setLongName(twUser.getName());
            user.setLocation(twUser.getLocation());
            user.setLanguage(twUser.getLang());
            user.setUrl(twUser.getURL() == null ? null : twUser.getURL().toExternalForm());

            userMgr.saveUser(user);
            String referenceId = (String) request.getSession().getAttribute(HomePageServlet.REFERENCE_ID);
            long referenceLong = -1;
            try {
                referenceLong = Long.parseLong(referenceId);
            } catch (NumberFormatException e) {
                logger.error("Parsing reference id failed: " + referenceId);
            }
            if (referenceLong > -1) {
                userMgr.invite(referenceLong, user.getId());
            }
            request.getSession().removeAttribute(HomePageServlet.REFERENCE_ID);

        } else {
            //existing user logging in again
            user = new User();
            user.setId(userId);
            user.setUserName(screenName);
            user.setLastIp(request.getRemoteHost());
            user.setOauthToken(oauthToken);
            user.setOauthTokenSecret(oauthTokenSecret);
            user.setAutoPlayer(false);
            userMgr.updateUser(user);
        }
        request.getSession().setAttribute(User.USER_ID, user.getId());
        Cookie cookies[] = createCookie(userId, oauthToken);
        writeCookies(response, cookies);
    } catch (TwitterException e) {
        throw new ServletException(e);
    }
    response.sendRedirect(request.getContextPath() + "/");
}

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 . j  a  va2 s. c o 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.twitstreet.twitter.AnnouncerMgrImpl.java

License:Open Source License

public void loadAnnouncers() {
    Connection connection = null;
    PreparedStatement ps = null;//from ww  w.ja  va  2s. com
    ResultSet rs = null;
    try {
        connection = dbMgr.getConnection();
        ps = connection.prepareStatement(LOAD_ANNOUNCER);
        rs = ps.executeQuery();
        while (rs.next()) {
            Announcer announcer = new Announcer();
            announcer.getDataFromResultSet(rs);
            announcerDataList.add(announcer);
            if (TWITSTREET_GAME.equals(announcer.getName())) {
                twitstreetGame = new TwitterFactory().getInstance();
                twitstreetGame.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
                twitstreetGame.setOAuthAccessToken(
                        new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
            } else {
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
                twitter.setOAuthAccessToken(
                        new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
                announcerList.add(twitter);
            }
        }
        logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString());
    } catch (SQLException ex) {
        logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex);

    } finally {
        dbMgr.closeResources(connection, ps, rs);
    }

}

From source file:com.twitstreet.twitter.TwitterProxyImpl.java

License:Open Source License

@Inject
public TwitterProxyImpl(ConfigMgr configMgr, @Assisted("oauthToken") String oauthToken,
        @Assisted("oauthTokenSecret") String oauthTokenSecret) {
    this.configMgr = configMgr;
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret());
    accessToken = new AccessToken(oauthToken, oauthTokenSecret);

    oToken = oauthToken;/*from ww  w.ja  v  a2 s .c  o m*/
    oSecret = oauthTokenSecret;

    twitter.setOAuthAccessToken(accessToken);
    this.setTwitter(twitter);

    //top
    woiedMap.put("Worldwide", 1);
    //1
    woiedMap.put("Argentina", 23424747);
    woiedMap.put("Australia", 23424748);
    woiedMap.put("Brazil", 23424768);
    woiedMap.put("Canada", 23424775);
    woiedMap.put("Chile", 23424782);
    woiedMap.put("Colombia", 23424787);
    woiedMap.put("Dominican Republic", 23424800);
    woiedMap.put("Ecuador", 23424801);
    woiedMap.put("France", 23424819);
    woiedMap.put("Germany", 23424829);
    woiedMap.put("Guatemala", 23424834);
    woiedMap.put("India", 23424848);
    //2
    woiedMap.put("Indonesia", 23424846);
    woiedMap.put("Ireland", 23424803);
    woiedMap.put("Italy", 23424853);
    woiedMap.put("Japan", 23424856);
    woiedMap.put("Malaysia", 23424901);
    woiedMap.put("Mexico", 23424900);
    woiedMap.put("Netherlands", 23424909);
    woiedMap.put("New Zeland", 23424916);
    woiedMap.put("Nigeria", 23424908);
    woiedMap.put("Pakistan", 23424922);
    woiedMap.put("Peru", 23424919);
    woiedMap.put("Philippines", 23424934);
    //3
    woiedMap.put("Russia", 23424936);
    woiedMap.put("Singapore", 23424948);
    woiedMap.put("South Africa", 23424942);
    woiedMap.put("Spain", 23424950);
    woiedMap.put("Sweden", 23424954);
    woiedMap.put("Turkey", 23424969);
    woiedMap.put("United Arab Emirates", 23424738);
    woiedMap.put("United Kingdom", 23424975);
    woiedMap.put("United States", 23424977);
    woiedMap.put("Venezuela", 23424982);
}

From source file:com.zisal.twit.crawl.core.Example.java

public static void main(String[] args) {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ApplicationConstant.TwitterKey.CUSTOMER_KEY,
            ApplicationConstant.TwitterKey.CUSTOMER_SECRET);
    twitter.setOAuthAccessToken(//from   w w w  .ja va  2 s .  c  o  m
            new AccessToken(ApplicationConstant.TwitterKey.TOKEN, ApplicationConstant.TwitterKey.TOKEN_SECRET));
    /*try{
    ResponseList<Status> responseList = twitter.getUserTimeline(new Paging(1, 5));
    for(Status s: responseList){
        System.out.println("Response List ".concat(s.getText()));
    }
    }catch(Exception e){
    e.printStackTrace();
    }
            
    long cursor = -1;
    IDs ids = null;
    System.out.println("Listing followers's ids.");
    do {
    try {
        ids = twitter.getFollowersIDs(ApplicationConstant.Twitter.SCREEN_NAME, cursor);
        for (long id : ids.getIDs()) {
            System.out.println(id);
            User user = twitter.showUser(id);
            System.out.println(user.getName());
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
    } while ((cursor = ids != null ? ids.getNextCursor() : 0) != 0);*/

    long cursor = -1;
    PagableResponseList<User> pagableFollowings = null;
    List<User> listFriends = new ArrayList<>();
    do {
        try {
            pagableFollowings = twitter.getFriendsList(18211861, cursor);
            for (User user : pagableFollowings) {
                listFriends.add(user);
                logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend #1st level " + user.getName());
                /*PagableResponseList<User> _2ndLevelPageableFollowings = twitter.getFriendsList(user.getId(), cursor);
                for(User _2ndLevelFriend : _2ndLevelPageableFollowings){
                logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "added friend #2nd level "+ _2ndLevelFriend.getName());
                listFriends.add(_2ndLevelFriend);
                }*/
            }
        } catch (TwitterException e) {
            e.printStackTrace();
        }

    } while ((cursor = pagableFollowings.getNextCursor()) != 0);

    logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend total : " + listFriends.size());
    for (User user : listFriends) {
        logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend : " + user.getName());
    }

    /*
            cursor = -1;
            PagableResponseList<User> pagableFollowers = null;
            List<User> listFollowers = new ArrayList<>();
            do {
    try {
        pagableFollowers = twitter.getFollowersList(twitter.getId(), cursor);
        for (User user : pagableFollowers) {
            listFollowers.add(user); // ArrayList<User>
            System.out.println(user.getName());
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
            
            } while ((cursor = pagableFollowers.getNextCursor()) != 0);
    */

}

From source file:controllers.modules.CorpusModule.java

License:Open Source License

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;/*from   w  w w . ja v  a 2 s  .  co m*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:de.hikinggrass.eiwomisarc.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 * /* w w w . jav  a2 s .c  om*/
 * @param args
 *            message
 */
public UpdateStatus() {
    try {
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        //use https for oauth 
        confBuilder.setUseSSL(true);

        Configuration conf = confBuilder.build();
        Twitter twitter = new TwitterFactory(conf).getInstance();
        twitter.setOAuthConsumer("HaBxuZMHygmtcuPeCbOLg", "zg6bV26ksBrgKHdhmiLlubTtV9MaDhoIRZC1ODUKw");
        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("test from eiwomisarc");
        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:edu.stanford.muse.slant.SigninServlet.java

License:Apache License

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

    try {//w  w  w  .j  av  a2s .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);
    }

}