Example usage for twitter4j.conf ConfigurationBuilder setOAuthAccessToken

List of usage examples for twitter4j.conf ConfigurationBuilder setOAuthAccessToken

Introduction

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

Prototype

public ConfigurationBuilder setOAuthAccessToken(String oAuthAccessToken) 

Source Link

Usage

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();// ww  w  . java 2 s .co  m
}

From source file:traffickarmasent.newgetpage.java

public static void main(String[] args) throws IOException {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {//from w w w  .  j av a2  s . c  om
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);
        cb.setOAuthConsumerKey("GPtsu5cjC08KTOEojEoaHw");
        cb.setOAuthConsumerSecret("SsgeXn73bN4CXUYtJfEdKOwBxVTmAEPvmFo3q2CX45w");
        cb.setOAuthAccessToken("154196958-J1Gqy86jmQ6YSoFVVq69bmbJB0acGxiDEocxtvre");
        cb.setOAuthAccessTokenSecret("DpTJr3huuDy2qMwsCMgsTn5yNbi0oQzSDGhDDWQsLog");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter1 = tf.getInstance();
        List<Status> statuses;
        String user;
        String[] users = { "livetrafficsyd", "trafficnsw", "sydtraffic_cs", "WazeTrafficSYD",
                "livetrafficnsw" };
        Date[] d_users = { new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12),
                new Date(99, 2, 12) };

        while (true) {
            for (int i = 0; i < users.length; i++) {

                statuses = twitter1.getUserTimeline(users[i]);

                for (int j = statuses.size() - 1; j >= 0; j--) {
                    Status st = statuses.get(j);
                    if (d_users[i].before(st.getCreatedAt())) {
                        String message = removeUrl(st.getText());

                        File file = new File("out_sydney_new.txt");

                        //if file doesnt exists, then create it
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        //true = append file
                        FileWriter fileWritter = new FileWriter(file.getName(), true);
                        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
                        bufferWritter.write(message + "\n");
                        bufferWritter.close();

                        System.out.println("Done");

                        System.out.println("@" + st.getUser().getScreenName() + " - " + st.getText());
                        d_users[i] = st.getCreatedAt();
                    }
                }
            }
            try {
                Thread.sleep(300000); //1000 milliseconds is one second.
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            System.out.println("firse");

        }

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:traffickarmasent.TweetCollection.java

public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    // loading slang dictionary with key as slang and value as its full form
    slangMap = new HashMap<String, String>();
    BufferedReader slangRead = new BufferedReader(new FileReader("extras/out.txt"));
    String line = "";
    while ((line = slangRead.readLine()) != null) {
        String parts[] = line.split("\t");
        slangMap.put(parts[0], parts[1]);
    }/*from   w ww  . j  a  va2 s. c  om*/
    slangRead.close();

    //loading entity list
    BufferedReader htm_in = new BufferedReader(new FileReader("extras/html_ent.txt"));
    entityList = new ArrayList<String>();
    while ((line = htm_in.readLine()) != null) {
        entityList.add(line);
    }
    FileInputStream fos1 = new FileInputStream(new File("extras/hash1.dat")); // loading emoticon dictionary, with key as emoticon and value as its sentiment score
    ObjectInputStream out1 = new ObjectInputStream(fos1);
    emohash1 = (HashMap<String, Double>) out1.readObject();
    //System.out.println(hm1);

    FileInputStream fos2 = new FileInputStream(new File("extras/hash2.dat")); // loading emoticon dictionary, with key as emoticon and value as its sentiment score
    ObjectInputStream out2 = new ObjectInputStream(fos2);
    emohash2 = (HashMap<String, Double>) out2.readObject();
    //System.out.println(hm2);

    //loading senti-wordnet
    FileReader fr2 = new FileReader("extras/SentiWordNet_scores_final.txt");
    BufferedReader br2 = new BufferedReader(fr2);
    String str2;
    senti_map = new HashMap<String, Double>();
    while ((str2 = br2.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(str2, "^");
        senti_map.put(st.nextToken(), Double.parseDouble(st.nextToken()));
    }

    String serializedClassifier = "english.all.3class.distsim.crf.ser.gz"; //NER configuration
    AbstractSequenceClassifier classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier);
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();

    MaxentTagger tagger = new MaxentTagger("taggers/english-left3words-distsim.tagger");

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("ufulV3imKoYNzdh58LotTC1YD");
    cb.setOAuthConsumerSecret("2A781ma736HTenAXXYn9tRIelQYJkbCqY0GLi7W71ZwwDmNU59");
    cb.setOAuthAccessToken("2564905075-MY9osfHabaRnonQVHHhHeA1vCLSOhuHWjBNBiIY");
    cb.setOAuthAccessTokenSecret("JsD8Woc7iiFiDSwoCwjNAb6KNEurz7tBqSj9pJV8WXabr");
    twitter4j.TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener = new StatusListener() {
        double score = 0.0;
        double count = 0;
        ArrayList<String> locArray = new ArrayList<String>();

        @Override

        public void onStatus(Status status) {
            String text = status.getText();

            double geoLat = 0.0;
            double geoLng = 0.0;
            String tweetId = status.getId() + "";
            String userName = status.getUser().getName();
            String userId = status.getUser().getId() + "";
            if (status.getGeoLocation() != null) {
                geoLat = status.getGeoLocation().getLatitude();
                geoLng = status.getGeoLocation().getLongitude();
            }

            tweetClean(text, status.getGeoLocation());
            System.out.println(text + "\n" + tweetId + " " + userName + " " + userId);

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onException(Exception excptn) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        public void tweetClean(String message, GeoLocation loc) {
            try {

                // URL removal 
                message = removeUrl(message);
                System.out.println("lalala" + message);
                //removing user mentions
                message = userMentions(message);
                //slang removal
                String[] acro = slangRemoval(message);
                //entity removal
                String[] finaldata = entityRemoval(acro);
                message = "";
                for (String word : finaldata) {
                    message += word + " ";
                }
                //System.out.println(message);
                //Ner Taggging
                String XmlData = classifier.classifyWithInlineXML(message);
                message = XmlData;

                //handling words to the spell_checked
                String[] data = message.split("<");
                String val = "";
                for (String word : data) {
                    if (word.startsWith("PER") || word.startsWith("LOC")) {
                        word = word.replaceAll("PERSON>", "");
                        word = word.replaceAll("/PERSON>", "");
                        word = word.replaceAll("LOCATION>", "");
                        word = word.replaceAll("/LOCATION>", "");
                        //insert word into database here 
                        locArray.add(word);
                    } else {
                        word = word.replaceAll("/PERSON>", "");
                        word = word.replaceAll("/LOCATION>", "");
                        //System.out.println(word);
                        val += word;
                    }
                }
                //System.out.println("see" + val);
                if (loc != null || locArray.size() > 0) {
                    val = val.replaceAll("\\s+", " ");
                    String[] temp = val.split(" ");
                    String match = "";
                    //spell_check
                    for (String word : temp) {
                        //System.out.println(word);
                        if (emohash2.containsKey(word)) {
                            score += emohash2.get(word);
                            count++;
                            message = message.replace(word, "");
                        }
                        Process p = Runtime.getRuntime().exec("python extras/text_blob.py " + word);
                        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        //System.out.println(in.readLine());
                        match = in.readLine();
                        //match = spell_check(word);
                        //System.out.println(match);
                        if (!match.equals(word)) {
                            message = message.replaceAll(word, match);
                        }

                    }
                    System.out.println(message);
                    //UTF-8 emoji's
                    emojiDetection(message);
                    //handle NerTags
                    message = af_spellcheck(message);
                    //System.out.println(a);

                    //removing irrelevant chars         
                    message = removeChars(message);
                    //System.out.println(a);

                    //POS- TAGGING
                    message = posTagging(message);

                    // removing prepositions and nouns
                    message = removePrepn(message);
                    //System.out.println(a);

                    sentiScores(message);
                    System.out.println(score);
                    System.out.println(score / count);
                }

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

        }

        public String removeUrl(String message) {
            String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
            Pattern p = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(message);
            int i = 0;
            while (m.find()) {
                message = message.replaceAll(m.group(i), "").trim();
                i++;
            }
            return message;
        }

        public String af_spellcheck(String message) {

            message = message.replaceAll("<PERSON>", "");
            message = message.replaceAll("</PERSON>", "");
            message = message.replaceAll("<LOCATION>", "");
            message = message.replaceAll("</LOCATION>", "");
            return message;
        }

        public String removeChars(String message) {

            message = message.replaceAll("\\.", "");
            message = message.replaceAll("\\!", "");
            message = message.replaceAll("\\$", "");
            message = message.replaceAll("\\%", "");
            message = message.replaceAll("\\^", "");
            message = message.replaceAll("\\|", "");
            message = message.replaceAll("\\+", "");
            message = message.replaceAll("\\:", "");
            message = message.replaceAll("\\(", "");
            message = message.replaceAll("\\)", "");
            message = message.replaceAll("\\*", "");
            message = message.replaceAll("\\{", "");
            return message;
        }

        public void sentiScores(String message) {

            message = message.replaceAll("_NNS", "_n");
            message = message.replaceAll("_NN", "_n");
            message = message.replaceAll("_RBR", "_r");
            message = message.replaceAll("_RBS", "_r");
            message = message.replaceAll("_RB", "_r");
            message = message.replaceAll("_JJR", "_a");
            message = message.replaceAll("_JJS", "_a");
            message = message.replaceAll("_JJ", "_a");
            message = message.replaceAll("_VBD", "_v");
            message = message.replaceAll("_VBG", "_v");
            message = message.replaceAll("_VBN", "_v");
            message = message.replaceAll("_VBP", "_v");
            message = message.replaceAll("_VBZ", "_vs");
            message = message.replaceAll("_VB", "_v");

            message = message.replaceAll("\\s+", " ");
            // System.out.println(message);
            String[] senti_token = message.split(" ");

            for (String word : senti_token) {
                word = word.toLowerCase();
                System.out.println(word);
                if (senti_map.containsKey(word)) {

                    score += senti_map.get(word);
                    //System.out.println(score);
                    count++;
                }

            }

        }

        public void emojiDetection(String message) {
            Pattern emo = Pattern.compile("[\\uD83D\\uDE01-\\uD83D\\uDE4F]");
            Matcher m_emo = emo.matcher(message);
            while (m_emo.find()) {
                if (emohash1.containsKey(m_emo.group())) //System.out.println("llalala");
                {
                    score += emohash1.get(m_emo.group());
                }
                count++;
            }
        }

        public String userMentions(String message) {
            Pattern p = Pattern.compile("\\@\\w+");
            Matcher m = p.matcher(message);
            while (m.find()) {
                //System.out.println(m.group());
                message = message.replaceAll(m.group(), "");
            }
            return message;

        }

        public String[] slangRemoval(String message) {
            ArrayList<String> slangRemovalList = new ArrayList<String>();
            String[] words = message.split(" ");
            for (String single : words) {
                if (slangMap.containsKey(single.toUpperCase())) {
                    slangRemovalList.add(slangMap.get(single.toUpperCase()));
                } else {
                    slangRemovalList.add(single);
                }
            }
            String[] myArray = new String[slangRemovalList.size()];
            slangRemovalList.toArray(myArray);
            return myArray;
        }

        public String posTagging(String message) throws Exception {

            String tagged = tagger.tagString(message);

            return tagged;
        }

        public String removePrepn(String message) {
            String delims = " ";
            String[] tokens = message.split(delims);
            for (String word : tokens) {
                if (word.endsWith("_IN") || word.endsWith("_NNP") || word.endsWith("_NNPS")) {
                    message = message.replace(word, "");
                }

            }
            return message;
        }

        public String[] entityRemoval(String[] message) {
            List<String> finalList = new ArrayList<String>();
            for (String word : message) {
                if (!entityList.contains(word.trim())) {
                    finalList.add(word);
                }
            }
            String[] myArray = new String[finalList.size()];
            finalList.toArray(myArray);
            return myArray;
        }

    };
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "Mumbai traffic", "@TrafflineMUM", "TrafficMum", "MumbaiTrafficPol",
            "avoid traffic Mumbai", "Breakdown Mumbai traffic", "@smart_mumbaikar", "@TrafficBOM",
            "#StreetSmartWithTraffline mumbai", "#mumbai #TRAFFICALERT ", "#mumbai #TRAFFIC" };

    fq.track(keywords);
    twitterStream.addListener(listener);
    twitterStream.filter(fq);
}

From source file:twitfeedbot.BotherSomeoneServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Twitter twit;/*  w  w  w. j a v a  2s . c  o  m*/
    StringBuilder builder = new StringBuilder();
    User victim = null;
    long cursor = -1;
    long[] friendIDs, victimIDs;
    Random r = new Random();

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();

        Trends t = twit.getPlaceTrends(1); //global trends
        friendIDs = twit.getFollowersIDs(twit.getId(), cursor).getIDs();
        if (friendIDs.length == 0)
            resp.getWriter().println("Cannot find any followers to bother");
        else {
            victimIDs = twit.getFollowersIDs(friendIDs[r.nextInt(friendIDs.length)], cursor).getIDs();
            if (victimIDs.length == 0)
                resp.getWriter().println("Cannot find any followers to bother");
            else {
                victim = twit.showUser(victimIDs[r.nextInt(victimIDs.length)]);
                builder.append("@" + victim.getScreenName()).append(" ");
                //Append Wordnik example sentence
                builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                if (builder.length() > 140) //Tweets are maximum 140 characters
                {
                    if (builder.lastIndexOf(";", 110) > 0)
                        builder.setLength(builder.lastIndexOf(";", 110));
                    else if (builder.lastIndexOf(":", 110) > 0)
                        builder.setLength(builder.lastIndexOf(":", 110));
                    else if (builder.lastIndexOf(",", 110) > 0)
                        builder.setLength(builder.lastIndexOf(",", 110));
                    else
                        builder.setLength(110);
                }
                builder.append(" " + t.getTrends()[r.nextInt(t.getTrends().length)].getName());

                if (builder.length() > 140)
                    builder.setLength(140); //Tweets are limited to 140 characters

                twit.updateStatus(builder.toString());
                resp.getWriter().println("Tweet posted: " + builder.toString() + "<br>");
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitfeedbot.RespondServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ResponseList<Status> mentions;
    Twitter twit;//from www  .j av a 2s.  c  o m
    StringBuilder builder = new StringBuilder();
    long lastPostId = 0;

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity lastPostIdEntity;

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
        mentions = twit.getMentionsTimeline();

        lastPostIdEntity = datastore.get(KeyFactory.createKey("lastPostIDEntity", "ID"));
        lastPostId = Long.parseLong(lastPostIdEntity.getProperty("lastPostID").toString());

        if (mentions.size() == 0 || mentions.get(0).getId() == lastPostId)
            resp.getWriter().println("No mentions so far...<br>");
        else {
            resp.getWriter().println("Responding to mentions...<br>");
            for (Status mention : mentions) {
                builder.setLength(0); // Clear the String Builder
                if (lastPostId < mention.getId()) {
                    //Figure out how to like a reply with certain words (best fuck etc)
                    if (mention.getUser().getId() == twit.getId())
                        ;//don't respond to myself
                    else if (mention.isRetweeted())
                        ; //don't respond to retweet
                    else if (mention.getText().toLowerCase().contains("bye")) // Say goodbye
                    {
                        builder.setLength(0); // Clear the String Builder 
                        builder.append("@").append(mention.getUser().getScreenName()).append(" Ok. Bye");
                    } else {
                        builder.setLength(0); // Clear the String Builder
                        builder.append("@").append(mention.getUser().getScreenName());
                        builder.append(" ");

                        //Append Wordnik example sentence
                        builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                        if (builder.length() > 140) {
                            if (builder.lastIndexOf(";", 110) > 0)
                                builder.setLength(builder.lastIndexOf(";", 110));
                            else if (builder.lastIndexOf(":", 110) > 0)
                                builder.setLength(builder.lastIndexOf(":", 110));
                            else if (builder.lastIndexOf(",", 110) > 0)
                                builder.setLength(builder.lastIndexOf(",", 110));
                            else
                                builder.setLength(110);
                        }
                    }
                    twit.updateStatus(builder.toString());
                    resp.getWriter().println("Reply posted: " + builder.toString() + "<br>");
                    builder.delete(0, builder.length()); //Clear the builder
                }
            }
            //Save last post ID
            lastPostIdEntity.setProperty("lastPostID", (Long.toString(mentions.get(0).getId())));
            datastore.put(lastPostIdEntity);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (EntityNotFoundException e) {
        resp.getWriter().println("lastPostID not found. Creating...<br>");
        lastPostIdEntity = new Entity("lastPostIDEntity", "ID");
        //lastPostIdEntity.setProperty("lastPostID", 0);
        lastPostIdEntity.setProperty("lastPostID", "883352596160946176");
        datastore.put(lastPostIdEntity);

    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitfeedbot.UpdateStatusServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    StringBuilder builder = new StringBuilder(140);
    GetFeed feed = new GetFeed(feedsFile);
    Random r = new Random();

    resp.setContentType("text/plain; charset=UTF-8");

    try {/*from   w w w.  ja  v  a2s.  c o m*/
        resp.getWriter().println("Updating status...");
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();

        //Append feed title
        try {
            builder.append(feed.title()).append(separator[(r.nextInt(separator.length))]);
        } catch (FeedException e) {
            resp.getWriter().println("Problem with RSS Feed <br> <pre>");
            e.printStackTrace(resp.getWriter());
        }

        //Append Wordnik example sentence
        builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
        if (builder.length() > 140) //Tweets are maximum 140 characters
        {
            if (builder.lastIndexOf(";", 110) > 0)
                builder.setLength(builder.lastIndexOf(";", 110));
            else if (builder.lastIndexOf(":", 110) > 0)
                builder.setLength(builder.lastIndexOf(":", 110));
            else if (builder.lastIndexOf(",", 110) > 0)
                builder.setLength(builder.lastIndexOf(",", 110));
            else
                builder.setLength(110);
        }
        //Add a global trend
        builder.append(
                " " + twit.getPlaceTrends(1).getTrends()[r.nextInt(twit.getPlaceTrends(1).getTrends().length)]
                        .getName());
        // Make up a trend by combining two words
        builder.append(" #" + WordsApi.randomWord().getWord() + WordsApi.randomWord().getWord());

        if (builder.length() > 140)
            builder.setLength(140); //Tweets are limited to 140 characters

        twit.updateStatus(builder.toString());
        resp.getWriter().println("Tweet posted: " + builder.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");

        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitter.crawler.TwitterCrawler.java

public static void main(String[] args) {
    try {//from  w  w w. ja  v a2s. c om
        // Authorise the library
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("AhoydO8uSe4v8NEq7j2ISGFlq");
        cb.setOAuthConsumerSecret("ptKEYwq3G9vpFkqAhvwFLSWFcBW8U1SfqycECwK4cH6wThVba6");
        cb.setOAuthAccessToken("778240255577194496-taafqDIHebrg972oxT5kTqcNd3Uojod");
        cb.setOAuthAccessTokenSecret("DMRmeRahnLJRvCBIGQGTaTzE6Pr3PAZMgMsfWIT5ue3PD");
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        User user = twitter.verifyCredentials(); // Get main user

        long cursor = -1;

        // Print user profile
        System.out.println("@" + user.getScreenName());
        System.out.println(user.getId());
        System.out.println(user.getProfileImageURL());
        System.out.println(user.getFriendsCount() + " friends.");
        System.out.println("-------");

        // Print Home Timeline
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");

        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        //Print followers
        System.out.println("-------");
        System.out.println("Showing Follwers:");

        PagableResponseList<User> followers;

        //do
        //{
        followers = twitter.getFollowersList(user.getScreenName(), cursor);

        for (User follower : followers) {
            System.out.println("@" + follower.getScreenName());
        }
        //}
        //while ((cursor = followers.getNextCursor())!=-1);

        //Print follwees

        System.out.println("-------");
        System.out.println("Showing Followees:");

        PagableResponseList<User> followees;

        do {
            followees = twitter.getFriendsList(user.getScreenName(), cursor);

            for (User followee : followees) {
                System.out.println("@" + followee.getScreenName());
            }
        } while ((cursor = followees.getNextCursor()) != -1);
    }

    catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitter.metrics.TwitterMetrics.java

/**
 * @param args the command line arguments
 *///from w  ww.  j ava2  s. c  o m
public static void main(String[] args) {

    try {

        /*Parte que guarda en un archivo*/
        // Se crea el libro
        HSSFWorkbook libro = new HSSFWorkbook();

        // Se crea una hoja dentro del libro
        HSSFSheet hoja = libro.createSheet();

        // Se crea una fila dentro de la hoja
        HSSFRow fila = hoja.createRow(0);

        // Se crea una celda dentro de la fila
        HSSFCell celda = fila.createCell(1);

        // Se crea el contenido de la celda y se mete en ella.
        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Twitter");
        celda.setCellValue(texto);
        /************************************/

        /*Conexion con Mongo DB*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoTwitter");

        DBCollection datos = db.getCollection("Datos");

        /***********************/

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);

        cb.setOAuthConsumerKey("TobUISZXWUhDda04ZBtFGQ");
        cb.setOAuthConsumerSecret("7xurVN3iP6VDcBfKdFJxVuNsJjExERFYNmQIDgtg");

        cb.setOAuthAccessToken("849956971-GJBiORhLIuWK4i3MJ2YCd4vidh65N1GzPIb6duXk");
        cb.setOAuthAccessTokenSecret("4MJgPS9grxVuKbczrPCdSjNnumhcWs7t7OLy2F4kkpOdu");

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

        User u = twitter.showUser("Pringles");

        System.out.println("Nombre: " + u.getName());
        System.out.println("Seguidores: " + u.getFollowersCount());
        System.out.println("Favoritos: " + u.getFavouritesCount());
        System.out.println("Seguidos: " + u.getFriendsCount());
        System.out.println("Ubicacion: " + u.getLocation());
        System.out.println("Descripcin: " + u.getDescription());
        System.out.println("");

        fila = hoja.createRow(1);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Nombre:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getName()));

        fila = hoja.createRow(2);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidores:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFollowersCount() + ""));

        fila = hoja.createRow(3);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Favoritos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFavouritesCount() + ""));

        fila = hoja.createRow(4);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFriendsCount() + ""));

        fila = hoja.createRow(5);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Ubicacin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getLocation() + ""));

        fila = hoja.createRow(6);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Descripcin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getDescription() + ""));

        fila = hoja.createRow(7);
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweets!!!"));

        fila = hoja.createRow(9);
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("IdTweet"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Cuenta"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweet"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Geolocation"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("Place"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("Retweets"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Favoritos"));

        Paging paging = new Paging(1, 1000);
        ResponseList<Status> s = twitter.getUserTimeline(u.getId(), paging);
        int i = 0;
        int filaNum = 10;
        for (Status st : s) {

            BasicDBObject obj = new BasicDBObject();

            obj.append("idTweet", s.get(i).getId() + "");
            obj.append("Cuenta", u.getName());
            obj.append("Tweet", s.get(i).getText());
            obj.append("Geolocation", s.get(i).getGeoLocation());
            obj.append("Place", s.get(i).getPlace());
            obj.append("Reteews", s.get(i).getRetweetCount());
            obj.append("Favoritos", s.get(i).getFavoriteCount());

            fila = hoja.createRow(filaNum);
            celda = fila.createCell(1);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getId() + ""));
            celda = fila.createCell(2);
            celda.setCellValue(new HSSFRichTextString(u.getName()));
            celda = fila.createCell(3);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getText()));
            celda = fila.createCell(4);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getGeoLocation() + ""));
            celda = fila.createCell(5);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getPlace() + ""));
            celda = fila.createCell(6);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getRetweetCount() + ""));
            celda = fila.createCell(7);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getFavoriteCount() + ""));

            i++;
            filaNum++;

            datos.insert(obj);
        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_Twitter.xls");
        libro.write(elFichero);
        elFichero.close();

        /********************************/

        System.out.println(i);

        //User usuario = twitter.showUser("@aaron21007");
        //    List<Status> statuses = twitter.getHomeTimeline();
        //    System.out.println("Showing home timeline.");
        //    for (Status status : statuses) {
        //        System.out.println(status.getUser().getName() + ":" +
        //                           status.getText());
        //    }

        //        Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance();
        //        
        //          List<String> listaTweets = new ArrayList();
        //          List<Long> ListaRettewts = new ArrayList();
        //          List<Integer> ListaFavoritos = new ArrayList();
        //          List<Integer> ListaMenciones = new ArrayList();
        //          List<Date> ListaFecha = new ArrayList();
        //          List<Long> ListaIds = new ArrayList();
        ////
        //          User usuario = unauthenticatedTwitter.showUser("@aaron21007");
        //          List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe();
        //          List<Status> favoritos = unauthenticatedTwitter.getFavorites();
        //          Paging paging = new Paging(1, 1000);
        //          ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(), paging);
        //          
        //          
        //          for (Status sta : statuses) {
        //              
        //            ListaIds.add(Long.valueOf(sta.getId()));
        //            listaTweets.add(sta.getText());
        //            ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + "")));
        //            ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length));
        //            ListaFecha.add(sta.getCreatedAt());
        //            ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount()));
        //              System.out.println(sta.getText());
        //              
        //          }
        //          
        //          
        //        
        //       
        //        
    } catch (Exception e) {
        System.err.println("Fallo................." + e);
    }
}

From source file:TwitterAnalytics.TwitterAPI.java

private TwitterAPI() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumeSecretKey);
    builder.setOAuthAccessToken(accessToken);
    builder.setOAuthAccessTokenSecret(accessSecretToken);
    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);

    twitter = factory.getInstance();/*w w  w . j av a2 s .c om*/
}

From source file:twitterAPI.Twitter_testing.java

private void connectTwitter() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(OAuthConsumerKey);
    cb.setOAuthConsumerSecret(OAuthConsumerSecret);
    cb.setOAuthAccessToken(AccessToken);
    cb.setOAuthAccessTokenSecret(AccessTokenSecret);
    twitterFactory = new TwitterFactory(cb.build());
    twitter = twitterFactory.getInstance();
    System.out.println("connected");
}