Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory(String configTreePath) 

Source Link

Document

Creates a TwitterFactory with a specified config tree

Usage

From source file:org.gameontext.auth.twitter.TwitterCallback.java

License:Apache License

/**
 * Method that performs introspection on an AUTH string, and returns data as
 * a String->String hashmap.//from   ww w  .  java  2  s .c  om
 *
 * @param auth
 *            the authstring to query, as built by an auth impl.
 * @return the data from the introspect, in a map.
 * @throws IOException
 *             if anything goes wrong.
 */
public Map<String, String> introspectAuth(String token, String tokensecret) throws IOException {
    Map<String, String> results = new HashMap<String, String>();

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret).setOAuthAccessToken(token)
            .setOAuthAccessTokenSecret(tokensecret).setIncludeEmailEnabled(true).setJSONStoreEnabled(true);

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

    try {
        // ask twitter to verify the token & tokensecret from the auth
        // string
        // if invalid, it'll throw a TwitterException
        User verified = twitter.verifyCredentials();

        // if it's valid, lets grab a little more info about the user.
        String name = verified.getName();
        String email = verified.getEmail();

        results.put("valid", "true");
        results.put("id", "twitter:" + twitter.getId());
        results.put("name", name);
        results.put("email", email);

    } catch (TwitterException e) {
        results.put("valid", "false");
    }

    return results;
}

From source file:org.gatein.security.oauth.twitter.TwitterProcessorImpl.java

License:Open Source License

public TwitterProcessorImpl(ExoContainerContext context, InitParams params) {
    this.clientID = params.getValueParam("clientId").getValue();
    this.clientSecret = params.getValueParam("clientSecret").getValue();
    String redirectURLParam = params.getValueParam("redirectURL").getValue();

    if (clientID == null || clientID.length() == 0 || clientID.trim().equals("<<to be replaced>>")) {
        throw new IllegalArgumentException("Property 'clientId' needs to be provided. The value should be "
                + "clientId of your Twitter application");
    }//from w  w w .  j a va  2s. c o m

    if (clientSecret == null || clientSecret.length() == 0
            || clientSecret.trim().equals("<<to be replaced>>")) {
        throw new IllegalArgumentException("Property 'clientSecret' needs to be provided. The value should be "
                + "clientSecret of your Twitter application");
    }

    if (redirectURLParam == null || redirectURLParam.length() == 0) {
        this.redirectURL = "http://localhost:8080/" + context.getName()
                + OAuthConstants.TWITTER_AUTHENTICATION_URL_PATH;
    } else {
        this.redirectURL = redirectURLParam.replaceAll("@@portal.container.name@@", context.getName());
    }

    this.chunkLength = OAuthPersistenceUtils.getChunkLength(params);

    if (log.isDebugEnabled()) {
        log.debug("configuration: clientId=" + clientID + ", clientSecret=" + clientSecret + ", redirectURL="
                + redirectURL + ", chunkLength=" + chunkLength);
    }
    // Create 'generic' twitterFactory for user authentication to GateIn
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(clientID).setOAuthConsumerSecret(clientSecret);
    twitterFactory = new TwitterFactory(builder.build());
}

From source file:org.gatein.security.oauth.twitter.TwitterProcessorImpl.java

License:Open Source License

@Override
public Twitter getAuthorizedTwitterInstance(TwitterAccessTokenContext accessTokenContext) {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(clientID).setOAuthConsumerSecret(clientSecret);

    // Now add accessToken properties to builder
    builder.setOAuthAccessToken(accessTokenContext.getAccessToken());
    builder.setOAuthAccessTokenSecret(accessTokenContext.getAccessTokenSecret());

    // Return twitter instance with successfully established accessToken
    return new TwitterFactory(builder.build()).getInstance();
}

From source file:org.getlantern.firetweet.util.Utils.java

License:Open Source License

