Example usage for twitter4j.conf ConfigurationBuilder setOAuthConsumerKey

List of usage examples for twitter4j.conf ConfigurationBuilder setOAuthConsumerKey

Introduction

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

Prototype

public ConfigurationBuilder setOAuthConsumerKey(String oAuthConsumerKey) 

Source Link

Usage

From source file:com.dwdesign.tweetings.util.Utils.java

License:Open Source License

public static Twitter getTwitterInstance(final Context context, final long account_id,
        final boolean include_entities, final boolean include_rts, final boolean use_httpclient) {
    if (context == null)
        return null;
    final SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
            Context.MODE_PRIVATE);
    final boolean enable_gzip_compressing = preferences != null
            ? preferences.getBoolean(PREFERENCE_KEY_GZIP_COMPRESSING, true)
            : true;//from   w ww  .  j  a  v a 2s . c om
    final boolean ignore_ssl_error = preferences != null
            ? preferences.getBoolean(PREFERENCE_KEY_IGNORE_SSL_ERROR, false)
            : false;
    final boolean enable_proxy = preferences != null
            ? preferences.getBoolean(PREFERENCE_KEY_ENABLE_PROXY, false)
            : false;
    final String consumer_key = preferences != null
            ? preferences.getString(PREFERENCE_KEY_CONSUMER_KEY, CONSUMER_KEY)
            : CONSUMER_KEY;
    final String consumer_secret = preferences != null
            ? preferences.getString(PREFERENCE_KEY_CONSUMER_SECRET, CONSUMER_SECRET)
            : CONSUMER_SECRET;

    Twitter twitter = null;
    final StringBuilder where = new StringBuilder();
    where.append(Accounts.USER_ID + "=" + account_id);
    final Cursor cur = context.getContentResolver().query(Accounts.CONTENT_URI, Accounts.COLUMNS,
            where.toString(), null, null);
    if (cur != null) {
        if (cur.getCount() == 1) {
            cur.moveToFirst();
            final ConfigurationBuilder cb = new ConfigurationBuilder();
            setUserAgent(context, cb);
            if (use_httpclient) {
                cb.setHttpClientImplementation(HttpClientImpl.class);
            }
            cb.setGZIPEnabled(enable_gzip_compressing);
            if (enable_proxy) {
                final String proxy_host = preferences.getString(PREFERENCE_KEY_PROXY_HOST, null);
                final int proxy_port = parseInt(preferences.getString(PREFERENCE_KEY_PROXY_PORT, "-1"));
                if (!isNullOrEmpty(proxy_host) && proxy_port > 0) {
                    cb.setHttpProxyHost(proxy_host);
                    cb.setHttpProxyPort(proxy_port);
                }

            }
            final String rest_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.REST_BASE_URL));
            final String signing_rest_base_url = cur
                    .getString(cur.getColumnIndexOrThrow(Accounts.SIGNING_REST_BASE_URL));
            final String search_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.SEARCH_BASE_URL));
            final String upload_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.UPLOAD_BASE_URL));
            final String oauth_base_url = cur.getString(cur.getColumnIndexOrThrow(Accounts.OAUTH_BASE_URL));
            final String signing_oauth_base_url = cur
                    .getString(cur.getColumnIndexOrThrow(Accounts.SIGNING_OAUTH_BASE_URL));
            //if (!isNullOrEmpty(rest_base_url)) {
            cb.setRestBaseURL(DEFAULT_REST_BASE_URL);
            //}
            //if (!isNullOrEmpty(search_base_url)) {
            cb.setSearchBaseURL(DEFAULT_SEARCH_BASE_URL);
            //}
            cb.setIncludeEntitiesEnabled(include_entities);
            cb.setIncludeRTsEnabled(include_rts);

            switch (cur.getInt(cur.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
            case Accounts.AUTH_TYPE_OAUTH:
            case Accounts.AUTH_TYPE_XAUTH:
                if (isNullOrEmpty(consumer_key) || isNullOrEmpty(consumer_secret)) {
                    cb.setOAuthConsumerKey(CONSUMER_KEY);
                    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
                } else {
                    cb.setOAuthConsumerKey(consumer_key);
                    cb.setOAuthConsumerSecret(consumer_secret);
                }
                twitter = new TwitterFactory(cb.build()).getInstance(
                        new AccessToken(cur.getString(cur.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN)),
                                cur.getString(cur.getColumnIndexOrThrow(Accounts.TOKEN_SECRET))));
                break;
            case Accounts.AUTH_TYPE_BASIC:
                twitter = new TwitterFactory(cb.build()).getInstance(
                        new BasicAuthorization(cur.getString(cur.getColumnIndexOrThrow(Accounts.USERNAME)),
                                cur.getString(cur.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD))));
                break;
            default:
            }
        }
        cur.close();
    }
    return twitter;
}

