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:net.chrissearle.flickrvote.service.cli.TwitterOAuthCLI.java

License:Apache License

public void authorize(String key, String secret) throws TwitterException, IOException {
    Twitter twitter = new TwitterFactory().getInstance();

    twitter.setOAuthConsumer(key, secret);

    RequestToken requestToken = twitter.getOAuthRequestToken();

    AccessToken accessToken = null;/*from  w w w.  j  av  a2 s .  com*/

    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) or just hit enter.[PIN]:");

        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }

            System.out.println("Token: " + accessToken.getToken());
            System.out.println("TokenSecret: " + accessToken.getTokenSecret());
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
}

From source file:net.firejack.platform.web.security.twitter.BaseTwitterAuthenticationProcessor.java

License:Apache License

protected Twitter populateTwitterService() {
    if (!isEnable())
        throw new IllegalStateException("Service disabled.");

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(getTwitterConsumerKey(), getTwitterConsumerSecret());
    return twitter;
}

From source file:onl.area51.a51li.twitter.TwitterAuth.java

License:Apache License

public static void main(String args[]) throws Exception {
    final String consumerKey = args[0];
    final String consumerSecret = args[1];

    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*ww  w.  j  av a 2 s .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(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.anc.lapps.datasource.twitter.TwitterDatasource.java

/**
 * Entry point for a Lappsgrid service.//from w  w w  .  ja va2  s . co m
 * <p>
 * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object
 * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container}
 * payload.
 * <p>
 * Errors and exceptions that occur during processing should be wrapped in a {@code Data}
 * object with the discriminator set to http://vocab.lappsgrid.org/ns/error
 * <p>
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br />
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br />
 *
 * @param input A JSON string representing a Data object
 * @return A JSON string containing a Data object with a Container payload.
 */
@Override
public String execute(String input) {
    Data<String> data = Serializer.parse(input, Data.class);
    String discriminator = data.getDiscriminator();

    // Return ERRORS back
    if (Discriminators.Uri.ERROR.equals(discriminator)) {
        return input;
    }

    // Generate an error if the used discriminator is wrong
    if (!Discriminators.Uri.GET.equals(discriminator)) {
        return generateError(
                "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator);
    }

    Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false)
            .build();

    // Authentication using saved keys
    Twitter twitter = new TwitterFactory(config).getInstance();
    String key = readProperty(KEY_PROPERTY);
    if (key == null) {
        return generateError("The Twitter Consumer Key property has not been set.");
    }

    String secret = readProperty(SECRET_PROPERTY);
    if (secret == null) {
        return generateError("The Twitter Consumer Secret property has not been set.");
    }

    twitter.setOAuthConsumer(key, secret);

    try {
        twitter.getOAuth2Token();
    } catch (TwitterException te) {
        String errorData = generateError(te.getMessage());
        logger.error(errorData);
        return errorData;
    }

    // Get query String from data payload
    Query query = new Query(data.getPayload());

    // Set the type to Popular or Recent if specified
    // Results will be Mixed by default.
    if (data.getParameter("type") == "Popular")
        query.setResultType(Query.POPULAR);
    if (data.getParameter("type") == "Recent")
        query.setResultType(Query.RECENT);

    // Get lang string
    String langCode = (String) data.getParameter("lang");

    // Verify the validity of the language code and add it to the query if it's valid
    if (validateLangCode(langCode))
        query.setLang(langCode);

    // Get date strings
    String sinceString = (String) data.getParameter("since");
    String untilString = (String) data.getParameter("until");

    // Verify the format of the date strings and set the parameters to query if correctly given
    if (validateDateFormat(untilString))
        query.setUntil(untilString);
    if (validateDateFormat(sinceString))
        query.setSince(sinceString);

    // Get GeoLocation
    if (data.getParameter("address") != null) {
        String address = (String) data.getParameter("address");
        double radius = (double) data.getParameter("radius");
        if (radius <= 0)
            radius = 10;
        Query.Unit unit = Query.MILES;
        if (data.getParameter("unit") == "km")
            unit = Query.KILOMETERS;
        GeoLocation geoLocation;
        try {
            double[] coordinates = getGeocode(address);
            geoLocation = new GeoLocation(coordinates[0], coordinates[1]);
        } catch (Exception e) {
            String errorData = generateError(e.getMessage());
            logger.error(errorData);
            return errorData;
        }

        query.geoCode(geoLocation, radius, String.valueOf(unit));

    }

    // Get the number of tweets from count parameter, and set it to default = 15 if not specified
    int numberOfTweets;
    try {
        numberOfTweets = (int) data.getParameter("count");
    } catch (NullPointerException e) {
        numberOfTweets = 15;
    }

    // Generate an ArrayList of the wanted number of tweets, and handle possible errors.
    // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed
    ArrayList<Status> allTweets;
    Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter);
    String tweetsDataDisc = tweetsData.getDiscriminator();
    if (Discriminators.Uri.ERROR.equals(tweetsDataDisc))
        return tweetsData.asPrettyJson();

    else {
        allTweets = (ArrayList<Status>) tweetsData.getPayload();
    }

    // Initialize StringBuilder to hold the final string
    StringBuilder builder = new StringBuilder();

    // Append each Status (each tweet) to the initialized builder
    for (Status status : allTweets) {
        String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : "
                + status.getText() + "\n";
        builder.append(single);
    }

    // Output results
    Container container = new Container();
    container.setText(builder.toString());
    Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container);
    return output.asPrettyJson();
}

