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:com.storm.demo.TwitterSampleSpout.java

License:Apache License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<String>(1000);
    _collector = collector;//  www  .j ava  2  s. c  om

    //        StatusListener listener = new StatusListener() {
    //
    //            @Override
    //            public void onStatus(Status status) {
    //                System.out.println(DataObjectFactory.getRawJSON(status));
    //                queue.offer(status);
    //            }
    //
    //            @Override
    //            public void onDeletionNotice(StatusDeletionNotice sdn) {
    //            }
    //
    //            @Override
    //            public void onTrackLimitationNotice(int i) {
    //            }
    //
    //            @Override
    //            public void onScrubGeo(long l, long l1) {
    //            }
    //
    //            @Override
    //            public void onException(Exception ex) {
    //            }
    //
    //            @Override
    //            public void onStallWarning(StallWarning arg0) {
    //                // TODO Auto-generated method stub
    //
    //            }
    //
    //        };

    RawStreamListener rawListener = new RawStreamListener() {
        @Override
        public void onMessage(String rawJSON) {
            //System.out.println(rawJSON);
            queue.offer(rawJSON);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance();

    //twitterStream.addListener(listener);
    twitterStream.addListener(rawListener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {

        twitterStream.sample();
    }

    else {

        FilterQuery query = new FilterQuery().track(keyWords);
        twitterStream.filter(query);
    }

}

From source file:com.stronquens.amgtwitter.ControllerOAuth.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww. j  av  a2  s .c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Parametros del request
        HttpSession sesion = request.getSession();
        String verifier = request.getParameter("verifier");
        String op = request.getParameter("op");

        // Definimos variables
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        Twitter OAuthTwitter = null;
        String url = null;

        // Devolemos la url generada          
        if ((verifier == null || verifier == "") && "url".equalsIgnoreCase(op)) {
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                    .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
            OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
            sesion.setAttribute("twitter", OAuthTwitter);
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                sesion.setAttribute("requestToken", requestToken);
                url = requestToken.getAuthenticationURL();
                out.println("{\"url\":\"" + url + "\"}");
            } catch (TwitterException ex) {
            }
        }

        // Devolvemos el acces token generado
        if (verifier != null && verifier.length() > 0) {
            OAuthTwitter = (Twitter) sesion.getAttribute("twitter");
            requestToken = (RequestToken) sesion.getAttribute("requestToken");
            accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, verifier);
            sesion.setAttribute("accesToken", accessToken);
            sesion.removeAttribute("twitter");
            sesion.removeAttribute("requestToken");
            out.println("{\"token\":\"" + accessToken.getToken() + "\",\"secret\":\""
                    + accessToken.getTokenSecret() + "\"}");
        }

    }
}