From source file:com.esri.geoevent.transport.twitter.TwitterInboundTransport.java

License:Apache License

private void receiveData() {
    try {/*from  w w w .j a va 2s.  c o m*/
        applyProperties();
        setRunningState(RunningState.STARTED);

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);
        cb.setOAuthConsumerKey(consumerKey);
        cb.setOAuthConsumerSecret(consumerSecret);
        cb.setOAuthAccessToken(accessToken);
        cb.setOAuthAccessTokenSecret(accessTokenSecret);
        twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

        RawStreamListener rl = new RawStreamListener() {

            @Override
            public void onException(Exception ex) {
                LOGGER.error("INBOUND_TRANSPORT_RAW_STREAM_LISTERNER_EXCEPTION", ex.getMessage());
            }

            @Override
            public void onMessage(String rawString) {
                receive(rawString);
            }
        };

        FilterQuery fq = new FilterQuery();

        String keywords[] = tracks;

        if (follows != null && follows.length > 0)
            fq.follow(follows);
        else if (keywords != null && keywords.length > 0)
            fq.track(keywords);
        else if (locations != null)
            fq.locations(locations);
        else
            throw new Exception("INBOUND_TRANSPORT_NOFILTER_ERROR");

        fq.count(count);

        LOGGER.info("INBOUND_TRANSPORT_FILTER", filterString);

        twitterStream.addListener(rl);
        twitterStream.filter(fq);

    } catch (Throwable ex) {
        LOGGER.error("UNEXPECTED_ERROR", ex);
        setRunningState(RunningState.ERROR);
    }
}

From source file:com.fsatir.twitter.TwitterManagedBean.java

public Twitter bringMyTwitterInstance() throws TwitterException {

    String consumerKey = TwitterInfos.CONSUMER_KEY.getCredentialValue();
    String consumerSecret = TwitterInfos.CONSUMER_SECRET.getCredentialValue();
    String oAuthToken = TwitterInfos.OAUTH_TOKEN.getCredentialValue();
    String oAuthSecret = TwitterInfos.OAUTH_SECRET.getCredentialValue();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    builder.setOAuthAccessToken(oAuthToken);
    builder.setOAuthAccessTokenSecret(oAuthSecret);
    Configuration configuration = builder.build();
    TwitterFactory factory = new TwitterFactory(configuration);
    Twitter twitter = factory.getInstance();
    return twitter;
}

From source file:com.github.gorbin.asne.twitter.TwitterSocialNetwork.java

License:Open Source License

private void initTwitterClient() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(fConsumerKey);
    builder.setOAuthConsumerSecret(fConsumerSecret);

    String accessToken = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_TOKEN, null);
    String accessTokenSecret = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_SECRET, null);

    TwitterFactory factory = new TwitterFactory(builder.build());

    if (TextUtils.isEmpty(accessToken) && TextUtils.isEmpty(accessTokenSecret)) {
        mTwitter = factory.getInstance();
    } else {//from   w w w  .j  a va 2 s  .  c  o  m
        mTwitter = factory.getInstance(new AccessToken(accessToken, accessTokenSecret));
    }
}

From source file:com.github.hiro2k.logback.twitter.TwitterAppender.java

License:Apache License

