Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

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

Prototype

public Configuration build() 

Source Link

Usage

From source file:setting.TwitterToken.java

public static TwitterFactory getTwitterFactory() {
    TwitterFactory tf = null;// ww w  .j  ava  2s  .  c om
    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("Kb8ND2PPNcQoJSEdh2pA")
                .setOAuthConsumerSecret("vb1tSs2CRUZQUkfKDRCDAEqO1JUpSvBU7vtW3Al52IY")
                .setOAuthAccessToken("88373110-NaKga9zqHgI3t9gxWxlUQ8od8VakHtHqupLX8BKmS")
                .setOAuthAccessTokenSecret("vKp9xuT3XQWeCZ3VfgnoAeKmtqaBVB7yjpLxZJmAEgdgX");
        tf = new TwitterFactory(cb.build());
    } catch (Exception e) {
        System.err.println(" Exception occure in Twitter getTwitterFactory " + e);
    }
    return tf;

}

From source file:Situational_Awareness.TwitterSearch.java

public TwitterSearch() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("XQj7G52yevzl0pBkySy3UzvzR")
            .setOAuthConsumerSecret("yfsTeuPGbbX6pSvIiiOazx2E9vkuoCm1qBYT7Jvek9I5C9BPr3")
            .setOAuthAccessToken("4713593925-gOovKDZzZ5bmk6hX8CIqwmosVx6EcKQ4uxqoeVD")
            .setOAuthAccessTokenSecret("43YMSb8LRb6O7Fk0rS5vLSEzGXJ0WUCcPknpG0erSfoLb");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();/*from   ww w.  j av  a2  s.  c om*/
}

From source file:social.controller.PostToSocial.java

@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    boolean face = false;
    boolean twit = false;
    try {//w  w  w. j av  a  2 s  .com
        getSqlMethodsInstance().session = request.getSession();
        Integer user_id = (Integer) getSqlMethodsInstance().session.getAttribute("UID");
        String htmlString = (String) getSqlMethodsInstance().session.getAttribute("htmlString");
        String isFacebook = request.getParameter("isFacebook");
        String isTwitter = request.getParameter("isTwitter");
        String getImageFile = request.getParameter("imageToPost");
        String getFile = request.getParameter("imagePost");
        String url = request.getParameter("url");

        String file_image_path = AppConstants.LAYOUT_IMAGES_HOME + File.separator + getImageFile;

        //            String file_image_path = getServletContext().getRealPath("") + "/temp/"+getImageFile;
        String imagePostURL = ServletUtil.getServerName(request.getServletContext());
        //String imagePostURL = AppConstants.LAYOUT_IMAGES_HOME + getImageFile;
        if (isFacebook.equalsIgnoreCase("true")) {

            String accessToken = request.getParameter("accesstoken");
            String posttext = request.getParameter("postText");
            String title = request.getParameter("title");
            String description = request.getParameter("description");
            String url1 = request.getParameter("url");

            facebook = new FacebookFactory().getInstance();
            facebook.setOAuthAppId("592852577521569", "a87cc0c30d792fa5dd0aaef6b43994ef");
            facebook.setOAuthPermissions("publish_actions, publish_pages,manage_pages");
            //            File file = new File(file_image_path);
            facebook.setOAuthAccessToken(new AccessToken(accessToken));

            if (title == "") {

                Media media = new Media(new File(file_image_path));
                PhotoUpdate update = new PhotoUpdate(media);
                update.message(posttext);
                facebook.postPhoto(update);
            } else {
                logger.info(title);
                PostUpdate post = new PostUpdate(posttext).picture(new URL(
                        imagePostURL + "DownloadImage?image_type=LAYOUT_IMAGES&image_name=" + getImageFile))
                        .name(title).link(new URL(url1)).description(description);
                facebook.postFeed(post);
            }
            try {

                getSqlMethodsInstance().setSocialPostHistory(user_id, htmlString, false, true, getImageFile);
            } catch (Exception ex) {
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getCause());
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getMessage());
            }
        }
        if (isTwitter.equalsIgnoreCase("true")) {

            try {

                AccessToken accTok = null;
                String shortUrl = "";
                ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
                twitterConfigBuilder.setDebugEnabled(true);
                twitterConfigBuilder.setOAuthConsumerKey("K7TJ3va8cyAeh6oN3Hia91S2o");
                twitterConfigBuilder
                        .setOAuthConsumerSecret("IWUt2aDVTHgUc8N0qI0cF1Z1dTAEQ7CSgnBymZNr3BPSmtkNHL");
                twitterConfigBuilder.setOAuthAccessToken(request.getParameter("twittweraccestoken"));
                twitterConfigBuilder.setOAuthAccessTokenSecret(request.getParameter("twitterTokenSecret"));

                Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
                String statusMessage = request.getParameter("text").replace("bit.ly/1XOkJo", "");
                shortUrl = request.getParameter("shorturl");
                if (shortUrl.length() > 0) {
                    String StatusMessageWithoutUrl = statusMessage.substring(0, statusMessage.length());
                    if (StatusMessageWithoutUrl.length() + shortUrl.length() < 140) {
                        statusMessage = StatusMessageWithoutUrl + " " + shortUrl;
                    } else {
                        int urlLength = shortUrl.length() + 1;
                        int statusLength = 115 - urlLength;
                        statusMessage = StatusMessageWithoutUrl.substring(0, statusLength);
                        statusMessage = statusMessage + " " + shortUrl;
                    }
                }
                File file = new File(file_image_path);
                int count = statusMessage.length();
                StatusUpdate status = new StatusUpdate(statusMessage);
                // set the image to be uploaded here.

                status.setMedia(file);
                twitter.updateStatus(status);
                try {
                    getSqlMethodsInstance().setSocialPostHistory(user_id, htmlString, false, true,
                            getImageFile);
                } catch (Exception ex) {
                    Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getCause());
                    Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getMessage());
                }

            } catch (TwitterException te) {

                PrintWriter out1 = response.getWriter();
                out1.println("Twitter Exception: " + te.getMessage());
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, te.getCause());
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, te.getMessage());

            } catch (Exception e) {
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e);
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getMessage());
            }

        }
    } catch (FacebookException e) {
        Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getCause());
        Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getMessage());
    }
}