@Nullable
public static Twitter getTwitterInstance(final Context context, final long accountId,
        final boolean includeEntities, final boolean includeRetweets) {
    if (context == null)
        return null;
    final FiretweetApplication app = FiretweetApplication.getInstance(context);
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int connection_timeout = prefs.getInt(KEY_CONNECTION_TIMEOUT, 10) * 1000;
    final boolean enableGzip = prefs.getBoolean(KEY_GZIP_COMPRESSING, true);
    final boolean ignoreSslError = prefs.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enableProxy = prefs.getBoolean(KEY_ENABLE_PROXY, false);
    // Here I use old consumer key/secret because it's default key for older
    // versions/*from   w  w w . j  a  va2 s  .  c  o m*/
    final ParcelableCredentials credentials = ParcelableCredentials.getCredentials(context, accountId);
    if (credentials == null)
        return null;
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHostAddressResolverFactory(new FiretweetHostResolverFactory(app));
    cb.setHttpClientFactory(new OkHttpClientFactory(context));
    cb.setHttpConnectionTimeout(connection_timeout);
    cb.setGZIPEnabled(enableGzip);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeCards(true);
    cb.setCardsPlatform("Android-12");
    //            cb.setModelVersion(7);
    if (enableProxy) {
        final String proxy_host = prefs.getString(KEY_PROXY_HOST, null);
        final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1"));
        if (!isEmpty(proxy_host) && proxy_port > 0) {
            cb.setHttpProxyHost(proxy_host);
            cb.setHttpProxyPort(proxy_port);
        }
    }
    final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
    final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
    final String apiUrlFormat = credentials.api_url_format;
    final String consumerKey = trim(credentials.consumer_key);
    final String consumerSecret = trim(credentials.consumer_secret);
    final boolean sameOAuthSigningUrl = credentials.same_oauth_signing_url;
    final boolean noVersionSuffix = credentials.no_version_suffix;
    if (!isEmpty(apiUrlFormat)) {
        final String versionSuffix = noVersionSuffix ? null : "/1.1/";
        cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix));
        cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
        cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix));
        cb.setOAuthAuthorizationURL(getApiUrl(apiUrlFormat, null, null));
        if (!sameOAuthSigningUrl) {
            cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
            cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
            cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
        }
    }
    if (TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret)) {
        setMockOfficialUserAgent(context, cb);
    } else {
        setUserAgent(context, cb);
    }

    cb.setIncludeEntitiesEnabled(includeEntities);
    cb.setIncludeRTsEnabled(includeRetweets);
    cb.setIncludeReplyCountEnabled(true);
    cb.setIncludeDescendentReplyCountEnabled(true);
    switch (credentials.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
            cb.setOAuthConsumerKey(consumerKey);
            cb.setOAuthConsumerSecret(consumerSecret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        }
        final String token = credentials.oauth_token;
        final String tokenSecret = credentials.oauth_token_secret;
        if (isEmpty(token) || isEmpty(tokenSecret))
            return null;
        return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret));
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = credentials.screen_name;
        final String username = credentials.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = credentials.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password));
    }
    case Accounts.AUTH_TYPE_TWIP_O_MODE: {
        return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization());
    }
    default: {
        return null;
    }
    }
}

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 ww. j  av  a  2 s.  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();//  ww w.jav  a2  s  . c o m

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

From source file:org.jclouds.demo.tweetstore.config.GuiceServletConfig.java