@Override
public void start() {
    boolean requiredPropsSet = true;
    if (getAccessToken() == null) {
        addStatus(new ErrorStatus("Access token not set", this));
        requiredPropsSet = false;/*from  ww w . j a v a 2s .  c  o  m*/
    }
    if (getAccessSecret() == null) {
        addStatus(new ErrorStatus("Access secret not set", this));
        requiredPropsSet = false;
    }
    if (getConsumerKey() == null) {
        addStatus(new ErrorStatus("Consumer key not set", this));
        requiredPropsSet = false;
    }
    if (getConsumerSecret() == null) {
        addStatus(new ErrorStatus("Consumer Secret not set", this));
        requiredPropsSet = false;
    }
    if (!requiredPropsSet && twitter == null) {
        addWarn("Appender not started because the required properties weren't all set.");
        return;
    }
    if (layout == null) {
        layout = makeDefaultPatternLayout();
    }
    if (twitter == null) {
        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        configBuilder.setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
                .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessSecret);
        TwitterFactory tf = new TwitterFactory(configBuilder.build());
        this.twitter = tf.getInstance();
    }
    super.start();
}

From source file:com.hortonworks.amuise.cdrstorm.kafka.producers.CDRTestDataProducer.java

private void start() {

    /**//  w  ww  .j a  va2  s  . c om
     * Kafka Twitter Producer properties *
     */
    Properties twitterconprops = new Properties();
    twitterconprops.put("metadata.broker.list", globalconfigs.getProperty("twitter4j.brokerlist"));
    twitterconprops.put("serializer.class", globalconfigs.getProperty("twitter4j.serializer"));
    twitterconprops.put("request.required.acks", globalconfigs.getProperty("twitter4j.requiredacks"));
    ProducerConfig twitterproducerconfig = new ProducerConfig(twitterconprops);
    final Producer<String, String> twitterproducer = new Producer<String, String>(twitterproducerconfig);

    /**
     * Kafka CDR Producer properties *
     */
    Properties cdrconprops = new Properties();
    cdrconprops.put("metadata.broker.list", globalconfigs.getProperty("cdr.brokerlist"));
    cdrconprops.put("serializer.class", globalconfigs.getProperty("cdr.serializer"));
    cdrconprops.put("request.required.acks", globalconfigs.getProperty("cdr.requiredacks"));
    ProducerConfig cdrproducerconfig = new ProducerConfig(cdrconprops);
    final Producer<String, String> cdrproducer = new Producer<String, String>(cdrproducerconfig);

    /**
     * Twitter4j properties *
     */
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(globalconfigs.getProperty("twitter4j.consumerkey"));
    cb.setOAuthConsumerSecret(globalconfigs.getProperty("twitter4j.consumersecretkey"));
    cb.setOAuthAccessToken(globalconfigs.getProperty("twitter4j.accesstokenkey"));
    cb.setOAuthAccessTokenSecret(globalconfigs.getProperty("twitter4j.accesstokensecretkey"));
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    /**
     * Twitter listener *
     */
    StatusListener listener = new StatusListener() {
        // The onStatus method is executed every time a new tweet comes
        // in.
        public void onStatus(Status status) {

            StringBuilder sb = new StringBuilder();
            sb.append(status.getUser().getScreenName());
            sb.append("|");
            sb.append(status.getCreatedAt());
            sb.append("|");
            sb.append(status.getRetweetCount());
            sb.append("|");
            sb.append(status.getSource());
            sb.append("|");
            sb.append(status.getText());

            //call CDR create message
            String cdrmessage = createCDRMessage(status.getText());

            //Debug output
            System.out.println("_________________________________________________________");
            System.out.println(sb.toString());
            System.out.println("cdr message: " + cdrmessage);
            System.out.println("_________________________________________________________");

            //call producer for tweet
            KeyedMessage<String, String> twitterdata = new KeyedMessage<String, String>(
                    globalconfigs.getProperty("twitter4j.kafkatopic"), sb.toString());
            twitterproducer.send(twitterdata);

            //call producer for cdr
            KeyedMessage<String, String> cdrmessagedata = new KeyedMessage<String, String>(
                    globalconfigs.getProperty("cdr.kafkatopic"), cdrmessage);
            cdrproducer.send(cdrmessagedata);

        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onScrubGeo(long userId, long upToStatusId) {
        }

        public void onException(Exception ex) {
            System.out.println("General Exception: shutting down Twitter sample stream...");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
            twitterStream.shutdown();
        }

        public void onStallWarning(StallWarning warning) {
        }
    };

    twitterStream.addListener(listener);

    // Filter stream with targeted words
    String filterstring = globalconfigs.getProperty("twitter4j.filterwords");
    FilterQuery filterq = new FilterQuery();
    filterq.track(filterstring.split(","));
    twitterStream.filter(filterq);

    //twitterStream.sample();
}

From source file:com.illusionaryone.TwitterAPI.java

License:Open Source License

public Boolean authenticate() {
    com.gmt2001.Console.debug.println("Attempting to Authenticate");
    try {//w w  w. j a  va 2s.  c o m
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setOAuthConsumerKey(consumerKey);
        configurationBuilder.setOAuthConsumerSecret(consumerSecret);
        configurationBuilder.setOAuthAccessToken(oauthAccessToken);
        configurationBuilder.setOAuthAccessTokenSecret(oauthAccessSecret);

        TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build());
        twitter = twitterFactory.getInstance();

        accessToken = twitter.getOAuthAccessToken();
        com.gmt2001.Console.out.println("Authenticated with Twitter API");
        return true;
    } catch (TwitterException ex) {
        com.gmt2001.Console.err.println("Twitter Auth Failed: " + ex.getMessage());
        accessToken = null;
        return false;
    }
}

