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:br.com.porcelli.hornetq.integration.twitter.stream.StreamHandler.java

License:Apache License

public StreamHandler(final String connectorName, final Map<String, Object> configuration,
        final StorageManager storageManager, final PostOffice postOffice) {

    this.connectorName = connectorName;

    this.mbean = new TwitterStreamManagement(this);

    try {// w w  w.  ja  v  a2s  .  c om
        MBeanServer mbServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName mbeanName = new ObjectName("org.hornetq:module=ConnectorService,name=" + connectorName);
        mbServer.registerMBean(mbean, mbeanName);
    } catch (Exception e) {
        log.error("Error on registering JMX info.", e);
    }

    final Configuration conf = new ConfigurationBuilder()
            .setOAuthConsumerKey(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_CONSUMER_KEY, null, configuration))
            .setOAuthConsumerSecret(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_CONSUMER_SECRET, null, configuration))
            .setOAuthAccessToken(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_ACCESS_TOKEN, null, configuration))
            .setOAuthAccessTokenSecret(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_ACCESS_TOKEN_SECRET, null, configuration))
            .build();

    final String queueName = ConfigurationHelper.getStringProperty(InternalTwitterConstants.PROP_QUEUE_NAME,
            null, configuration);

    final String userScreenName = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_SCREEN_NAME, null, configuration);

    final String lastTweetQueueName = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_LAST_TWEET_QUEUE_NAME, null, configuration);

    final String lastDMQueueName = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_LAST_DM_QUEUE_NAME, null, configuration);

    Long lastTweetId = null;
    if (lastTweetQueueName != null && lastTweetQueueName.trim().length() > 0) {
        final Binding lastTweetBinding = postOffice.getBinding(new SimpleString(lastTweetQueueName));
        if (lastTweetBinding != null) {
            final Queue lastTweetQueue = (Queue) lastTweetBinding.getBindable();
            if (lastTweetQueue.getMessageCount() > 0) {
                long ltweetId = Long.MIN_VALUE;
                for (final Iterator<MessageReference> iterator = lastTweetQueue.iterator(); iterator
                        .hasNext();) {
                    final MessageReference msg = iterator.next();
                    lastTweetId = msg.getMessage().getBodyBuffer().readLong();
                    if (lastTweetId > ltweetId) {
                        ltweetId = lastTweetId;
                    }
                }
                lastTweetId = ltweetId + 1L;
            }
        }
    }

    Long lastDMId = null;
    if (lastDMQueueName != null && lastDMQueueName.trim().length() > 0) {
        final Binding lastTweetBinding = postOffice.getBinding(new SimpleString(lastDMQueueName));
        if (lastTweetBinding != null) {
            final Queue lastDMQueue = (Queue) lastTweetBinding.getBindable();
            if (lastDMQueue.getMessageCount() > 0) {
                long ldmId = Long.MIN_VALUE;
                for (final Iterator<MessageReference> iterator = lastDMQueue.iterator(); iterator.hasNext();) {
                    final MessageReference msg = iterator.next();
                    lastDMId = msg.getMessage().getBodyBuffer().readLong();
                    if (lastDMId > ldmId) {
                        ldmId = lastDMId;
                    }
                }
                lastDMId = ldmId + 1L;
            }
        }
    }

    final String[] mentionedUsers = splitProperty(ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_MENTIONED_USERS, null, configuration));

    final String[] hashTags = splitProperty(
            ConfigurationHelper.getStringProperty(InternalTwitterConstants.PROP_HASHTAGS, null, configuration));

    int[] userIds = null;
    int userId = -1;
    Twitter twitter = null;
    if (mentionedUsers != null) {
        try {
            twitter = new TwitterFactory(conf).getInstance();
            userId = twitter.getId();
            userIds = userIds(twitter.lookupUsers(mentionedUsers));
        } catch (final TwitterException e) {
            mbean.notifyException(e);
        } finally {
            if (twitter != null) {
                twitter.shutdown();
            }
        }
    }

    data = new TwitterStreamDTO(queueName, userScreenName, userId, lastTweetQueueName, lastDMQueueName,
            lastTweetId, lastDMId, mentionedUsers, userIds, hashTags, conf, postOffice);

    final String reclaimers = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_TWEET_RECLAIMERS, null, configuration);

    message = new MessageQueuing(data, this.mbean, splitProperty(reclaimers));

    streamListenersInsanceArgs = new Object[] { data, message, mbean };

    final String listenerList = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_STREAM_LISTENERS, null, configuration);

    final String[] listeners = splitProperty(listenerList);
    if (listeners != null) {
        final UserStreamHandler userHandler = buildUserStreamHandler(listeners);
        final SiteStreamHandler siteHandler = buildSiteStreamHandler(listeners);
        final StatusStreamHandler statusHandler = buildStatusStreamHandler(listeners);
        if (userHandler != null || siteHandler != null || statusHandler != null) {
            streamHandlers = new HashSet<BaseStreamHandler>();
            if (userHandler != null) {
                streamHandlers.add(userHandler);
            }
            if (siteHandler != null) {
                streamHandlers.add(siteHandler);
            }
            if (statusHandler != null) {
                streamHandlers.add(statusHandler);
            }
        } else {
            streamHandlers = null;
        }
    } else {
        streamHandlers = null;
    }
}

