Example usage for twitter4j TwitterFactory getInstance

List of usage examples for twitter4j TwitterFactory getInstance

Introduction

In this page you can find the example usage for twitter4j TwitterFactory getInstance.

Prototype

public Twitter getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:org.fenixedu.bennu.social.domain.api.TwitterAPI.java

License:Open Source License

@Override
public String getAuthenticationUrlForUser(User user) {

    try {/*from  w w w .  ja  v a  2 s .c o m*/
        TwitterFactory tf = new TwitterFactory();
        Twitter twitter = tf.getInstance();
        twitter.setOAuthConsumer(getClientId(), getClientSecret());

        RequestToken oauthRequestToken = twitter.getOAuthRequestToken(getCallbackURL());

        String oauthToken = oauthRequestToken.getToken();
        String oauthTokenSecret = oauthRequestToken.getTokenSecret();
        String authorizationURL = oauthRequestToken.getAuthorizationURL();

        LOGGER.info("Received OauthToken. Token: " + oauthToken + ", TokenSecret: " + oauthTokenSecret
                + ", AuthenticationURL: " + authorizationURL);

        TwitterUser twitterUser = new TwitterService().getAuthenticatedUser(user);
        twitterUser.setOauthToken(oauthToken);
        twitterUser.setOauthTokenSecret(oauthTokenSecret);

        return authorizationURL;

    } catch (TwitterException e) {
        LOGGER.error("Received TwitterException:" + e.getErrorMessage());
        e.printStackTrace();
        return "";
    }
}

From source file:org.glassfish.jersey.sample.sse.TwitterBean.java

License:Open Source License

/**
 * Since twitter uses the v1.1 API we use twitter4j to get
 * the search results using OAuth//w w  w .jav  a  2s  . c  o m
 * @return a JsonArray containing tweets
 * @throws TwitterException
 * @throws IOException
 */
public JsonArray getFeedData() throws TwitterException, IOException {

    Properties prop = new Properties();
    // try {
    //load a properties file
    prop.load(this.getClass().getResourceAsStream("twitter4j.properties"));

    //get the property value and print it out
    String consumerKey = prop.getProperty("oauth.consumerKey");
    String consumerSecret = prop.getProperty("oauth.consumerSecret");
    String accessToken = prop.getProperty("oauth.accessToken");
    String accessTokenSecret = prop.getProperty("oauth.accessTokenSecret");
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    Query query = new Query("glassfish");
    QueryResult result = twitter.search(query);

    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    for (Status status : result.getTweets()) {
        jsonArrayBuilder.add(Json.createObjectBuilder().add("text", status.getText()).add("created_at",
                status.getCreatedAt().toString()));

        System.out.println(
                "@" + status.getUser().getScreenName() + ":" + status.getText() + status.getCreatedAt());
    }

    return jsonArrayBuilder.build();
}

From source file:org.hubiquitus.hubotsdk.adapters.HTwitterAdapterOutbox.java

License:Open Source License