License:Apache License

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    BlobStoreContextFactory blobStoreContextFactory = new BlobStoreContextFactory();

    Properties props = loadJCloudsProperties(servletContextEvent);

    Set<Module> modules = ImmutableSet.<Module>of();
    // shared across all blobstores and used to retrieve tweets
    try {//  w w  w. j  ava  2  s  . c o  m
        Configuration twitterConf = new ConfigurationBuilder().setUser(props.getProperty("twitter.identity"))
                .setPassword(props.getProperty("twitter.credential")).build();
        twitterClient = new TwitterFactory(twitterConf).getInstance();
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                "properties for twitter not configured properly in " + props.toString(), e);
    }
    // common namespace for storing tweets
    container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER);

    // instantiate and store references to all blobstores by provider name
    providerTypeToBlobStoreMap = Maps.newHashMap();
    for (String hint : Splitter.on(',')
            .split(checkNotNull(props.getProperty(PROPERTY_BLOBSTORE_CONTEXTS), PROPERTY_BLOBSTORE_CONTEXTS))) {
        providerTypeToBlobStoreMap.put(hint, blobStoreContextFactory.createContext(hint, modules, props));
    }

    // get a queue for submitting store tweet requests
    queue = TaskQueue.builder().name("twitter").period(MINUTES).build();
    Factory taskFactory = HttpRequestTask.factory(props, "twitter");
    // submit a job to store tweets for each configured blobstore
    for (String name : providerTypeToBlobStoreMap.keySet()) {
        queue.add(taskFactory.create(HttpRequest.builder()
                .endpoint(URI.create("http://localhost:8080"
                        + servletContextEvent.getServletContext().getContextPath() + "/store/do"))
                .headers(ImmutableMultimap.of("context", name, "X-RUN@cloud-QueueName", "twitter"))
                .method("GET").build()));
    }

    super.contextInitialized(servletContextEvent);
}

From source file:org.jclouds.demo.tweetstore.config.SpringServletConfig.java

License:Apache License

@PostConstruct
public void initialize() throws IOException {
    BlobStoreContextFactory blobStoreContextFactory = new BlobStoreContextFactory();

    Properties props = loadJCloudsProperties();
    logger.trace("About to initialize members.");

    Module googleModule = new GoogleAppEngineConfigurationModule();
    Set<Module> modules = ImmutableSet.<Module>of(googleModule);
    // shared across all blobstores and used to retrieve tweets
    try {//w  w w .  ja v  a  2s .c o m
        twitter4j.conf.Configuration twitterConf = new ConfigurationBuilder()
                .setUser(props.getProperty("twitter.identity"))
                .setPassword(props.getProperty("twitter.credential")).build();
        twitterClient = new TwitterFactory(twitterConf).getInstance();
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                "properties for twitter not configured properly in " + props.toString(), e);
    }
    // common namespace for storing tweets
    container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER);

    // instantiate and store references to all blobstores by provider name
    providerTypeToBlobStoreMap = Maps.newHashMap();
    for (String hint : Splitter.on(',')
            .split(checkNotNull(props.getProperty(PROPERTY_BLOBSTORE_CONTEXTS), PROPERTY_BLOBSTORE_CONTEXTS))) {
        providerTypeToBlobStoreMap.put(hint, blobStoreContextFactory.createContext(hint, modules, props));
    }

    // get a queue for submitting store tweet requests
    Queue queue = QueueFactory.getQueue("twitter");
    // submit a job to store tweets for each configured blobstore
    for (String name : providerTypeToBlobStoreMap.keySet()) {
        queue.add(withUrl("/store/do").header("context", name).method(Method.GET));
    }
    logger.trace("Members initialized. Twitter: '%s', container: '%s', provider types: '%s'", twitterClient,
            container, providerTypeToBlobStoreMap.keySet());
}

From source file:org.jorge.twitterpromoter.io.net.TwitterManager.java

License:Open Source License

public void tweet(String message) {
    Twitter twitter = new TwitterFactory(new ConfigurationBuilder().setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).build()).getInstance();
    try {//from  ww  w.  j a  v a 2 s  .c  om
        twitter.updateStatus(message);
        System.out.println("Tweet " + message + " sent!");
    } catch (TwitterException e) {
        System.err.println("Tweet " + message + "not sent!");
        e.printStackTrace(System.err);
    }
}

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();/*  www  .  ja  va  2  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;
}