From source file:br.shura.team.mpsbot.runtime.ConnectedBot.java

License:Open Source License

public void connect() {
    ApiKeys keys = getBot().getApiKeys();

    if (!isConnected()) {
        Configuration configuration = new ConfigurationBuilder().setOAuthAccessToken(keys.getAccessToken())
                .setOAuthAccessTokenSecret(keys.getAccessTokenSecret())
                .setOAuthConsumerKey(keys.getConsumerKey()).setOAuthConsumerSecret(keys.getConsumerSecret())
                .build();/*  w w w .  j  a  va2s.c  om*/
        OAuthAuthorization auth = new OAuthAuthorization(configuration);
        TwitterStreamFactory streamFactory = new TwitterStreamFactory(configuration);
        ImageUploadFactory uploadFactory = new ImageUploadFactory(configuration);

        this.streamer = streamFactory.getInstance(auth);
        this.uploader = uploadFactory.getInstance(auth);
    }
}

From source file:cats.twitter.collect.Collect.java

@Override
public boolean runCollect() {

    dateEnd = Calendar.getInstance();
    dateEnd.add(Calendar.DAY_OF_YEAR, duree);
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/* www . ja  va 2 s  .  c  o  m*/
    cb.setOAuthConsumerKey(user.getConsumerKey());
    System.out.println("CONSUMER KEY " + user.getConsumerKey());
    cb.setOAuthConsumerSecret(user.getConsumerSecret());
    System.out.printf("CONSUMER SECRET " + user.getConsumerSecret());
    cb.setOAuthAccessToken(user.getToken());
    System.out.printf("TOKEN" + user.getToken());
    cb.setOAuthAccessTokenSecret(user.getTokenSecret());
    System.out.printf("TOKEN SECRET " + user.getTokenSecret());

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

    setStatus(State.WAITING_FOR_CONNECTION);

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {

            if (!corpus.getState().equals(State.INPROGRESS)) {
                setStatus(State.INPROGRESS);
            }
            if (status.getCreatedAt().after(dateEnd.getTime())) {
                shutdown();

            } else if (corpus.getLang() == null || corpus.getLang().equals(status.getLang())) {
                Tweet t = new Tweet();
                t.setText(status.getText().replace("\r", "\n"));
                t.setAuthor(status.getUser().getId());
                t.setId(status.getId());
                t.setDate(status.getCreatedAt());
                if (status.getGeoLocation() != null)
                    t.setLocation(status.getGeoLocation().toString());
                t.setName(status.getUser().getName());
                t.setDescriptionAuthor(status.getUser().getDescription());
                t.setLang(status.getLang());
                t.setCorpus(corpus);
                if (tweetRepository != null)
                    tweetRepository.save(t);
            }

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
            System.out.println(sdn);
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            corpus.setLimitationNotice(i);
            corpus = corpusRepository.save(corpus);

        }

        @Override
        public void onScrubGeo(long l, long l1) {
            System.out.println(l + "" + l1);
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            System.out.println(sw);
        }

        @Override
        public void onException(Exception excptn) {
            corpus.setErrorMessage(excptn.getMessage());
            setStatus(State.ERROR);
            excptn.printStackTrace();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.filter(filter);

    return false;
}

From source file:clientetwitter.ClienteTwitter.java

public static void PostInTimeLine(String texto) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("xxxxxxxxxxxx") //to get all the OAuth go to apps.twitter.com 
            .setOAuthConsumerSecret("xxxxxxxxxxxxxxxx").setOAuthAccessToken("xxxxxxxxxxxxxxxxxxxxxxx")
            .setOAuthAccessTokenSecret("xxxxxxxxxxxxxxxxxxxx");

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter4j.Twitter tw = tf.getInstance();

    //posting// ww w . j  a va2s  .  c om
    Status stat = tw.updateStatus(texto);
    System.out.println("Posted");

}

From source file:clientetwitter.ClienteTwitter.java

public static void ReadTimeLine() throws TwitterException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("ZpF1TSpAyQlBLMN7egUz3uT3D")
            .setOAuthConsumerSecret("r2icg36QB6G862Re2IvwHNGuDK25z5awKSeNG9kV9LRpcAmuOW")
            .setOAuthAccessToken("4314010284-QGXKFbFQ5TK4zqbplRsfoP0wL6NTv7bsMJypWex")
            .setOAuthAccessTokenSecret("4v61YXTkzM3Kob0xAHu59ISgM0fTKSLrOuDXTG5ctX7rr");

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter4j.Twitter tw = tf.getInstance();

    //reading//  w w  w . jav  a 2s .  co m
    List<Status> statuses = tw.getHomeTimeline();
    for (Status status1 : statuses) {
        System.out.println(status1.getUser().getName() + ": " + status1.getText());
    }

}