From source file:com.irontec.mintzatu.EzarpenakDetailActivity.java

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

    try {// ww  w.j  a  va  2s. com
        requestToken = twitter.getOAuthRequestToken(TwitterHelper.CALLBACK_URL);
        Intent i = new Intent(this, WebviewActivity.class);
        i.putExtra("URL", requestToken.getAuthenticationURL());
        startActivityForResult(i, TWITTER_AUTH);
    } catch (TwitterException e) {
        e.printStackTrace();
    }
}

From source file:com.javielinux.api.loaders.ImageUploadLoader.java

License:Apache License

@Override
public BaseResponse loadInBackground() {

    try {/*  w ww  .j  av  a  2  s  .  c  o m*/

        ImageUploadResponse response = new ImageUploadResponse();

        String f = Utils.appUploadImageDirectory + request.getFilename();

        response.setFile(request.getFilename());
        /*
           int size = Integer.parseInt(Utils.getPreference(mContext).getString("prf_size_photo", "2"));
                
           if (size == 1) {
           Bitmap resizedBitmap = Utils.getResizeBitmapFromFile(f, Utils.HEIGHT_PHOTO_SIZE_SMALL);
           if (resizedBitmap!=null) {
               FileOutputStream out = new FileOutputStream(f);
               resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
           }
           } else if (size == 2) {
           Bitmap resizedBitmap = Utils.getResizeBitmapFromFile(f, Utils.HEIGHT_PHOTO_SIZE_MIDDLE);
           if (resizedBitmap!=null) {
               FileOutputStream out = new FileOutputStream(f);
               resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
           }
           }
           */
        response.setBmp(ImageUtils.getBitmapFromFile(f, Utils.HEIGHT_THUMB_NEWSTATUS, true));

        File file = new File(f);

        int type = Integer.parseInt(Utils.getPreference(getContext()).getString("prf_service_image", "1"));

        MediaProvider mp = MediaProvider.YFROG;

        if (type == 1) {
            mp = MediaProvider.YFROG;
        } else if (type == 2) {
            mp = MediaProvider.TWITPIC;
        } else if (type == 3) {
            mp = MediaProvider.PLIXI;
        }

        loadConsumerKeys();

        ConfigurationBuilder confBuild = new ConfigurationBuilder();
        confBuild.setOAuthConsumerKey(consumerKey);
        confBuild.setOAuthConsumerSecret(consumerSecretKey);
        confBuild.setOAuthAccessToken(ConnectionManager.getInstance().getTwitter(request.getUserId())
                .getOAuthAccessToken().getToken());
        confBuild.setOAuthAccessTokenSecret(ConnectionManager.getInstance().getTwitter(request.getUserId())
                .getOAuthAccessToken().getTokenSecret());
        if (type == 1) {
        } else if (type == 2) {
            confBuild.setMediaProviderAPIKey("e3533af853e8f63a0018a2c63d7ee69f");
        } else if (type == 3) {
            confBuild.setMediaProviderAPIKey("57438faa-51e4-43a5-9e15-0c63b6f73950");
        }

        confBuild.setMediaProvider(mp.name());
        Configuration config = confBuild.build();

        ImageUpload upload = new ImageUploadFactory(config).getInstance(mp);
        if (upload != null) {
            response.setUrl(upload.upload(file));
            return response;
        } else {
            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.setError("Image upload is null");
            return errorResponse;
        }

    } catch (TwitterException exception) {
        exception.printStackTrace();
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setError(exception, exception.getMessage());
        return errorResponse;
    } catch (Exception exception) {
        exception.printStackTrace();
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setError(exception, exception.getMessage());
        return errorResponse;
    }

}