From source file:socialImport.twitter.TwitterImportFactory.java

License:Open Source License

/**
 * Initializes the TwitterImport-Module with the given parameters
 * /*  w  w  w .  j  av  a  2 s  .  c o m*/
 * @param oAuthConsumerKey The oAuthConsumerKey as generated by Twitter.
 * @param oAuthConsumerSecret The oAuthConsumerSecret as generated by Twitter.
 * @param oAuthAccessToken The oAuthAccessToken as generated by Twitter.
 * @param oAuthAccessTokenSecret The oAuthAccessTokenSecret as generated by Twitter.
 * @param debugEnabled Whether the Twitter4J-Library should print debugMessages to the console or not.
 * @param dataModule A reference to the systems Data-Module.
 * 
 * */
public ITwitterImport getInstance(String oAuthConsumerKey, String oAuthConsumerSecret, String oAuthAccessToken,
        String oAuthAccessTokenSecret, boolean debugEnabled, IData dataModule) {

    ConfigurationBuilder configBuilder = new ConfigurationBuilder();
    configBuilder.setDebugEnabled(debugEnabled).setOAuthConsumerKey(oAuthConsumerKey)
            .setOAuthConsumerSecret(oAuthConsumerSecret).setOAuthAccessToken(oAuthAccessToken)
            .setOAuthAccessTokenSecret(oAuthAccessTokenSecret).setJSONStoreEnabled(true);

    if (debugEnabled) {
        System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.StdOutLoggerFactory");
    } else {
        System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.NullLoggerFactory");
    }

    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(configBuilder.build());

    return new TwitterImport(twitterStreamFactory, dataModule);
}

From source file:SocialMedia.CTwitter.java

public CTwitter() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("pHLUEo8VqYL1YJfXCwFoUumf2")
            .setOAuthConsumerSecret("7HWGZid7bNewVQjQbLt8MtSD8QLcBMOv8rfQ5Y6Bd8riIpkYf7")
            .setOAuthAccessToken("2855061284-40lddUpxDf46zlEZsiLMMekBU5r6L8dJFX3Lsfy")
            .setOAuthAccessTokenSecret("0TDs0JBRkA8CnY6YAavehMuvmuMRriM65BtTp6vptvNry");

    objTwitter = new TwitterFactory(cb.build()).getInstance();

}

From source file:source.TwitterSource.java

License:Apache License

/**
 * The initialization method for the Source. The context contains all the
 * Flume configuration info, and can be used to retrieve any configuration
 * values necessary to set up the Source.
 *
 * @param context Key-value store used to pass configuration information
 * throughout the system./*from  ww  w.ja v a  2  s .co  m*/
 */
@Override
public void configure(Context context) {

    consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY);
    consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET);
    accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN);
    accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET);

    String swString = context.getString(TwitterSourceConstants.SW_LNG_LAT);
    String neString = context.getString(TwitterSourceConstants.NE_LNG_LAT);
    if (swString != null && neString != null) {
        String[] sw = swString.split(",");
        String[] ne = neString.split(",");
        if (sw.length == 2 && ne.length == 2) {
            for (int i = 0; i < 2; i++) {
                locations[0][i] = Double.parseDouble(sw[i].trim());
                locations[1][i] = Double.parseDouble(ne[i].trim());
            }
        } else {
            locations = null;
        }
    } else {
        locations = null;
    }

    String keywordString = context.getString(TwitterSourceConstants.KEYWORDS);
    if (keywordString != null) {
        keywords = keywordString.split(",");
        for (int i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
        }
    }

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

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

}