From source file:cloudcomputebot.Twitter.TwitterLib.java

License:Open Source License

public static void init() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("yZpAVykzcxwyohWOVBwuFaaaB")
            .setOAuthConsumerSecret("tXZQzYPeh1YmxGUPYotaKFoeLKeI6m8dAPgPh60l4mSltmMpxw")
            .setOAuthAccessToken("4741197613-i0WRUBMg1oGM2JR6GWnAztKs60u8lhMBhlr8TXD")
            .setOAuthAccessTokenSecret("H4EMPCNPV0NkTom3aUZB8J2uOaWnYHC28vxyTZ1bCvpd6");
    TwitterFactory tf = new TwitterFactory(cb.build());
    t = tf.getInstance();/*w w  w  .j  ava 2s.co m*/
}

From source file:co.cask.cdap.template.etl.realtime.source.TwitterSource.java

License:Apache License

@Override
public void initialize(RealtimeContext context) throws Exception {
    super.initialize(context);

    // Disable chatty logging from twitter4j.
    System.setProperty("twitter4j.loggerFactory", "twitter4j.NullLoggerFactory");

    Schema.Field idField = Schema.Field.of(ID, Schema.of(Schema.Type.LONG));
    Schema.Field msgField = Schema.Field.of(MSG, Schema.of(Schema.Type.STRING));
    Schema.Field langField = Schema.Field.of(LANG, Schema.nullableOf(Schema.of(Schema.Type.STRING)));
    Schema.Field timeField = Schema.Field.of(TIME, Schema.nullableOf(Schema.of(Schema.Type.LONG)));
    Schema.Field favCount = Schema.Field.of(FAVC, Schema.of(Schema.Type.INT));
    Schema.Field rtCount = Schema.Field.of(RTC, Schema.of(Schema.Type.INT));
    Schema.Field sourceField = Schema.Field.of(SRC, Schema.nullableOf(Schema.of(Schema.Type.STRING)));
    Schema.Field geoLatField = Schema.Field.of(GLAT, Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)));
    Schema.Field geoLongField = Schema.Field.of(GLNG, Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)));
    Schema.Field reTweetField = Schema.Field.of(ISRT, Schema.of(Schema.Type.BOOLEAN));
    schema = Schema.recordOf("tweet", idField, msgField, langField, timeField, favCount, rtCount, sourceField,
            geoLatField, geoLongField, reTweetField);

    statusListener = new StatusListener() {
        @Override/*from   ww w .j  a va2s  . c  o m*/
        public void onStatus(Status status) {
            tweetQ.add(status);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            // No-op
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            // No-op
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            // No-op
        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {
            // No-op
        }

        @Override
        public void onException(Exception e) {
            // No-op
        }
    };

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(false).setOAuthConsumerKey(twitterConfig.consumerKey)
            .setOAuthConsumerSecret(twitterConfig.consumeSecret).setOAuthAccessToken(twitterConfig.accessToken)
            .setOAuthAccessTokenSecret(twitterConfig.accessTokenSecret);

    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    twitterStream.addListener(statusListener);
    twitterStream.sample();
}

From source file:co.cask.hydrator.plugin.realtime.source.TwitterSource.java

License:Apache License

@Override
public void initialize(RealtimeContext context) throws Exception {
    super.initialize(context);

    // Disable chatty logging from twitter4j.
    System.setProperty("twitter4j.loggerFactory", "twitter4j.NullLoggerFactory");

    statusListener = new StatusListener() {
        @Override//from   w  w w  .j a va 2  s . com
        public void onStatus(Status status) {
            tweetQ.add(status);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            // No-op
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            // No-op
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            // No-op
        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {
            // No-op
        }

        @Override
        public void onException(Exception e) {
            // No-op
        }
    };

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(false).setOAuthConsumerKey(twitterConfig.consumerKey)
            .setOAuthConsumerSecret(twitterConfig.consumeSecret).setOAuthAccessToken(twitterConfig.accessToken)
            .setOAuthAccessTokenSecret(twitterConfig.accessTokenSecret);

    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
    twitterStream.addListener(statusListener);
    twitterStream.sample();
}

From source file:co.thehotnews.lambda.TheHotNewsSpeechlet.java

License:Open Source License

public TheHotNewsSpeechlet() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(TWITTER_OAUTH_CONSUMER_KEY)
            .setOAuthConsumerSecret(TWITTER_OAUTH_CONSUMER_SECRET)
            .setOAuthAccessToken(TWITTER_OAUTH_ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(TWITTER_OAUTH_ACCESS_TOKEN_SECRET);
    twitterFactory = new TwitterFactory(cb.build());
}

From source file:co.uk.socialticker.ticker.TickerActivity.java

License:Open Source License

/**
 * Function to login twitter/*from   w  w w .j a v a2s.  c o  m*/
 * */
private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        try {
            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}