From source file:org.celstec.arlearn2.oauth.OauthTwitterWorker.java

License:Open Source License

public void redirectToTwitterForAuthentication(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(client_id, client_secret);
    RequestToken token = null;/*  w ww  .  ja  v a 2  s.  c o  m*/
    try {
        token = twitter.getOAuthRequestToken(redirect_uri);
        req.getSession().setAttribute("requestToken", token);
        String loginUrl = token.getAuthenticationURL() + "&force_login=true";
        resp.sendRedirect(loginUrl);
    } catch (TwitterException e) {
        e.printStackTrace();
        log.log(Level.SEVERE, e.getErrorMessage(), e);
    }
}

From source file:org.celstec.arlearn2.oauth.OauthTwitterWorker.java

License:Open Source License

public String afterSuccesfullAuthentication(HttpServletRequest request) {
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken token = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    twitter.setOAuthConsumer(client_id, client_secret);
    try {/*  www.  j  a  va  2  s .com*/
        AccessToken accessToken = twitter.getOAuthAccessToken(token, verifier);
        User user = twitter.verifyCredentials();
        AccountJDO account = AccountManager.addAccount("" + user.getId(), AccountJDO.TWITTERCLIENT, "", "", "",
                user.getName(), user.getProfileImageURL(), false);
        UserLoggedInManager.submitOauthUser(account.getUniqueId(), accessToken.getToken());
        return accessToken.getToken();
    } catch (TwitterException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}

From source file:org.encuestame.social.api.templates.TwitterAPITemplate.java

License:Apache License

/**
 * Get Twitter Ping./* w  w w  .  ja  v  a 2s  .  c o m*/
 * @param consumerKey consumer key
 * @param consumerSecret consumer secret
 * @return {@link RequestToken}
 * @throws TwitterException exception
 */
public RequestToken getTwitterPing() throws TwitterException {
    if (consumerKey == null) {
        throw new IllegalArgumentException("Consumer key is missing");
    }
    if (consumerSecret == null) {
        throw new IllegalArgumentException("Consumer secret is missing");
    }
    final Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    return twitter.getOAuthRequestToken();
}

From source file:org.eventjuggler.services.security.authc.social.twitter.TwitterAuthenticationMechanism.java

License:Open Source License

@Override
protected Principal doAuthenticate(UserCredential credential, AuthenticationResult result)
        throws AuthenticationException {
    TwitterCredential oAuthCredential = (TwitterCredential) credential;

    HttpServletRequest request = oAuthCredential.getRequest();
    HttpServletResponse response = oAuthCredential.getResponse();
    HttpSession session = request.getSession();

    Principal principal = null;//from w ww.j a v  a2 s .  c om

    provideSecrets(oAuthCredential);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(clientID, clientSecret);

    //See if we are a callback
    RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    String verifier = request.getParameter("oauth_verifier");
    if (requestToken != null && verifier != null) {
        try {
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            session.setAttribute("accessToken", accessToken);
            session.removeAttribute("requestToken");
        } catch (TwitterException e) {
            throw new AuthenticationException(e);
        }

        try {
            principal = new TwitterPrincipal(twitter.verifyCredentials());
            checkUserInStore((TwitterPrincipal) principal);
        } catch (TwitterException e) {
            throw new AuthenticationException(e);
        }
        return principal;
    }
    try {
        requestToken = twitter.getOAuthRequestToken(returnURL);
        session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (Exception e) {
        throw new AuthenticationException(e);
    }
    return principal;
}

From source file:org.examproject.tweet.service.SimpleTweetService.java

License:Apache License

private Twitter getTwitter() {
    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer(authValue.getConsumerKey(), authValue.getConsumerSecret());
    twitter.setOAuthAccessToken(new AccessToken(authValue.getOauthToken(), authValue.getOauthTokenSecret()));
    return twitter;
}

From source file:org.exoplatform.extensions.twitter.services.TwitterService.java

License:Open Source License

public Twitter getTwitter() {
    Twitter twitter = null;
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, secretKey);
    return twitter;
}