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: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 {//from  w  w w . ja v  a 2 s  . c o  m
        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: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/*from   w  w w .java  2 s.c o m*/
    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/*from   w w w  .  ja va2 s.c o 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();//from  www.  j a  v  a  2 s  .  com
}

From source file:cmu.edu.homework.mediaUpload.TwitterVideoUpload.java

License:Apache License

public TwitterVideoUpload(Configuration conf, OAuthAuthorization oauth) {
    twitter = new TwitterFactory(conf).getInstance(oauth);
}

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  ww w .j ava  2s.  co  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();
    }
}

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

License:Open Source License

/**
 * Test code to try and retrieve some data from twitter in a search!
 * @throws TwitterException //from  w w  w.j a  v  a2 s .  c  om
 * */
public JSONArray doSearch(View v) throws TwitterException {

    if (mApiClient != null || debugOn) {
        // The factory instance is re-useable and thread safe.
        //get the hashtag - check to make sure if returned value is set to something with a length
        JSONArray jsA = new JSONArray();
        String qHash = p.getString(KEY_CAST_HASHTAG, "");
        Log.d(TAG, "Hash to search: " + qHash);
        if (qHash.length() == 0) {
            Toast.makeText(this, "The hashtag looks like it is not setup. May want to fix that",
                    Toast.LENGTH_LONG).show();
        } else {
            try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

                // Access Token 
                String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
                // Access Token Secret
                String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

                AccessToken accessToken = new AccessToken(access_token, access_token_secret);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
                //Query query = new Query("#MOTD2014");
                Query query = new Query(qHash);
                query.count(TWEET_COUNT);
                QueryResult result = twitter.search(query);
                for (twitter4j.Status status : result.getTweets()) {

                    MediaEntity[] me = status.getMediaEntities();
                    String meUrl = "";
                    if (me.length > 0) {
                        Log.d(TAG, "me[0] : " + me[0].getMediaURL());
                        //meUrl = me[0].getDisplayURL(); //sjort URl = useless.
                        meUrl = me[0].getMediaURL();
                    }

                    JSONObject jso = tweetJSON(status.getUser().getScreenName(), status.getUser().getName()
                    //                        , status.getUser().getOriginalProfileImageURL() //Whatever the size was it was uploaded in
                    //                        , status.getUser().getProfileImageURL() // 48x48
                            , status.getUser().getBiggerProfileImageURL() // 73x73
                            , status.getText(), status.getCreatedAt().toString(), status.getFavoriteCount(),
                            status.getRetweetCount(), meUrl);
                    jsA.put(jso);
                }

            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Search Error", e.getMessage());
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        ;
        return jsA;
    } else {
        Toast.makeText(this, "You do not seem to be connected to a cast device...", Toast.LENGTH_LONG).show();
        return null;
    }
}

From source file:cojoytuerto.CojoYTuertoFrame.java

public CojoYTuertoFrame() {
    initComponents();/* w  ww . j ava2s  .  com*/
    jTable1.getTableHeader().setReorderingAllowed(false);
    try {
        TAuth auth = new TAuth();
    } catch (IOException | TwitterException ex) {
        Logger.getLogger(CojoYTuertoFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        // Apertura del fichero y creacion de BufferedReader
        archivo = new File("auth_file.txt");
        fileR = new FileReader(archivo);
        lecturaTeclado = new BufferedReader(fileR);
        // Lectura del fichero
        String linea = new String();
        int n = 1;
        while ((linea = lecturaTeclado.readLine()) != null) {
            if (n == 1) { //La primera lnea es el Access Token
                System.out.println(linea);
                Token = linea;
            } else if (n == 2) { //La segunda lnea es el Access Token Secret
                System.out.println(linea);
                TokenSecret = linea;
            }
            n++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // En el finally cerramos el fichero, para asegurarnos
        // que se cierra tanto si todo va bien como si salta
        // una excepcin.
        try {
            if (null != fileR) {
                fileR.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    configBuilder = new ConfigurationBuilder();
    configBuilder.setDebugEnabled(true).setOAuthConsumerKey("wCWSOW8xHlxfQq24kSxXuXNm9")
            .setOAuthConsumerSecret("5B1R4bxZv7TcO7Vmq3NvhM3Bo3YcO0qCIJP2vDD9HnOaPL63YD");
    configBuilder.setHttpProxyHost("127.0.0.1");
    configBuilder.setUseSSL(true);
    configBuilder.setHttpProxyPort(3128);

    configBuilder.setOAuthAccessToken(Token).setOAuthAccessTokenSecret(TokenSecret);
    twitter = new TwitterFactory(configBuilder.build()).getInstance();
}

From source file:cojoytuerto.TAuth.java

public TAuth() throws IOException, TwitterException { //Constructor de la clase
    File file = new File("auth_file.txt");
    if (!file.exists()) {

        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        configBuilder.setDebugEnabled(true).setOAuthConsumerKey("wCWSOW8xHlxfQq24kSxXuXNm9")
                .setOAuthConsumerSecret("5B1R4bxZv7TcO7Vmq3NvhM3Bo3YcO0qCIJP2vDD9HnOaPL63YD");
        configBuilder.setHttpProxyHost("127.0.0.1");
        configBuilder.setUseSSL(true);//from   w w  w .j a v  a 2s  .co  m
        configBuilder.setHttpProxyPort(3128);
        Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        String url = null;

        do {
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                System.out.println("Request Token obtenido con xito.");
                System.out.println("Request Token: " + requestToken.getToken());
                System.out.println("Request Token secret: " + requestToken.getTokenSecret());
                url = requestToken.getAuthorizationURL();
                url = url.replace("http://", "https://");
                System.out.println("URL:");
                System.out.println(url);
            } catch (TwitterException ex) {
                Logger.getLogger(TAuth.class.getName()).log(Level.SEVERE, null, ex);
            }
            BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in));
            //Abro el navegador. Firefox, en este caso.
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("firefox " + url);
            } catch (Exception e) {
            }
            //Nos avisa de que introduciremos el PIN a continuacin

            System.out.print("Introduce el PIN del navegador y pulsa intro.nn PIN: ");
            //Leemos el PIN
            //                String pin = lectorTeclado.readLine();
            String pin = JOptionPane.showInputDialog(null,
                    "Introduce el PIN del navegador y pulsa intro.nn PIN: ");
            if (pin.length() > 0) {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken);
            }
        } while (accessToken == null);

        System.out.println("nnAccess Tokens obtenidos con xito.");
        System.out.println("Access Token: " + accessToken.getToken());
        System.out.println("Access Token secret: " + accessToken.getTokenSecret());
        FileOutputStream fileOS = null;
        //            File file;
        String content = accessToken.getToken() + "\n" + accessToken.getTokenSecret();
        try {
            //                file = new File("auth_file.txt");
            fileOS = new FileOutputStream(file);
            //Si el archivo no existe, se crea
            if (!file.exists()) {
                file.createNewFile();
            }
            //Se obtiene el contenido en Bytes
            byte[] contentInBytes = content.getBytes();
            fileOS.write(contentInBytes);
            fileOS.flush();
            fileOS.close();
            System.out.println("Escritura realizada con xito.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOS != null) {
                    fileOS.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}