From source file:com.stronquens.amgtwitter.ControllerTwitter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w  .  ja v a2s. co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Obtenemos parametros de la peticion
        String op = request.getParameter("op");
        String accesToken = request.getParameter("token");
        String accesTokenSecret = request.getParameter("secret");

        // Inicializamos variables
        String jsonResult = "";
        Twitter twitter = null;
        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create();

        // Se crea la instancia de twitter segun los parametros de ususario
        if (!"".equalsIgnoreCase(accesToken) && !"".equalsIgnoreCase(accesTokenSecret)) {
            try {
                configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                        .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW")
                        .setOAuthAccessToken(accesToken).setOAuthAccessTokenSecret(accesTokenSecret);
                twitter = new TwitterFactory(configBuilder.build()).getInstance();
            } catch (Exception e) {
                System.out.println(e);
            }
        } else {
            try {
                configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                        .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
                twitter = new TwitterFactory(configBuilder.build()).getInstance();
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        // Se realizan las diferentes operaciones
        switch (op) {
        case "timeline":
            try {
                Paging pagina = new Paging();
                pagina.setCount(25);
                ResponseList listado = twitter.getHomeTimeline(pagina);
                jsonResult = gson.toJson(listado);
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        case "usersettings":
            try {
                jsonResult = gson.toJson(twitter.showUser(twitter.getId()));
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        case "pruebas":
            try {
                jsonResult = gson.toJson(twitter.showUser(twitter.getId()));
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        default:
            jsonResult = "{\"eror\":\"la operacion no existe\"}";
        }
        // Se devuelven los valores
        out.println(jsonResult);
    }
}

From source file:com.telefonica.iot.cygnus.sources.TwitterSource.java

License:Open Source License

@Override
public void configure(Context context) {
    consumerKey = context.getString("consumerKey");
    consumerSecret = context.getString("consumerSecret");
    accessToken = context.getString("accessToken");
    accessTokenSecret = context.getString("accessTokenSecret");

    LOGGER.info("Consumer Key:        '" + consumerKey + "'");
    LOGGER.info("Consumer Secret:     '" + consumerSecret + "'");
    LOGGER.info("Access Token:        '" + accessToken + "'");
    LOGGER.info("Access Token Secret: '" + accessTokenSecret + "'");

    String southWestLatitude;//from w  w  w  .  ja v a 2  s.  co  m
    String southWestLongitude;
    String northEastLatitude;
    String northEastLongitude;
    String keywords;

    //Top-left coordinate
    southWestLatitude = context.getString("south_west_latitude");
    southWestLongitude = context.getString("south_west_longitude");
    LOGGER.info("South-West coordinate: '" + southWestLatitude + " " + southWestLongitude + "'");

    //Bottom-right coordinate
    northEastLatitude = context.getString("north_east_latitude");
    northEastLongitude = context.getString("north_east_longitude");
    LOGGER.info("North-East coordinate: '" + northEastLatitude + " " + northEastLongitude + "'");

    keywords = context.getString("keywords");
    LOGGER.info("Keywords:            '" + keywords + "'");

    if (southWestLatitude != null && southWestLongitude != null && northEastLatitude != null
            && northEastLongitude != null) {
        double latitude1 = Double.parseDouble(southWestLatitude);
        double longitude1 = Double.parseDouble(southWestLongitude);

        double latitude2 = Double.parseDouble(northEastLatitude);
        double longitude2 = Double.parseDouble(northEastLongitude);

        boundingBox = new double[][] { new double[] { longitude1, latitude1 }, // south-west
                new double[] { longitude2, latitude2 } // north-east
        };

        LOGGER.info("Coordinates:         '" + boundingBox[0][0] + " " + boundingBox[0][1] + " "
                + boundingBox[1][0] + " " + boundingBox[1][1] + "'");
        haveFilters = true;
        haveCoordinateFilter = true;
    }

    if (keywords != null) {
        if (keywords.trim().length() != 0) {
            splitKeywords = keywords.split(",");
            for (int i = 0; i < splitKeywords.length; i++) {
                splitKeywords[i] = splitKeywords[i].trim();
            }

            LOGGER.info("keywords:            {}", Arrays.toString(splitKeywords));
            haveFilters = true;
            haveKeywordFilter = true;
        }
    }

    maxBatchSize = context.getInteger("maxBatchSize", maxBatchSize);
    maxBatchDurationMillis = context.getInteger("maxBatchDurationMillis", maxBatchDurationMillis);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);

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

}

From source file:com.thesmartweb.swebrank.TwitterAnalysis.java

License:Apache License

/**
 * Method to get tweets regarding a string 
 * @param query_string the string to search for
 * @param config_path the directory with the twitter api key
 * @return the tweets in a string/*w  w  w  .java  2  s  . com*/
 */
public String perform(String query_string, String config_path) {
    try {
        List<String> twitterkeys = GetKeys(config_path);
        //configuration builder in order to set the keys of twitter
        ConfigurationBuilder cb = new ConfigurationBuilder();
        String consumerkey = twitterkeys.get(0);
        String consumersecret = twitterkeys.get(1);
        String accesstoken = twitterkeys.get(2);
        String accesstokensecret = twitterkeys.get(3);
        cb.setDebugEnabled(true).setOAuthConsumerKey(consumerkey).setOAuthConsumerSecret(consumersecret)
                .setOAuthAccessToken(accesstoken).setOAuthAccessTokenSecret(accesstokensecret);
        TwitterFactory tf = new TwitterFactory(cb.build());
        AccessToken acc = new AccessToken(accesstoken, accesstokensecret);

        Twitter twitter = tf.getInstance(acc);

        //query the twitter
        Query query = new Query(query_string);
        int rpp = 100;
        query.count(rpp);
        query.setQuery(query_string);

        //----------get the tweets------------
        QueryResult result = twitter.search(query);
        List<Status> tweets = result.getTweets();

        RateLimitStatus rls = result.getRateLimitStatus();

        String tweet_txt = "";
        for (Status tweet : tweets) {
            tweet_txt = tweet_txt + " " + tweet.getText();
        }
        DataManipulation txtpro = new DataManipulation();
        Stopwords st = new Stopwords();
        tweet_txt = txtpro.removeChars(tweet_txt);
        tweet_txt = st.stop(tweet_txt);
        tweet_txt = txtpro.removeChars(tweet_txt);
        return tweet_txt;
    } catch (TwitterException ex) {
        String tweet_txt = "";
        Logger.getLogger(TwitterAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return tweet_txt = "fail";
    }
}

From source file:com.twasyl.slideshowfx.server.service.TwitterService.java

License:Apache License

@Override
public void start() {
    final Map twitter = this.vertx.sharedData().getMap(SlideshowFXServer.SHARED_DATA_TWITTER);
    final String hashtag = (String) twitter.get(SlideshowFXServer.SHARED_DATA_TWITTER_HASHTAG);

    this.twitterConfiguration = new ConfigurationBuilder().setOAuthConsumerKey("5luxVGxswd42RgTfbF02g")
            .setOAuthConsumerSecret("winWDhMbeJZ4m66gABqpohkclLDixnyeOINuVtPWs").build();

    if (hashtag != null && !hashtag.isEmpty()) {
        this.connect();
        this.accessToken.addListener((value, oldValue, newValue) -> {
            if (newValue != null) {
                FilterQuery query = new FilterQuery();
                query.track(new String[] { hashtag });

                this.twitterStream = new TwitterStreamFactory(this.twitterConfiguration)
                        .getInstance(this.accessToken.get());
                this.twitterStream.addListener(this.buildTwitterStreamListener());
                this.twitterStream.filter(query);
            }//  w ww . jav a2s. co  m
        });
    }
}

From source file:com.tweet.HelperMethods.java

License:Apache License

public static void postToTwitter(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);//from w  ww.  jav a2 s.co  m
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {
                Calendar cal = Calendar.getInstance();

                twitter.updateStatus(message + "\n@" + cal.getTime().toString());
            } catch (TwitterException e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.tweet.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);//  www.  j a v a 2s.c o m
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    //final File file = new File(imageUrl);

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {

                if (StaticData.graphFile.exists()) {
                    Calendar cal = Calendar.getInstance();

                    StatusUpdate status = new StatusUpdate(message + "\n@" + cal.getTime().toString());
                    status.setMedia(StaticData.graphFile);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.tweet.LoginActivity.java

License:Apache License

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

    new Thread(new Runnable() {
        @Override//  ww w.j a  v  a2s . c o 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() {
                        mAlertBuilder.cancel();
                        Toast.makeText(LoginActivity.this, errorString.toString(), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
                return;
            }

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

From source file:com.TweetExtractor.java

/**
 * */*from   w  ww.j a v a  2  s .c  om*/
 * Method to set up the API keys for the configuration builder
 */
private void buildConfiguration() throws IOException, SAXException, ParserConfigurationException {
    cb = new ConfigurationBuilder();
    Logger.getLogger(TweetExtractor.class).debug("Building Configuration");

    String consumerKey = "9Rk0BvBYIUZB4LiKZWmx00Dpl";
    String consumerSecret = "QmLCDeGkKgbpmxVQzFnAJoq2Wpgw3uj0AdE8VxvQRCymzSvCct";
    String accessToken = "1602877004-upomW5DK5e8BSUdhU7OW9mQzBBr05AqCbDxEzuQ";
    String accessTokenSecret = "aBaklu0v1iu4WidpqpulPjT6I8VqHOYHurTSgWK8aPcEi";
    maxTweets = 50;
    // userToSearch="dulsrazz";

    if (consumerKey == null || consumerSecret == null || accessToken == null || accessTokenSecret == null) {

        throw new NullPointerException("TWitter API Keys not set");
    }

    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
}