@Override
public void start() {

    log.info("Twitter adapter outbox '" + actor + "' starting...");

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setUseSSL(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(twitterAccessToken)
            .setOAuthAccessTokenSecret(twitterAccessTokenSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();

    log.info("Twitter adapter outbox '" + actor + "' started.");
}

From source file:org.jraf.irondad.handler.twitter.follow.TwitterFollowHandler.java

License:Open Source License

private static Twitter getTwitter(HandlerContext handlerContext) {
    Twitter res = (Twitter) handlerContext.get("twitter");
    if (res == null) {
        TwitterFollowHandlerConfig twitterFollowHandlerConfig = (TwitterFollowHandlerConfig) handlerContext
                .getHandlerConfig();//from w  w w . ja v  a2  s . c  om
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey(twitterFollowHandlerConfig.getOauthConsumerKey());
        configurationBuilder.setOAuthConsumerSecret(twitterFollowHandlerConfig.getOauthConsumerSecret());
        configurationBuilder.setOAuthAccessToken(twitterFollowHandlerConfig.getOauthAccessToken());
        configurationBuilder.setOAuthAccessTokenSecret(twitterFollowHandlerConfig.getOauthAccessTokenSecret());
        TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());
        res = twitterFactory.getInstance();

        handlerContext.put("twitter", res);
    }
    return res;
}

From source file:org.jraf.irondad.handler.twitter.links.TwitterLinksHandler.java

License:Open Source License

private static Twitter getTwitter(HandlerContext handlerContext) {
    Twitter res = (Twitter) handlerContext.get("twitter");
    if (res == null) {
        TwitterLinksHandlerConfig twitterLinksHandlerConfig = (TwitterLinksHandlerConfig) handlerContext
                .getHandlerConfig();/*from w  w w . j  a  v a  2s. c  o m*/
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey(twitterLinksHandlerConfig.getOauthConsumerKey());
        configurationBuilder.setOAuthConsumerSecret(twitterLinksHandlerConfig.getOauthConsumerSecret());
        configurationBuilder.setOAuthAccessToken(twitterLinksHandlerConfig.getOauthAccessToken());
        configurationBuilder.setOAuthAccessTokenSecret(twitterLinksHandlerConfig.getOauthAccessTokenSecret());
        TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());
        res = twitterFactory.getInstance();

        handlerContext.put("twitter", res);
    }
    return res;
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void requestAccessToken(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();// ww w  .  j  a v a 2s  . c o m

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg;
    String lCallbackURL = aToken.getString("callbackURL");
    try {
        if (!mCheckAuth(lResponse)) {
            mLog.error(lResponse.getString("msg"));
        } else {
            // get a new Twitter object for the user
            TwitterFactory lTwitterFactory = new TwitterFactory();
            Twitter lTwitter = lTwitterFactory.getInstance();
            lTwitter.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret());

            // pass callback URL to Twitter API if given
            RequestToken lReqToken = (lCallbackURL != null ? lTwitter.getOAuthRequestToken(lCallbackURL)
                    : lTwitter.getOAuthRequestToken());

            String lAuthenticationURL = lReqToken.getAuthenticationURL();
            String lAuthorizationURL = lReqToken.getAuthorizationURL();

            lResponse.setString("authenticationURL", lAuthenticationURL);
            lResponse.setString("authorizationURL", lAuthorizationURL);
            lMsg = "authenticationURL: " + lAuthenticationURL + ", authorizationURL: " + lAuthorizationURL;
            lResponse.setString("msg", lMsg);
            if (mLog.isInfoEnabled()) {
                mLog.info(lMsg);
            }

            aConnector.setVar(OAUTH_REQUEST_TOKEN, lReqToken);
            aConnector.setVar(TWITTER_VAR, lTwitter);
        }
    } catch (Exception lEx) {
        lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.keycloak.examples.broker.twitter.TwitterShowUserServlet.java

License:Apache License

@Override
protected void doGet(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    TwitterOAuthResponse twitterOAuthResponse = getTwitterOAuthResponse(request);
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey(this.identityProvider.getConfig().get("clientId"))
            .setOAuthConsumerSecret(this.identityProvider.getConfig().get("clientSecret"))
            .setOAuthAccessToken(twitterOAuthResponse.getToken())
            .setOAuthAccessTokenSecret(twitterOAuthResponse.getTokenSecret());

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {/*from w  w w  .j a  v a  2 s .c o  m*/
        User user = twitter.users().showUser(twitterOAuthResponse.getScreenName());

        response.setContentType(MediaType.APPLICATION_JSON);

        PrintWriter writer = response.getWriter();

        writer.println(new ObjectMapper().writeValueAsString(user));

        writer.flush();
    } catch (TwitterException e) {
        throw new RuntimeException("Could not load social profile.", e);
    }
}

From source file:org.loklak.harvester.TwitterAPI.java

License:Open Source License

public static JSONObject getUser(String screen_name, boolean forceReload) throws TwitterException, IOException {
    if (!forceReload) {
        JsonFactory mapcapsule = DAO.user_dump.get("screen_name", screen_name);
        if (mapcapsule == null)
            mapcapsule = DAO.user_dump.get("id_str", screen_name);
        if (mapcapsule != null) {
            JSONObject json = mapcapsule.getJSON();
            if (json.length() > 0) {
                // check if the entry is maybe outdated, i.e. if it is empty or too old
                try {
                    Date d = DAO.user_dump.parseDate(json);
                    if (d.getTime() + DateParser.DAY_MILLIS > System.currentTimeMillis())
                        return json;
                } catch (ParseException e) {
                    return json;
                }//from w  w  w. j a  v  a2s . c om
            }
        }
    }
    TwitterFactory tf = getUserTwitterFactory(screen_name);
    if (tf == null)
        tf = getAppTwitterFactory();
    if (tf == null)
        return new JSONObject();
    Twitter twitter = tf.getInstance();
    User user = twitter.showUser(screen_name);
    RateLimitStatus rateLimitStatus = user.getRateLimitStatus();
    getUserResetTime = System.currentTimeMillis() + rateLimitStatus.getSecondsUntilReset() * 1000;
    getUserRemaining = rateLimitStatus.getRemaining();
    JSONObject json = user2json(user);
    enrichLocation(json);
    DAO.user_dump.putUnique(json);
    return json;
}

From source file:org.loklak.harvester.TwitterAPI.java

License:Open Source License

public static JSONObject getNetworkerNames(final String screen_name, final int max_count,
        final Networker networkRelation) throws IOException, TwitterException {
    if (max_count == 0)
        return new JSONObject();
    boolean complete = true;
    Set<Number> networkingIDs = new LinkedHashSet<>();
    Set<Number> unnetworkingIDs = new LinkedHashSet<>();
    JsonFactory mapcapsule = (networkRelation == Networker.FOLLOWERS ? DAO.followers_dump : DAO.following_dump)
            .get("screen_name", screen_name);
    if (mapcapsule == null) {
        JsonDataset ds = networkRelation == Networker.FOLLOWERS ? DAO.followers_dump : DAO.following_dump;
        mapcapsule = ds.get("screen_name", screen_name);
    }/*from   w  ww.  j  a v  a2  s  .  c  o  m*/

    if (mapcapsule != null) {
        JSONObject json = mapcapsule.getJSON();

        // check date and completeness
        complete = json.has("complete") ? (Boolean) json.get("complete") : Boolean.FALSE;
        String retrieval_date_string = json.has("retrieval_date") ? (String) json.get("retrieval_date") : null;
        DateTime retrieval_date = retrieval_date_string == null ? null
                : AbstractObjectEntry.utcFormatter.parseDateTime(retrieval_date_string);
        if (complete && System.currentTimeMillis() - retrieval_date.getMillis() < DateParser.DAY_MILLIS)
            return json;

        // load networking ids for incomplete retrievals (untested)
        String nr = networkRelation == Networker.FOLLOWERS ? "follower" : "following";
        if (json.has(nr)) {
            JSONArray fro = json.getJSONArray(nr);
            for (Object f : fro)
                networkingIDs.add((Number) f);
        }
    }
    TwitterFactory tf = getUserTwitterFactory(screen_name);
    if (tf == null)
        tf = getAppTwitterFactory();
    if (tf == null)
        return new JSONObject();
    Twitter twitter = tf.getInstance();
    long cursor = -1;
    collect: while (cursor != 0) {
        try {
            IDs ids = networkRelation == Networker.FOLLOWERS ? twitter.getFollowersIDs(screen_name, cursor)
                    : twitter.getFriendsIDs(screen_name, cursor);
            RateLimitStatus rateStatus = ids.getRateLimitStatus();
            if (networkRelation == Networker.FOLLOWERS) {
                getFollowerIdRemaining = rateStatus.getRemaining();
                getFollowerIdResetTime = System.currentTimeMillis() + rateStatus.getSecondsUntilReset() * 1000;
            } else {
                getFollowingIdRemaining = rateStatus.getRemaining();
                getFollowingIdResetTime = System.currentTimeMillis() + rateStatus.getSecondsUntilReset() * 1000;
            }
            //System.out.println("got: " + ids.getIDs().length + " ids");
            //System.out.println("Rate Status: " + rateStatus.toString() + "; time=" + System.currentTimeMillis());
            boolean dd = false;
            for (long id : ids.getIDs()) {
                if (networkingIDs.contains(id))
                    dd = true; // don't break loop here
                networkingIDs.add(id);
            }
            if (dd)
                break collect; // this is complete!
            if (rateStatus.getRemaining() == 0) {
                complete = false;
                break collect;
            }
            if (networkingIDs.size() >= Math.min(10000, max_count >= 0 ? max_count : 10000)) {
                complete = false;
                break collect;
            }
            cursor = ids.getNextCursor();
        } catch (TwitterException e) {
            complete = false;
            break collect;
        }
    }
    // create result
    JSONObject json = new JSONObject(true);
    json.put("screen_name", screen_name);
    json.put("retrieval_date", AbstractObjectEntry.utcFormatter.print(System.currentTimeMillis()));
    json.put("complete", complete);
    Map<String, Number> networking = getScreenName(networkingIDs, max_count, true);
    Map<String, Number> unnetworking = getScreenName(unnetworkingIDs, max_count, true);
    if (networkRelation == Networker.FOLLOWERS) {
        json.put("followers_count", networking.size());
        json.put("unfollowers_count", unnetworking.size());
        json.put("followers_names", networking);
        json.put("unfollowers_names", unnetworking);
        if (complete)
            DAO.followers_dump.putUnique(json); // currently we write only complete data sets. In the future the update of datasets shall be supported
    } else {
        json.put("following_count", networking.size());
        json.put("unfollowing_count", unnetworking.size());
        json.put("following_names", networking);
        json.put("unfollowing_names", unnetworking);
        if (complete)
            DAO.following_dump.putUnique(json);
    }
    return json;
}

From source file:org.loklak.harvester.TwitterAPI.java

License:Open Source License

/**
 * search for twitter user names by a given set of user id's
 * @param id_strs/*from w ww.java 2 s  .  co m*/
 * @param lookupLocalUsersByUserId if this is true and successful, the resulting names may contain users without user info in the user dump
 * @return
 * @throws IOException
 * @throws TwitterException 
 */
public static Map<String, Number> getScreenName(Set<Number> id_strs, final int maxFollowers,
        boolean lookupLocalUsersByUserId) throws IOException, TwitterException {
    // we have several sources to get this mapping:
    // - 1st / fastest: mapping from DAO.twitter_user_dump
    // - 2nd / fast   : mapping from DAO.searchLocalUserByUserId(user_id)
    // - 3rd / slow   : from twitter API with twitter.lookupUsers(String[] user_id)
    // first we check all fast solutions until trying the twitter api
    Map<String, Number> r = new HashMap<>();
    Set<Number> id4api = new HashSet<>();
    for (Number id_str : id_strs) {
        if (r.size() >= maxFollowers)
            break;
        JsonFactory mapcapsule = DAO.user_dump.get("id_str", id_str.toString());
        if (mapcapsule != null) {
            JSONObject map = mapcapsule.getJSON();
            String screen_name = map.has("screen_name") ? (String) map.get("screen_name") : null;
            if (screen_name != null) {
                r.put(screen_name, id_str);
                continue;
            }
        }
        if (lookupLocalUsersByUserId) {
            UserEntry ue = DAO.searchLocalUserByUserId(id_str.toString());
            if (ue != null) {
                String screen_name = ue.getScreenName();
                if (screen_name != null) {
                    r.put(screen_name, id_str);
                    continue;
                }
            }
        }
        id4api.add(id_str);
    }

    while (id4api.size() > 100 && id4api.size() + r.size() > maxFollowers)
        id4api.remove(id4api.iterator().next());

    // resolve the remaining user_ids from the twitter api
    if (r.size() < maxFollowers && id4api.size() > 0) {
        TwitterFactory tf = getAppTwitterFactory();
        if (tf == null)
            return new HashMap<>();
        Twitter twitter = tf.getInstance();
        collect: while (id4api.size() > 0) {
            // construct a query term with at most 100 id's
            int chunksize = Math.min(100, id4api.size());
            long[] u = new long[chunksize];
            Iterator<Number> ni = id4api.iterator();
            for (int i = 0; i < chunksize; i++) {
                u[i] = ni.next().longValue();
            }
            try {
                ResponseList<User> users = twitter.lookupUsers(u);
                for (User usr : users) {
                    JSONObject map = user2json(usr);
                    enrichLocation(map);
                    DAO.user_dump.putUnique(map);
                    r.put(usr.getScreenName(), usr.getId());
                    id4api.remove(usr.getId());
                }
            } catch (TwitterException e) {
                if (r.size() == 0)
                    throw e;
                break collect;
            }
        }
    }
    return r;
}