From source file:stream.PrintUserStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    ConfigurationBuilder confbuilder = new ConfigurationBuilder();
    confbuilder.setOAuthAccessToken(TWITTER_ACCESS_TOKEN).setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET)
            .setOAuthConsumerKey(TWITTER_CONSUMER_KEY).setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
    confbuilder.setJSONStoreEnabled(true);

    TwitterStream twitterStream = new TwitterStreamFactory(confbuilder.build()).getInstance();
    //        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    // user() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.user();/*from  ww w . ja  v  a  2s  .c o m*/
}

From source file:stream.Sample.java

License:Apache License

/**
 * @param args/* ww w . java 2 s  . com*/
 */
public static void main(String[] args) {

    // Check how many arguments were passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("Please provide output directory path");
        System.exit(-1);
    }

    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    dataStoreManager();

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            // System.out.println(status.getUser().getName() + " : " +
            // status.getText());
            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            // System.out.println(rawJSON);
            writer.println(rawJSON);
            counter++;
            System.out.println(counter);
            if (counter >= 1000) {
                dataStoreManager();
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onException(Exception ex) {
        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    // mozellecandi
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("****").setOAuthConsumerSecret("****")
            .setOAuthAccessToken("****").setOAuthAccessTokenSecret("****").setJSONStoreEnabled(true);

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    twitterStream.addListener(listener);
    // sample() method internally creates a thread which manipulates
    // TwitterStream and calls these adequate listener methods continuously.
    twitterStream.sample();

}

From source file:streamflow.spout.twitter.TwitterSampleSpout.java

License:Apache License

@Override
public void open(Map config, TopologyContext context, SpoutOutputCollector collector) {
    this.collector = collector;

    logger.info(/*  www.j a  va2 s.c o m*/
            "Twitter Sampler Started: Consumer Key = " + consumerKey + ", Consumer Secret = " + consumerSecret
                    + ", Access Token = " + accessToken + ", Access Token Secret = " + accessTokenSecret);

    if (StringUtils.isNotBlank(consumerKey) && StringUtils.isNotBlank(consumerSecret)
            && StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(accessTokenSecret)) {
        // Build the twitter config to authenticate the requests
        ConfigurationBuilder twitterConfig = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey)
                .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
                .setOAuthAccessTokenSecret(accessTokenSecret).setJSONStoreEnabled(true)
                .setIncludeEntitiesEnabled(true).setIncludeEntitiesEnabled(true);

        // Add the proxy settings to the Twitter config if they were specified
        if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
            try {
                twitterConfig.setHttpProxyPort(proxyPort).setHttpProxyHost(proxyHost);
            } catch (Exception ex) {
            }
        }

        // Status listener which handle the status events and add them to the queue
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                queue.offer(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                logger.debug("Twitter Deletion Notice: " + statusDeletionNotice.getUserId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                logger.debug("Twitter On Track Limitation Notice: Number Of Limited Statuses"
                        + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                logger.debug("Twitter Scrub Geo: UserID = " + userId + ", UpToStatusId = " + upToStatusId);
            }

            @Override
            public void onException(Exception exception) {
                logger.debug("Twitter Exception: " + exception.getMessage());
            }

            @Override
            public void onStallWarning(StallWarning stallWarning) {
                logger.debug("Twitter Stall Warning: " + stallWarning.toString());
            }
        };

        TwitterStreamFactory twitterFactory = new TwitterStreamFactory(twitterConfig.build());
        twitterStream = twitterFactory.getInstance();
        twitterStream.addListener(listener);
        twitterStream.sample();

        logger.info("Twitter Sample Stream Initialized");

    } else {
        logger.info("Twitter Sampler missing required OAuth properties. "
                + "Pleast check your settings and try again.");
    }
}

From source file:StringMatching.GetTweet.java

/**
 * @param args the command line arguments
 *///w w w .  j  a  va2 s .c  o m
public static void main(String[] args) throws JSONException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH")
            .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK")
            .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA")
            .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC")
            .setHttpProxyHost("cache.itb.ac.id").setHttpProxyPort(8080).setHttpProxyUser("jonathan.benedict")
            .setHttpProxyPassword("rollingonthefloor");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    JSONObject obj = new JSONObject();
    int counterTweet = 0;
    FileWriter file = new FileWriter("C:\\Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt");
    file.flush();
    try {
        Query query = new Query("barca".toLowerCase());
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                counterTweet++;
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                obj.put("user", tweet.getUser().getScreenName());
                obj.put("tweets", tweet.getText());

                //Tulis file ke dalam txt

                try {
                    file.write(obj.toString());
                    System.out.println("Successfully Copied JSON Object to File...");
                    System.out.println("\nJSON Object: " + obj);

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        } while (counterTweet < 1000);

        file.close();
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    System.exit(0);
}