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:SentimentAnalyses.PrintSampleStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {

    final PrintSampleStream pr = new PrintSampleStream();

    try {/*  w  w  w. j av  a2  s .  co  m*/
        pr.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Em3WTI7jc90HcvKzPkTLQ")
            .setOAuthConsumerSecret("vg4p6rOF32bmffqRR8m0jAUClrxvtGiMB5PrSr3Zsw")
            .setOAuthAccessToken("1681973072-1q0zI0VPjHD3ttNuaBOL94frzCI9sXInxAcDK0w")
            .setOAuthAccessTokenSecret("ZRLkOyjmhHBkU1iNyEVNyIgIBsKrl0DUDKOcOMneYFYEM");
    cb.setJSONStoreEnabled(true);

    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    TwitterStream twitterStream = tf.getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            //System.out.println(status);
            String str = DataObjectFactory.getRawJSON(status);
            try {
                //JSONObject nnstr = new JSONObject(newstr);
                DBObject dbObject = (DBObject) JSON.parse(str);
                //                    System.out.println(dbObject);
                pr.collection.insert(dbObject);
                //System.out.println(dbObject);
                pr.count++;
                if (pr.count % 1000 == 0)
                    System.out.println(pr.count);
                if (pr.count > 100000) {
                    pr.mongo.close();
                    System.exit(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

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

    String[] trackArray;
    String[] Track = { "Malaysia Airlines", "Flight MH370", "Boeing-777", "Kuala Lumpur", "Bei jing" };
    //trackArray[0] = "Obama";
    //trackArray[1] = "Romney";

    FilterQuery filter = new FilterQuery();
    filter.track(Track);
    String[] lang = { "en" };
    filter.language(lang);
    twitterStream.filter(filter);
    //pr.mongo.close();
}

From source file:sentimentanalysis.Twitter.Twitter4JConfig.java

public ConfigurationBuilder getConfigurationBuilder() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
            .setOAuthAccessToken(ACCESS_KEY).setOAuthAccessTokenSecret(ACCESS_SECRET);
    return cb;//from   www .j a va 2 s. c  om
}

From source file:Servlet.TwitterAuthServlet.java

License:Apache License

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   w ww. j a  va2 s .co  m*/
 * @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");

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(TwitterApp.CONSUMER_KEY);
    cb.setOAuthConsumerSecret(TwitterApp.CONSUMER_SECRET);

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        System.out.println(callbackURL);

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());

        System.out.println("Authentication " + requestToken.getAuthenticationURL());
        System.out.println("Authorization " + requestToken.getAuthorizationURL());

        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:servlets.TwitterConnectionServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("Start TwitterConnectionServlet.doGet");

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(UtilTwitter.CONSUMER_KEY);
    builder.setOAuthConsumerSecret(UtilTwitter.CONSUMER_SECRET);

    TwitterFactory factory = new TwitterFactory(builder.build());
    Twitter twitter = factory.getInstance();

    RequestToken requestToken;//ww w. ja  va  2s .co m

    try {
        requestToken = twitter.getOAuthRequestToken(UtilTwitter.CALL_BACK_URL);
        String url = requestToken.getAuthenticationURL();

        System.out.println("End TwitterConnectionServlet.doGet");
        response.sendRedirect(url);
    } catch (TwitterException e) {
        e.printStackTrace();
    }
}

From source file:setting.TwitterToken.java

public static Twitter twitterObject() {
    Twitter twitter = null;//  w  ww .j  a  v a 2  s .  co m
    try {

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("Kb8ND2PPNcQoJSEdh2pA")
                .setOAuthConsumerSecret("vb1tSs2CRUZQUkfKDRCDAEqO1JUpSvBU7vtW3Al52IY")
                .setOAuthAccessToken("88373110-NaKga9zqHgI3t9gxWxlUQ8od8VakHtHqupLX8BKmS")
                .setOAuthAccessTokenSecret("vKp9xuT3XQWeCZ3VfgnoAeKmtqaBVB7yjpLxZJmAEgdgX");
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
        System.out.println(twitter);

    } catch (Exception e) {
        System.out.println(e);
    }
    return twitter;
}

From source file:setting.TwitterToken.java

public static TwitterFactory getTwitterFactory() {
    TwitterFactory tf = null;// w  w  w.  j  a va2s  .c o  m
    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:site_streaming.SiteStream.java

License:Apache License

public static void main(String[] args) throws Exception {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET)
            .setSiteStreamBaseURL("https://sitestream.twitter.com/1.1/site.json").build();

    TwitterStream SiteStream = new TwitterStreamFactory(configuration).getInstance();
    SiteStream.addListener(new MyStatusListener());

    long[] follow = { 1598997848 };//anondroid3?id:1598997848
    FilterQuery filter = new FilterQuery(follow);//?userID?????
    SiteStream.filter(filter);//www  .  j  a v  a2s . c o  m
}

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 .ja  v  a 2  s .co  m*/
}

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 {//from   w w  w .  j  a v  a  2 s .co m
        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
 * //ww  w  .  ja v a 2s. 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);
}