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:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java

License:Open Source License

/**
 * Starts a command line authentication with yammer to get the needed access
 * token.//w ww . j  av  a2  s.  co  m
 */
private void startCommandLineAuthentication() {

    if (!source.isPropertyTrue(TwitterProperties.ALLOW_COMMAND_LINE_AUTHENTICATION)) {
        return;
    }

    // get property values from configuration
    String consumerKey = source.getPropertyValue(TwitterProperties.CONSUMER_KEY_PROPERTY);
    String consumerSecret = source.getPropertyValue(TwitterProperties.CONSUMER_SECRET_PROPERTY);

    // check properties
    if (consumerKey == null || consumerKey.isEmpty()) {
        log("A valid consumer key is needed in the configuration specified by "
                + TwitterProperties.CONSUMER_KEY_PROPERTY, LogService.LOG_WARNING);
        return;
    } else if (consumerSecret == null || consumerSecret.isEmpty()) {
        log("A valid consumer secret is needed in the configuration specified by "
                + TwitterProperties.CONSUMER_SECRET_PROPERTY, LogService.LOG_WARNING);
        return;
    }

    log("Starting command line authentication.", LogService.LOG_INFO);

    // Access Token not contained in properties
    Twitter twitter = new TwitterFactory().getInstance();

    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken;

    // create new request token
    try {
        requestToken = twitter.getOAuthRequestToken();
    } catch (TwitterException e) {
        log("Unable to get request token from Twitter. Please check your Consumer Key and Secret.",
                LogService.LOG_ERROR);
        return;
    }

    System.out.println("Request token: " + requestToken.getToken());
    System.out.println("Token secret: " + requestToken.getTokenSecret());

    String authorizationURL = requestToken.getAuthorizationURL();

    // wait for user confirming the request
    System.out.println("Now visit:\n" + authorizationURL + "\n... and grant this app authorization");
    System.out.println("Enter the PIN code and hit ENTER when you're done:");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String pin;
    try {
        pin = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    AccessToken accessToken = null;
    try {
        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
    } catch (Exception e) {
        accessToken = null;
    }

    if (accessToken == null) {
        log("Got no Twitter OAuth Access Token for given Request and Pin!", LogService.LOG_ERROR);
        return;
    }

    System.out.println("Access token: " + accessToken.getToken());
    System.out.println("Token secret: " + accessToken.getTokenSecret());
}

From source file:org.tomochika1985.twitter.AppSession.java

License:Apache License

public boolean login(String pin, Response response) {
    try {//from  w  w w.j  a  va  2 s  .com
        if (requestToken == null) {
            throw new IllegalStateException("requestToken is missing.");
        }

        Twitter client = new TwitterClient();
        client.setOAuthConsumer(consumerKey, consumerSecret);

        AccessToken accessToken = client.getOAuthAccessToken(requestToken, pin);
        client.setOAuthAccessToken(accessToken);
        this.twitterSession = client;
        dirty();
        return true;
    } catch (TwitterException ex) {
        LOGGER.error("Can not setup OAuth Access Token to Twitter object.", ex);
        return false;
    }
}

From source file:org.tomochika1985.twitter.AppSession.java

License:Apache License

public Twitter getTwitterSession(Request request) throws NeedAuthenticationException {
    if (request == null)
        throw new IllegalArgumentException("'request' is missing");

    //?Twitter?????????
    if (twitterSession != null)
        return twitterSession;

    // AccessTokenDB?????????????AccessToken??
    // Twitter????????
    // ????AccessToken???????????OAuth??

    // OAuth?RequestToken???
    Twitter client = new TwitterClient();
    client.setOAuthConsumer(consumerKey, consumerSecret);

    RequestToken token = null;//from w w  w .  ja va  2 s.co  m
    try {
        token = client.getOAuthRequestToken(RequestUtils.toAbsolutePath("login", "/"));
    } catch (TwitterException ex) {
        throw new RuntimeException(ex);
    }

    this.requestToken = token;
    this.lastAccessUrl = request.getClientUrl().toString();
    dirty();

    throw new RedirectToUrlException(token.getAuthorizationURL());
}

From source file:org.twitter.oauth.java

public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("SjLUa1Pwrs81nIAGiR4f1l4I7", "ISAXBmzqzYLKWQXAaOe09j34APvVOyxahHghLBSvvR0Psnhozl");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/* ww w.  ja v  a 2s  . c om*/
    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.
    storeAccessToken((int) 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:org.tynamo.examples.federatedaccounts.pages.Index.java

License:Apache License

@RequiresPermissions("twitter")
Block onActionFromListTweets() throws TwitterException {
    OauthAccessToken accessToken = securityService.getSubject().getPrincipals()
            .oneByType(TwitterAccessToken.class);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthConsumer(oauthClientId, oauthClientSecret);
    twitter.setOAuthAccessToken((AccessToken) accessToken.getCredentials());
    tweets = twitter.getHomeTimeline();// w  w  w .j av a 2s  . c om
    return tweetResults.getBody();

}

From source file:org.wso2.carbon.identity.authenticator.twitter.TwitterAuthenticator.java

License:Open Source License

/**
 * Initiate the authentication request/*from ww  w  .j  av a  2 s  .c  o m*/
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
    String apiKey = authenticatorProperties.get(TwitterAuthenticatorConstants.TWITTER_API_KEY);
    String apiSecret = authenticatorProperties.get(TwitterAuthenticatorConstants.TWITTER_API_SECRET);
    configurationBuilder.setIncludeEmailEnabled(true);
    Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
    twitter.setOAuthConsumer(apiKey, apiSecret);
    try {
        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
                context.getCallerSessionKey(), context.getContextIdentifier());
        String callbackURL = getCallbackUrl(authenticatorProperties);
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        String subStr = queryParams
                .substring(queryParams.indexOf(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="));
        String sessionDK = subStr
                .substring(subStr.indexOf(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="),
                        subStr.indexOf("&"))
                .replace((TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="), "");
        request.getSession().setAttribute(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY, sessionDK);
        request.getSession().setAttribute(TwitterAuthenticatorConstants.TWITTER_REQUEST_TOKEN, requestToken);
        request.getSession().setAttribute(TwitterAuthenticatorConstants.AUTHENTICATOR_NAME.toLowerCase(),
                twitter);
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        log.error("Exception while sending to the Twitter login page.", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    } catch (IOException e) {
        log.error("Exception while sending to the Twitter login page.", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:org.wso2.fasttrack.project.roadlk.rest.DatasetGenerator.java

License:Open Source License

/**
 * @param consumerKey//from  ww  w.  ja va 2s .  co  m
 *            Twitter Consumer Key (API Key)
 * @param consumerSecret
 *            Twitter Consumer Secret (API Secret)
 * @param accessToken
 *            Twitter Access Token
 * @param accessTokenSecret
 *            Twitter Access Token Secret
 * @param pageLimit
 *            Maximum pages to be retrieved
 * @throws IOException
 * @throws TwitterException
 */
@SuppressWarnings("resource")
public void generateDataset(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret, int pageLimit) throws IOException, TwitterException {
    // Twitter object of Twitter4J library
    Twitter twitter = TwitterFactory.getSingleton();

    // Twitter API authentication
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    PrintWriter printWriter = null;

    try {
        printWriter = new PrintWriter(new BufferedWriter(new FileWriter("dataset.txt", true)));
    } catch (IOException e) {
        throw new IOException(e);
    }

    LOGGER.debug("Twitter feed extraction started.");

    for (int i = 1; i < pageLimit; i = i + 1) {

        Paging paging = new Paging(i, 100);
        ResponseList<Status> statuses = null;

        try {
            statuses = twitter.getUserTimeline("road_lk", paging);
        } catch (TwitterException e) {
            //LOGGER.error("TwitterException occurred." + e.getMessage());
            throw new TwitterException(e);
        }

        for (Status status : statuses) {
            printWriter.println(status.getCreatedAt() + ": " + status.getText());
        }
    }
    printWriter.close();
    LOGGER.debug("Twitter feed extraction completed.");
}

From source file:org.yukung.following2ldr.command.impl.FindFeedUrlCommand.java

License:Apache License

@Override
public void run() throws Throwable {
    // Twitter??//from w w w.java 2s .c o m
    long start = System.currentTimeMillis();
    String consumerKey = config.getProperty(Constants.CONSUMER_KEY);
    String consumerSecret = config.getProperty(Constants.CONSUMER_SECRET);
    String userName = params.get(0);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    String authorizationURL = requestToken.getAuthorizationURL();
    System.out.println(":" + authorizationURL);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter the PIN:");
    String pin = br.readLine();
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);
    twitter.setOAuthAccessToken(accessToken);
    long cursor = -1L;
    IDs friendIDs;
    List<Long> iDsList = new ArrayList<Long>(5000);
    do {
        friendIDs = twitter.getFriendsIDs(userName, cursor);
        long[] iDs = friendIDs.getIDs();
        for (long iD : iDs) {
            iDsList.add(iD);
        }
        cursor = friendIDs.getNextCursor();
    } while (friendIDs.hasNext());
    List<long[]> list = new ArrayList<long[]>();
    int offset = 0;
    long[] tmp = new long[100];
    for (Long id : iDsList) {
        if (offset < 100) {
            tmp[offset] = id;
            offset++;
        } else {
            list.add(tmp);
            offset = 0;
            tmp = new long[100];
        }
    }
    list.add(tmp);
    List<URL> urlList = new ArrayList<URL>();
    for (long[] array : list) {
        ResponseList<User> lookupUsers = twitter.lookupUsers(array);
        for (User user : lookupUsers) {
            log.info("URL:" + user.getURL());
            urlList.add(user.getURL());
        }
    }
    String path = "C:\\Users\\ikeda_yusuke\\Documents\\sandbox\\java\\data\\" + userName + ".txt";
    FileWriter writer = new FileWriter(path);
    BufferedWriter out = new BufferedWriter(writer);
    //      PrintWriter pw = new PrintWriter(writer);
    for (URL url : urlList) {
        if (url != null) {
            out.write(url.toString() + "\n");
        }
    }
    out.flush();
    out.close();
    long end = System.currentTimeMillis();
    log.info("?:" + (end - start) + " ms");

    // ??IDor??
    // Twitter API??????ID?
    // ?????ID?URL100???
    // ??URL?

}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

public static ArrayList<Item> getFluxFromSearch(String search, String sourceUri) {
    ArrayList<Item> result = new ArrayList<Item>();
    try {/*from  w  ww .ja v a 2s.  com*/

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"),
                Config.getVar("Twitter-OAuth-customerKey"));
        twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"),
                Config.getVar("Twitter-OAuth-accessKey")));

        Query query = new Query(search);
        QueryResult items = twitter.search(query);
        for (Status r : items.getTweets()) {
            result.add(TwitterApi.getItemFromStatus(r, sourceUri));
        }

        return result;
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterApi.class.getName()).log(Level.WARNING, null, ex);
        return result;
    }
}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

public static ArrayList<Item> getFluxFromUser(String user, String sourceUri) {
    ArrayList<Item> result = new ArrayList<Item>();
    try {/*from w w  w. j a  va 2s  .  c  o  m*/

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"),
                Config.getVar("Twitter-OAuth-customerKey"));
        twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"),
                Config.getVar("Twitter-OAuth-accessKey")));

        List<Status> statusess = twitter.getUserTimeline(user);
        for (Status r : statusess) {
            result.add(TwitterApi.getItemFromStatus(r, sourceUri));
        }

        return result;
    } catch (TwitterException ex) {
        logger.warn(ex.getErrorMessage());
        return result;
    }
}