From source file:com.javielinux.task.ImageUploadAsyncTask.java

License:Apache License

@Override
protected ImageUploadAsyncTask.ImageUploadResult doInBackground(String... args) {
    ImageUploadResult iur = new ImageUploadResult();
    try {//from  w  ww  . j  av  a  2s . c  om

        String f = Utils.appUploadImageDirectory + args[0];

        iur.file = args[0];
        /*
        int size = Integer.parseInt(Utils.getPreference(mContext).getString("prf_size_photo", "2"));
                
        if (size == 1) {
           Bitmap resizedBitmap = Utils.getResizeBitmapFromFile(f, Utils.HEIGHT_PHOTO_SIZE_SMALL);
           if (resizedBitmap!=null) {
        FileOutputStream out = new FileOutputStream(f);
        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
           }
        } else if (size == 2) {
           Bitmap resizedBitmap = Utils.getResizeBitmapFromFile(f, Utils.HEIGHT_PHOTO_SIZE_MIDDLE);
           if (resizedBitmap!=null) {
        FileOutputStream out = new FileOutputStream(f);
        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
           }
        }
        */
        iur.bmp = ImageUtils.getBitmapFromFile(f, Utils.HEIGHT_THUMB_NEWSTATUS, true);

        File file = new File(f);

        int type = Integer.parseInt(Utils.getPreference(mContext).getString("prf_service_image", "1"));

        MediaProvider mp = MediaProvider.YFROG;

        if (type == 1) {
            mp = MediaProvider.YFROG;
        } else if (type == 2) {
            mp = MediaProvider.TWITPIC;
        } else if (type == 3) {
            mp = MediaProvider.PLIXI;
        }

        loadConsumerKeys();

        ConfigurationBuilder confBuild = new ConfigurationBuilder();
        confBuild.setOAuthConsumerKey(consumerKey);
        confBuild.setOAuthConsumerSecret(consumerSecretKey);
        confBuild.setOAuthAccessToken(twitter.getOAuthAccessToken().getToken());
        confBuild.setOAuthAccessTokenSecret(twitter.getOAuthAccessToken().getTokenSecret());
        if (type == 1) {
        } else if (type == 2) {
            confBuild.setMediaProviderAPIKey("e3533af853e8f63a0018a2c63d7ee69f");
        } else if (type == 3) {
            confBuild.setMediaProviderAPIKey("57438faa-51e4-43a5-9e15-0c63b6f73950");
        }

        confBuild.setMediaProvider(mp.name());
        Configuration config = confBuild.build();

        ImageUpload upload = new ImageUploadFactory(config).getInstance(mp);
        if (upload != null) {
            iur.url = upload.upload(file);
            iur.error = false;
        } else {
            iur.error = true;
        }

    } catch (TwitterException e) {
        e.printStackTrace();
        iur.error = true;

    } catch (Exception e) {
        e.printStackTrace();
        iur.error = true;
    }
    return iur;
}