Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

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

License:Apache License

/**
 *
 * @param consumerSecret// w w  w. j a v a2s. c  o m
 * @param consumerKey
 * @param account
 */
public TwitterAPITemplate(final String consumerSecret, final String consumerKey, final SocialAccount account) {
    Assert.notNull(consumerKey);
    Assert.notNull(consumerSecret);
    Assert.notNull(account);
    log.debug("consumer key " + consumerKey);
    log.debug("consumer secret " + consumerSecret);
    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;
    this.secretToken = account.getSecretToken();
    this.accessToken = account.getAccessToken();
    this.socialAccount = account;
    this.configurationBuilder = new ConfigurationBuilder();
    this.configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(this.consumerKey)
            .setOAuthConsumerSecret(this.consumerSecret).setOAuthAccessToken(this.accessToken)
            .setOAuthAccessTokenSecret(this.secretToken);
}

From source file:org.fossasia.phimpme.share.twitter.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final String imageUrl, final String message,
        final String token, final String secret, final TwitterCallback postResponse) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
    configurationBuilder.setOAuthAccessToken(token);
    configurationBuilder.setOAuthAccessTokenSecret(secret);
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    final File file = new File(imageUrl);
    boolean success = true;
    if (file.exists()) {
        try {//www . j av a 2  s .c  om
            StatusUpdate status = new StatusUpdate(message);
            status.setMedia(file);
            twitter.updateStatus(status);
        } catch (TwitterException e) {
            e.printStackTrace();
            success = false;
        }
    } else {
        Log.d(TAG, "----- Invalid File ----------");
        success = false;
    }
    postResponse.onFinsihed(success);

}

From source file:org.fossasia.phimpme.share.twitter.LoginActivity.java

License:Apache License

private void askOAuth() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
    Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {
        @Override//from   w w w  .  j a v  a 2s .co  m
        public void run() {
            try {
                requestToken = twitter.getOAuthRequestToken(AppConstant.TWITTER_CALLBACK_URL);
            } catch (Exception e) {
                final String errorString = e.toString();
                LoginActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        SnackBarHandler.show(parentView, errorString);
                        finish();
                    }
                });
                return;
            }

            LoginActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    twitterLoginWebView.loadUrl(requestToken.getAuthenticationURL());
                }
            });
        }
    }).start();
}

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

License:Apache License

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

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret);

    Twitter twitter = new TwitterFactory(c.build()).getInstance();
    request.getSession().setAttribute("twitter", twitter);

    try {/*from  w  ww.  j  a  v a2s.c  o  m*/
        // twitter will tell the users browser to go to this address once
        // they are done authing.
        String callbackURL = authURL + "/TwitterCallback";

        // to initiate an auth request, twitter needs us to have a request
        // token.
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);

        // stash the request token in the session.
        request.getSession().setAttribute("requestToken", requestToken);

        // send the user to twitter to be authenticated.
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }

}

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.j a  v  a  2  s  . c o  m
 *
 * @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");
    }/*  w w  w .  j a  v a2 s  .  com*/

    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.activity.support.SignInActivity.java

License:Open Source License

private Configuration getConfiguration() {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    final boolean enable_gzip_compressing = mPreferences.getBoolean(KEY_GZIP_COMPRESSING, false);
    final boolean ignore_ssl_error = mPreferences.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enable_proxy = mPreferences.getBoolean(KEY_ENABLE_PROXY, false);
    cb.setHostAddressResolverFactory(new FiretweetHostResolverFactory(mApplication));
    cb.setHttpClientFactory(new OkHttpClientFactory(mApplication));
    if (TwitterContentUtils.isOfficialKey(this, mConsumerKey, mConsumerSecret)) {
        Utils.setMockOfficialUserAgent(this, cb);
    } else {//from   ww  w.  j a v a  2 s .co m
        Utils.setUserAgent(this, cb);
    }
    final String apiUrlFormat = TextUtils.isEmpty(mAPIUrlFormat) ? DEFAULT_TWITTER_API_URL_FORMAT
            : mAPIUrlFormat;
    final String versionSuffix = mNoVersionSuffix ? null : "/1.1/";
    cb.setRestBaseURL(Utils.getApiUrl(apiUrlFormat, "api", versionSuffix));
    cb.setOAuthBaseURL(Utils.getApiUrl(apiUrlFormat, "api", "/oauth/"));
    cb.setUploadBaseURL(Utils.getApiUrl(apiUrlFormat, "upload", versionSuffix));
    cb.setOAuthAuthorizationURL(Utils.getApiUrl(apiUrlFormat, null, "/oauth/authorize"));
    cb.setHttpUserAgent(Utils.generateBrowserUserAgent());
    if (!mSameOAuthSigningUrl) {
        cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
        cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
        cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
    }
    if (isEmpty(mConsumerKey) || isEmpty(mConsumerSecret)) {
        cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_3);
        cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_3);
    } else {
        cb.setOAuthConsumerKey(mConsumerKey);
        cb.setOAuthConsumerSecret(mConsumerSecret);
    }
    cb.setGZIPEnabled(enable_gzip_compressing);
    cb.setIgnoreSSLError(ignore_ssl_error);
    if (enable_proxy) {
        final String proxy_host = mPreferences.getString(KEY_PROXY_HOST, null);
        final int proxy_port = ParseUtils.parseInt(mPreferences.getString(KEY_PROXY_PORT, "-1"));
        if (!isEmpty(proxy_host) && proxy_port > 0) {
            cb.setHttpProxyHost(proxy_host);
            cb.setHttpProxyPort(proxy_port);
        }
    }
    return cb.build();
}

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

License:Open Source License

public static HttpClientWrapper getHttpClient(final Context context, final int timeoutMillis,
        final boolean ignoreSslError, final Proxy proxy, final HostAddressResolverFactory resolverFactory,
        final String userAgent, final boolean twitterClientHeader) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeoutMillis);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeTwitterClientHeader(twitterClientHeader);
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress address = proxy.address();
        if (address instanceof InetSocketAddress) {
            cb.setHttpProxyHost(((InetSocketAddress) address).getHostName());
            cb.setHttpProxyPort(((InetSocketAddress) address).getPort());
        }//from  w  w w.  j  a  v  a2s . co  m
    }
    cb.setHostAddressResolverFactory(resolverFactory);
    if (userAgent != null) {
        cb.setHttpUserAgent(userAgent);
    }
    cb.setHttpClientFactory(new OkHttpClientFactory(context));
    return new HttpClientWrapper(cb.build());
}

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

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context,
        final ParcelableCredentials account) {
    if (context == null || account == null)
        return null;
    switch (account.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE);
        // Here I use old consumer key/secret because it's default
        // key for older
        // versions
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        if (!isEmpty(account.api_url_format)) {
            final String versionSuffix = account.no_version_suffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(account.api_url_format, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(account.api_url_format, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(account.api_url_format, "upload", versionSuffix));
            cb.setOAuthAuthorizationURL(getApiUrl(account.api_url_format, null, null));
            if (!account.same_oauth_signing_url) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }/*from  w ww  . j a  v a2s  .com*/
        }
        if (!isEmpty(account.consumer_key) && !isEmpty(account.consumer_secret)) {
            cb.setOAuthConsumerKey(account.consumer_key);
            cb.setOAuthConsumerSecret(account.consumer_secret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        }
        final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
        auth.setOAuthAccessToken(new AccessToken(account.oauth_token, account.oauth_token_secret));
        return auth;
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = account.screen_name;
        final String username = account.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = account.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new BasicAuthorization(loginName, password);
    }
    default: {
        return null;
    }
    }
}