Advertisement
myshkin1

Untitled

Apr 20th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.75 KB | None | 0 0
  1. package twiter;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import java.util.Scanner;
  8.  
  9. import org.apache.commons.lang3.StringUtils;
  10.  
  11.  
  12. public class Twitter implements TwitterApplication {
  13.  
  14.     private Cache cache;
  15.     private TwitterQuery tQ;
  16.     private List<Tweet> tweets;
  17.     private LocationSearch locationSearch;
  18.     private TwitterSearch twitterSearch;
  19.     private int gCount = 15;
  20.     boolean gCountSet = false;
  21.    
  22.     public Twitter(){
  23.        
  24.         // Initialize the cache
  25.         Cache cache = new MyCache();
  26.         cache.setCacheFilename("D:\\places.csv");
  27.         this.setCache(cache);
  28.         this.setLocationSearch(new MyLocationSearch());
  29.         this.setTwitterSearch(new MyTwitterSearch());
  30.        
  31.     }
  32.     //print how we use twitter application
  33.     public static void printUsage(boolean exit){
  34.         System.out.println(
  35.                 "\nMinimal Usage: java Twitter [location]"
  36.                 + "\nAdvanced Usage: java Twitter [location] -count [num] -sort [field] [asc|desc] -search [keyword]"
  37.                 + "\n\n\t�help Displays this message."
  38.                 + "\n\t�count num defines the number of tweets that are going to be displayed. The default is 15."
  39.                 + "\n\t�sort field [asc|desc]: Defines sorting. Default sorting is ascending."
  40.                 + "\n\tField can be author, date, tweet."
  41.                 + "\n\t�search keyword Only tweets with keywords are displayed.");
  42.        
  43.         if(exit)
  44.             System.exit(1);
  45.     }
  46.    
  47.        
  48.         //implementation of run with arguments,this function is call when twitter application run with comand line arguments.
  49.     @Override
  50.     public void runWithArgs(String[] args) {
  51.        
  52.                 //get all actions(comands) from given comand line arguments means which comands are given to twitter app and store in actions list
  53.         List<Action> actions = getActionsFromArguments(args);
  54.         // Execute all action(comand), which are given from comand line arguments
  55.                 //this loop is continue run until all actions are not completed.
  56.         for(Action action: actions){
  57.                         //execute each action
  58.             executeAction(action);
  59.         }
  60.         executeAction(new MyPrintAction());
  61.        
  62.     }
  63.  
  64.     @Override
  65.     public void runInteractive() {
  66.         System.out.println("Interactive Mode..");
  67.        
  68.         Scanner in = new Scanner(System.in);
  69.         String input;
  70.        
  71.         do{
  72.                         //get input from user
  73.             input = in.nextLine();
  74.             // Get actions from input and save in actions list
  75.             List<Action> actions = getActionsFromInput(input);
  76.            
  77.             // Execute each action
  78.             for(Action a:actions)
  79.                 executeAction(a);
  80.            
  81.             // Keep asking input till exit
  82.         } while(!input.equals("exit")) ;
  83.        
  84.         in.close();
  85.        
  86.     }
  87.  
  88.         //this method is call when we start twitter app using interactive mode
  89.     @Override
  90.     public List<Action> getActionsFromInput(String action) {
  91.        
  92.         String[] args = action.split("\\s+"); // Split input of user on space and save in args string array
  93.         List<Action> actions = new ArrayList<>();
  94.        
  95.         switch(args[0]){
  96.         //if action is query   
  97.         case "query":
  98.                         //create query action
  99.             MyQueryAction a = new MyQueryAction();
  100.             String location = "";
  101.             int index = 1;
  102.             //set default count set is 15
  103.             if(gCountSet)
  104.                 a.setCount(gCount);
  105.            
  106.             while ( index < args.length ) {
  107.                 // Set count if number then set new counts
  108.                 if ( StringUtils.isNumeric(args[index]) ){
  109.                     a.setCount(Integer.parseInt(args[index]));
  110.                    
  111.                     break;
  112.                 }
  113.                                 //set location
  114.                 location = location + " " + args[index];
  115.                 index++;
  116.             }
  117.             if (location.isEmpty() || a.getCount() < 1) {
  118.                 System.out.println("Invalid action specified");
  119.                 return actions;
  120.             }
  121.                         //set location in action
  122.             a.setLocation(location);
  123.                         //add this action in action list
  124.             actions.add(a);
  125.             break;
  126.         //if comand is for set counts  
  127.         case "setcount":
  128.             //if arguments having length of 2 then set counts
  129.             if(args.length == 2 && StringUtils.isNumeric(args[1])) {
  130.                 gCount = Integer.valueOf(args[1]);
  131.                 gCountSet = true;
  132.             }//else this action is invalid
  133.             else {
  134.                 System.out.println("Invalid action specified");
  135.                 return actions;
  136.             }
  137.                         //if count is <1 means negative then print message that invalid count specified
  138.             if (gCount < 1) {
  139.                 System.out.println("Invalid count specified");
  140.                 return actions;
  141.             }
  142.             System.out.println("Count set: " + gCount);
  143.             break;
  144.         //if action is print   
  145.         case "print":
  146.             //create print action
  147.             MyPrintAction p = new MyPrintAction();
  148.            
  149.             if(gCountSet)
  150.                 p.setCount(gCount);
  151.             //if input is length of 2 then set count
  152.             if(args.length == 2)
  153.                 p.setCount(Integer.valueOf(args[2]));
  154.                         //else if input arguemnts has length greater then 2 then print invalid action
  155.             else if (args.length > 2){
  156.                 System.out.println("Invalid action specified");
  157.                 return actions;
  158.             }
  159.                         //add print action in actions list
  160.             actions.add(p);
  161.             break;
  162.         //if action is search
  163.         case "search":
  164.                     //create serch action
  165.             MySearchAction s = null;
  166.                         //store keyword for my search action
  167.             if(args.length == 2){
  168.                 s = new MySearchAction(args[1]);
  169.             }
  170.                         //else if invalid arguments are given
  171.             else {
  172.                 System.out.println("Invalid action specified");
  173.                 return actions;
  174.             }
  175.                         //add search action in actions list
  176.             actions.add(s);
  177.             break;
  178.         //if action is sort
  179.         case "sort":
  180.             int field = 0, order = 0;
  181.             if(args.length == 2 || args.length == 3) {
  182.                 // Get the field means which field should be sorted either authors/tweets/date
  183.                 switch(args[1].toLowerCase()){
  184.                 case "author": field = SortAction.FIELD_AUTHOR; break;
  185.                 case "tweet": field = SortAction.FIELD_TWEET; break;
  186.                 case "date": field = SortAction.FIELD_DATE; break;
  187.                 default:
  188.                     System.out.println("Invalid sorting field specified.");
  189.                     return actions;
  190.                 }
  191.                                 // Get the order means ascending or descending
  192.                 if(args.length == 3){
  193.                     // Order is also specified if ascending
  194.                     if(args[2].equalsIgnoreCase("desc"))
  195.                         order = SortAction.ORDER_DESCENDING;
  196.                                         // Order is if descending
  197.                     else if(args[2].equalsIgnoreCase("asc"))
  198.                         order = SortAction.ORDER_ASCENDING;
  199.                                         // if order is invalid
  200.                     else {
  201.                         System.out.println("Invalid sorting order specified.");
  202.                         return actions;
  203.                     }
  204.                 }
  205.             }
  206.            
  207.             else {
  208.                 System.out.println("Invalid action specified");
  209.                 return actions;
  210.             }
  211.                
  212.             // All went well, add this sort action to the list
  213.             actions.add(new MySortAction(field, order));
  214.         }
  215.         //return all actions list
  216.         return actions;
  217.        
  218.     }
  219.  
  220.         //this function is call when twitter application is run with comand line arguments, all actions from comand line arguments are pass to this function for splitting all actions and store in actions list which is executed in runWithArgs() function which is define above.
  221.     @Override
  222.     public List<Action> getActionsFromArguments(String[] args) {
  223.        
  224.         List<Action> actions = new ArrayList<>();
  225.         int index = 0;
  226.         // create Query Action, where we store location from given arguments
  227.         MyQueryAction q = new MyQueryAction();
  228.         //if args array conatin comand "-help" then print Usage of twitter application
  229.         if (args[0].equalsIgnoreCase("-help")){
  230.             // Display the usage if -help specified
  231.             printUsage(true);
  232.         }  
  233.                 //if arguments not start with this "-", means others comands are given to twitter application
  234.         else if(!args[0].startsWith("-")) {
  235.             // Create location string
  236.             String location = "";
  237.                         //while loop is executed until any number is exists in given arguments, because we want location (a city name such as Berlin)
  238.             while ( index < args.length ) {
  239.                 // Break this loop if number or another argument come
  240.                 if ( StringUtils.isNumeric(args[index]) || args[index].startsWith("-") )
  241.                     break;
  242.                 //store location city name like Berlin in location string
  243.                 location = location + " " + args[index];
  244.                                 //increament index and see next argument, and continue loop
  245.                 index++;
  246.             }
  247.                         //set loaction from gven arguments(city like Berlin) in twitterQuery object
  248.             q.setLocation(location.trim());
  249.             //print location which is given in comand line arguments, which is we store in twitterQuery object(action)
  250.             System.out.println("Location set: " + q.getLocation());
  251.                     }
  252.                     //if arguments start with "-" but is not help then we also printUsage of twitter app
  253.                     else{
  254.                             // A string that starts with "-" and isn't "-help"
  255.                             printUsage(true);
  256.                     }
  257.            
  258.        
  259.         // Parse all other next arguments (like -count,-sort,-search)
  260.         while (index<args.length) {
  261.            
  262.             // If the count specified in given arguments,then take the next value as count, this count is use for define no. of tweets for display
  263.             if (args[index].equalsIgnoreCase("-count")){
  264.                 index++;
  265.                                 //if the value of count is not specified then print usage , means if -count is specified but value is not exists
  266.                 if(args.length < index+1)
  267.                     printUsage(true);
  268.                 // Count is specified too, and take value of count and store in count string
  269.                 String count = args[index];
  270.                                 //check if count is number or not if number then set in twitterQuery object
  271.                 if (StringUtils.isNumeric(count)) {
  272.                                         //convert the count string into integer and set in TwitterQuery object
  273.                     q.setCount(Integer.valueOf(count));
  274.                 }
  275.                                 //else if count is not number then also printUsage
  276.                 else
  277.                     printUsage(true);
  278.                 //if count is number and then check if count is either negative value or not if negative then print usage
  279.                 if (q.getCount() < 1)
  280.                     printUsage(true);
  281.                 //increament index++,  move to next comand
  282.                 index++;
  283.                                 //print value of count
  284.                 System.out.println("Count set: " + q.getCount());
  285.                
  286.             }
  287.            
  288.             // If -sort specified in given arguments, input the field and/or the order
  289.             else if(args[index].equalsIgnoreCase("-sort")){
  290.                
  291.                 index++;
  292.                                 //if the value of sort is not specified then print usage, means if -sort is specified but value is not exists
  293.                 if(args.length < index+1)
  294.                     printUsage(true);
  295.                
  296.                 int field = 0, order = 0;
  297.                 // Get the field ,means which field is use for sorting the tweets
  298.                                 //check which field(author,tweet,date) is specified and store in field string
  299.                 switch(args[index].toLowerCase()){
  300.                 case "author": field = SortAction.FIELD_AUTHOR; break;
  301.                 case "tweet": field = SortAction.FIELD_TWEET; break;
  302.                 case "date": field = SortAction.FIELD_DATE; break;
  303.                                 //print invalid msg and PringUsage if specified field is not (author/tweet/date)
  304.                 default:
  305.                     System.out.println("Invalid sorting field specified.");
  306.                     printUsage(true);
  307.                 }
  308.                                 //move to next argument in given comand line args array
  309.                 index++;
  310.                                 //check if order is speciferd then check which order(descending/ascending) is specified for sorting
  311.                 if(index+1 <args.length && !args[index+1].startsWith("-")){
  312.                     // Order is also specified check which is specified desc/asc and store in order string
  313.                                         //if order is desc
  314.                     if(args[index].equalsIgnoreCase("desc"))
  315.                         order = SortAction.ORDER_DESCENDING;
  316.                                         //else if order is asc
  317.                     else if(args[index].equalsIgnoreCase("asc"))
  318.                                            
  319.                         order = SortAction.ORDER_ASCENDING;
  320.                                         //else if order is other then asc/desc then print Usage
  321.                     else
  322.                         printUsage(true);
  323.                     index++;
  324.                 }
  325.                
  326.                 // All went well, add this new SortAction object to the actions list
  327.                 actions.add(new MySortAction(field, order));
  328.                 //print sort field and order
  329.                 System.out.println("Sort set: " + field + ", " + order);
  330.             }
  331.             // If -search comand is specified in given arguments, get the keyword from arguments and set.
  332.             else if(args[index].equalsIgnoreCase("-search")){
  333.                 index++;
  334.                 if(args.length < index+1)
  335.                     printUsage(true);
  336.                                 //take search keyword from given args and store in keyword string
  337.                 String keyword = args[index];
  338.                                 //create new MySearchAction with keyword and add in to actions list
  339.                 actions.add(new MySearchAction(keyword));
  340.                 index++;
  341.                 System.out.println("Keyword set: " + keyword);
  342.             }
  343.            
  344.             else {
  345.                 // Invalid
  346.                 printUsage(true);
  347.             }
  348.         }
  349.         // Add query at front of all actions
  350.         actions.add(0,q);
  351.         return actions;
  352.     }
  353.  
  354.         // this method is call when we execute an action(MyQuery/Sort/Search Action)
  355.     @Override
  356.     public void executeAction(Action action) {
  357.         //if action is MyQueryAction
  358.         if (action instanceof MyQueryAction) {
  359.             //get location from MyQueryAction
  360.             String location = ((MyQueryAction) action).getLocation();
  361.             //get MyTwitterQuery from cache for given location and store in tQ MyTwitterQuery
  362.             MyTwitterQuery tQ = (MyTwitterQuery) cache.getQueryFromCache(location);
  363.             //if this MyTwitterQuery is not already exists in cache
  364.             if (tQ == null || !tQ.isGeoSet()){
  365.                 // Need to fetch whole data from OSM & update in cache
  366.                 System.out.println("Fetching data from OSM...");
  367.                 tQ = (MyTwitterQuery) locationSearch.getQueryFromLocation(location);
  368.                
  369.                 // Check if valid location found
  370.                 if ( !tQ.isGeoSet() ){
  371.                     System.out.println("Invalid location entered..");
  372.                     printUsage(true);
  373.                 }
  374.                    
  375.                 //update cache with new loaction which is get from OSM
  376.                 cache.addLocation(tQ);
  377.             }
  378.                         //if MyTwitterQuery is found in cache for given location
  379.             else
  380.                 System.out.println("Found in cache");
  381.            
  382.             //get counts of tweets from myqueryAction and set in TwetterQuery
  383.             tQ.setCount(((MyQueryAction) action).getCount());
  384.            
  385.             // Set the TwitterQuery object to TwitterQuery instance variable
  386.             this.tQ = tQ;
  387.             // Perform Query and get all tweets of given  MyTwetterQuerry and set in tweets intance variable
  388.             this.tweets = twitterSearch.getTweets(this.tQ);
  389.            
  390.                         //print given location
  391.             System.out.println("Location search result: " + tQ.toString());
  392.            
  393.         }
  394.                 //if action is for sorting tweets then sorts all this.tweets according to given field(author/tweets/date) and order (asc/desc)
  395.         else if(action instanceof MySortAction){
  396.             // Sort List<Tweet> using Comparator
  397.             Collections.sort(tweets, new Comparator<Tweet>() {
  398.                 @Override
  399.                 public int compare(Tweet t1, Tweet t2) {
  400.                     int result = 0;
  401.                                         //check which sort field is specified
  402.                     switch(((MySortAction) action).getSortField()){
  403.                                                 //if given field is author then tweets compare according to their authors and sort in ascending order
  404.                         case SortAction.FIELD_AUTHOR:
  405.                             result = t1.getUser().compareToIgnoreCase(t2.getUser());
  406.                             break;
  407.                         //if given field is tweet then tweets compare according to their tweets and sort in ascending order
  408.                         case SortAction.FIELD_TWEET:
  409.                             result = t1.getText().compareToIgnoreCase(t2.getText());
  410.                             break;
  411.                         //if given field is date then tweets compare according to their dates and sort in ascending order
  412.                         case SortAction.FIELD_DATE:
  413.                             result = t1.getTimestamp().compareTo(t2.getTimestamp());
  414.                             break;
  415.                     }
  416.                     // If descending order needed, we change the sign of result and tweets are sort in descending
  417.                     if (((MySortAction) action).getSortOrder() == SortAction.ORDER_DESCENDING)
  418.                         result = -result;
  419.                    
  420.                     return result;
  421.                 }
  422.                
  423.             });
  424.         }//if action is for filter tweets using given keyword
  425.         else if(action instanceof MySearchAction){
  426.             // Filter using keyword
  427.             String keyword = ((MySearchAction) action).getSearchKeyword();
  428.             // Set keyword
  429.             this.tQ.setKeyword(keyword);
  430.             // Perform Query and get filtered tweets for specified filter(keyword)
  431.             this.tweets = twitterSearch.getTweets(this.tQ);
  432.         }
  433.                 //if action is for print all tweets
  434.         else if(action instanceof MyPrintAction){
  435.             // Print the list of tweets
  436.             ((MyPrintAction) action).print(tweets);
  437.         }
  438.     }
  439.  
  440.        
  441.         //getter and setter of all instance variable
  442.     @Override
  443.     public void setLocationSearch(LocationSearch locationSearch) {
  444.         this.locationSearch = (MyLocationSearch) locationSearch;       
  445.     }
  446.  
  447.     @Override
  448.     public LocationSearch getLocationSearch() {
  449.         return this.locationSearch;
  450.     }
  451.  
  452.     @Override
  453.     public void setTwitterSearch(TwitterSearch twitterSearch) {
  454.         this.twitterSearch = (MyTwitterSearch) twitterSearch;
  455.     }
  456.  
  457.     @Override
  458.     public TwitterSearch getTwitterSearch() {
  459.         return twitterSearch;
  460.     }
  461.  
  462.     @Override
  463.     public void setCache(Cache cache) {
  464.         this.cache = (MyCache) cache;
  465.     }
  466.  
  467.     @Override
  468.     public Cache getCache() {
  469.         return cache;
  470.     }
  471.  
  472.     @Override
  473.     public void setTweets(List<Tweet> tweets) {
  474.         this.tweets = tweets;
  475.        
  476.     }
  477.  
  478.     @Override
  479.     public List<Tweet> getTweets() {
  480.         return tweets;
  481.     }
  482.    
  483.     public static void main(String[] args) {
  484.                 //create twitter application object
  485.         TwitterApplication app = new Twitter();
  486.                 //get cache and initilize
  487.         app.getCache().init();
  488.                
  489.                 //run twitter application
  490.         app.run(args);
  491.        
  492.     }
  493. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement