Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package twiter;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- import java.util.Scanner;
- import org.apache.commons.lang3.StringUtils;
- public class Twitter implements TwitterApplication {
- private Cache cache;
- private TwitterQuery tQ;
- private List<Tweet> tweets;
- private LocationSearch locationSearch;
- private TwitterSearch twitterSearch;
- private int gCount = 15;
- boolean gCountSet = false;
- public Twitter(){
- // Initialize the cache
- Cache cache = new MyCache();
- cache.setCacheFilename("D:\\places.csv");
- this.setCache(cache);
- this.setLocationSearch(new MyLocationSearch());
- this.setTwitterSearch(new MyTwitterSearch());
- }
- //print how we use twitter application
- public static void printUsage(boolean exit){
- System.out.println(
- "\nMinimal Usage: java Twitter [location]"
- + "\nAdvanced Usage: java Twitter [location] -count [num] -sort [field] [asc|desc] -search [keyword]"
- + "\n\n\t�help Displays this message."
- + "\n\t�count num defines the number of tweets that are going to be displayed. The default is 15."
- + "\n\t�sort field [asc|desc]: Defines sorting. Default sorting is ascending."
- + "\n\tField can be author, date, tweet."
- + "\n\t�search keyword Only tweets with keywords are displayed.");
- if(exit)
- System.exit(1);
- }
- //implementation of run with arguments,this function is call when twitter application run with comand line arguments.
- @Override
- public void runWithArgs(String[] args) {
- //get all actions(comands) from given comand line arguments means which comands are given to twitter app and store in actions list
- List<Action> actions = getActionsFromArguments(args);
- // Execute all action(comand), which are given from comand line arguments
- //this loop is continue run until all actions are not completed.
- for(Action action: actions){
- //execute each action
- executeAction(action);
- }
- executeAction(new MyPrintAction());
- }
- @Override
- public void runInteractive() {
- System.out.println("Interactive Mode..");
- Scanner in = new Scanner(System.in);
- String input;
- do{
- //get input from user
- input = in.nextLine();
- // Get actions from input and save in actions list
- List<Action> actions = getActionsFromInput(input);
- // Execute each action
- for(Action a:actions)
- executeAction(a);
- // Keep asking input till exit
- } while(!input.equals("exit")) ;
- in.close();
- }
- //this method is call when we start twitter app using interactive mode
- @Override
- public List<Action> getActionsFromInput(String action) {
- String[] args = action.split("\\s+"); // Split input of user on space and save in args string array
- List<Action> actions = new ArrayList<>();
- switch(args[0]){
- //if action is query
- case "query":
- //create query action
- MyQueryAction a = new MyQueryAction();
- String location = "";
- int index = 1;
- //set default count set is 15
- if(gCountSet)
- a.setCount(gCount);
- while ( index < args.length ) {
- // Set count if number then set new counts
- if ( StringUtils.isNumeric(args[index]) ){
- a.setCount(Integer.parseInt(args[index]));
- break;
- }
- //set location
- location = location + " " + args[index];
- index++;
- }
- if (location.isEmpty() || a.getCount() < 1) {
- System.out.println("Invalid action specified");
- return actions;
- }
- //set location in action
- a.setLocation(location);
- //add this action in action list
- actions.add(a);
- break;
- //if comand is for set counts
- case "setcount":
- //if arguments having length of 2 then set counts
- if(args.length == 2 && StringUtils.isNumeric(args[1])) {
- gCount = Integer.valueOf(args[1]);
- gCountSet = true;
- }//else this action is invalid
- else {
- System.out.println("Invalid action specified");
- return actions;
- }
- //if count is <1 means negative then print message that invalid count specified
- if (gCount < 1) {
- System.out.println("Invalid count specified");
- return actions;
- }
- System.out.println("Count set: " + gCount);
- break;
- //if action is print
- case "print":
- //create print action
- MyPrintAction p = new MyPrintAction();
- if(gCountSet)
- p.setCount(gCount);
- //if input is length of 2 then set count
- if(args.length == 2)
- p.setCount(Integer.valueOf(args[2]));
- //else if input arguemnts has length greater then 2 then print invalid action
- else if (args.length > 2){
- System.out.println("Invalid action specified");
- return actions;
- }
- //add print action in actions list
- actions.add(p);
- break;
- //if action is search
- case "search":
- //create serch action
- MySearchAction s = null;
- //store keyword for my search action
- if(args.length == 2){
- s = new MySearchAction(args[1]);
- }
- //else if invalid arguments are given
- else {
- System.out.println("Invalid action specified");
- return actions;
- }
- //add search action in actions list
- actions.add(s);
- break;
- //if action is sort
- case "sort":
- int field = 0, order = 0;
- if(args.length == 2 || args.length == 3) {
- // Get the field means which field should be sorted either authors/tweets/date
- switch(args[1].toLowerCase()){
- case "author": field = SortAction.FIELD_AUTHOR; break;
- case "tweet": field = SortAction.FIELD_TWEET; break;
- case "date": field = SortAction.FIELD_DATE; break;
- default:
- System.out.println("Invalid sorting field specified.");
- return actions;
- }
- // Get the order means ascending or descending
- if(args.length == 3){
- // Order is also specified if ascending
- if(args[2].equalsIgnoreCase("desc"))
- order = SortAction.ORDER_DESCENDING;
- // Order is if descending
- else if(args[2].equalsIgnoreCase("asc"))
- order = SortAction.ORDER_ASCENDING;
- // if order is invalid
- else {
- System.out.println("Invalid sorting order specified.");
- return actions;
- }
- }
- }
- else {
- System.out.println("Invalid action specified");
- return actions;
- }
- // All went well, add this sort action to the list
- actions.add(new MySortAction(field, order));
- }
- //return all actions list
- return actions;
- }
- //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.
- @Override
- public List<Action> getActionsFromArguments(String[] args) {
- List<Action> actions = new ArrayList<>();
- int index = 0;
- // create Query Action, where we store location from given arguments
- MyQueryAction q = new MyQueryAction();
- //if args array conatin comand "-help" then print Usage of twitter application
- if (args[0].equalsIgnoreCase("-help")){
- // Display the usage if -help specified
- printUsage(true);
- }
- //if arguments not start with this "-", means others comands are given to twitter application
- else if(!args[0].startsWith("-")) {
- // Create location string
- String location = "";
- //while loop is executed until any number is exists in given arguments, because we want location (a city name such as Berlin)
- while ( index < args.length ) {
- // Break this loop if number or another argument come
- if ( StringUtils.isNumeric(args[index]) || args[index].startsWith("-") )
- break;
- //store location city name like Berlin in location string
- location = location + " " + args[index];
- //increament index and see next argument, and continue loop
- index++;
- }
- //set loaction from gven arguments(city like Berlin) in twitterQuery object
- q.setLocation(location.trim());
- //print location which is given in comand line arguments, which is we store in twitterQuery object(action)
- System.out.println("Location set: " + q.getLocation());
- }
- //if arguments start with "-" but is not help then we also printUsage of twitter app
- else{
- // A string that starts with "-" and isn't "-help"
- printUsage(true);
- }
- // Parse all other next arguments (like -count,-sort,-search)
- while (index<args.length) {
- // 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
- if (args[index].equalsIgnoreCase("-count")){
- index++;
- //if the value of count is not specified then print usage , means if -count is specified but value is not exists
- if(args.length < index+1)
- printUsage(true);
- // Count is specified too, and take value of count and store in count string
- String count = args[index];
- //check if count is number or not if number then set in twitterQuery object
- if (StringUtils.isNumeric(count)) {
- //convert the count string into integer and set in TwitterQuery object
- q.setCount(Integer.valueOf(count));
- }
- //else if count is not number then also printUsage
- else
- printUsage(true);
- //if count is number and then check if count is either negative value or not if negative then print usage
- if (q.getCount() < 1)
- printUsage(true);
- //increament index++, move to next comand
- index++;
- //print value of count
- System.out.println("Count set: " + q.getCount());
- }
- // If -sort specified in given arguments, input the field and/or the order
- else if(args[index].equalsIgnoreCase("-sort")){
- index++;
- //if the value of sort is not specified then print usage, means if -sort is specified but value is not exists
- if(args.length < index+1)
- printUsage(true);
- int field = 0, order = 0;
- // Get the field ,means which field is use for sorting the tweets
- //check which field(author,tweet,date) is specified and store in field string
- switch(args[index].toLowerCase()){
- case "author": field = SortAction.FIELD_AUTHOR; break;
- case "tweet": field = SortAction.FIELD_TWEET; break;
- case "date": field = SortAction.FIELD_DATE; break;
- //print invalid msg and PringUsage if specified field is not (author/tweet/date)
- default:
- System.out.println("Invalid sorting field specified.");
- printUsage(true);
- }
- //move to next argument in given comand line args array
- index++;
- //check if order is speciferd then check which order(descending/ascending) is specified for sorting
- if(index+1 <args.length && !args[index+1].startsWith("-")){
- // Order is also specified check which is specified desc/asc and store in order string
- //if order is desc
- if(args[index].equalsIgnoreCase("desc"))
- order = SortAction.ORDER_DESCENDING;
- //else if order is asc
- else if(args[index].equalsIgnoreCase("asc"))
- order = SortAction.ORDER_ASCENDING;
- //else if order is other then asc/desc then print Usage
- else
- printUsage(true);
- index++;
- }
- // All went well, add this new SortAction object to the actions list
- actions.add(new MySortAction(field, order));
- //print sort field and order
- System.out.println("Sort set: " + field + ", " + order);
- }
- // If -search comand is specified in given arguments, get the keyword from arguments and set.
- else if(args[index].equalsIgnoreCase("-search")){
- index++;
- if(args.length < index+1)
- printUsage(true);
- //take search keyword from given args and store in keyword string
- String keyword = args[index];
- //create new MySearchAction with keyword and add in to actions list
- actions.add(new MySearchAction(keyword));
- index++;
- System.out.println("Keyword set: " + keyword);
- }
- else {
- // Invalid
- printUsage(true);
- }
- }
- // Add query at front of all actions
- actions.add(0,q);
- return actions;
- }
- // this method is call when we execute an action(MyQuery/Sort/Search Action)
- @Override
- public void executeAction(Action action) {
- //if action is MyQueryAction
- if (action instanceof MyQueryAction) {
- //get location from MyQueryAction
- String location = ((MyQueryAction) action).getLocation();
- //get MyTwitterQuery from cache for given location and store in tQ MyTwitterQuery
- MyTwitterQuery tQ = (MyTwitterQuery) cache.getQueryFromCache(location);
- //if this MyTwitterQuery is not already exists in cache
- if (tQ == null || !tQ.isGeoSet()){
- // Need to fetch whole data from OSM & update in cache
- System.out.println("Fetching data from OSM...");
- tQ = (MyTwitterQuery) locationSearch.getQueryFromLocation(location);
- // Check if valid location found
- if ( !tQ.isGeoSet() ){
- System.out.println("Invalid location entered..");
- printUsage(true);
- }
- //update cache with new loaction which is get from OSM
- cache.addLocation(tQ);
- }
- //if MyTwitterQuery is found in cache for given location
- else
- System.out.println("Found in cache");
- //get counts of tweets from myqueryAction and set in TwetterQuery
- tQ.setCount(((MyQueryAction) action).getCount());
- // Set the TwitterQuery object to TwitterQuery instance variable
- this.tQ = tQ;
- // Perform Query and get all tweets of given MyTwetterQuerry and set in tweets intance variable
- this.tweets = twitterSearch.getTweets(this.tQ);
- //print given location
- System.out.println("Location search result: " + tQ.toString());
- }
- //if action is for sorting tweets then sorts all this.tweets according to given field(author/tweets/date) and order (asc/desc)
- else if(action instanceof MySortAction){
- // Sort List<Tweet> using Comparator
- Collections.sort(tweets, new Comparator<Tweet>() {
- @Override
- public int compare(Tweet t1, Tweet t2) {
- int result = 0;
- //check which sort field is specified
- switch(((MySortAction) action).getSortField()){
- //if given field is author then tweets compare according to their authors and sort in ascending order
- case SortAction.FIELD_AUTHOR:
- result = t1.getUser().compareToIgnoreCase(t2.getUser());
- break;
- //if given field is tweet then tweets compare according to their tweets and sort in ascending order
- case SortAction.FIELD_TWEET:
- result = t1.getText().compareToIgnoreCase(t2.getText());
- break;
- //if given field is date then tweets compare according to their dates and sort in ascending order
- case SortAction.FIELD_DATE:
- result = t1.getTimestamp().compareTo(t2.getTimestamp());
- break;
- }
- // If descending order needed, we change the sign of result and tweets are sort in descending
- if (((MySortAction) action).getSortOrder() == SortAction.ORDER_DESCENDING)
- result = -result;
- return result;
- }
- });
- }//if action is for filter tweets using given keyword
- else if(action instanceof MySearchAction){
- // Filter using keyword
- String keyword = ((MySearchAction) action).getSearchKeyword();
- // Set keyword
- this.tQ.setKeyword(keyword);
- // Perform Query and get filtered tweets for specified filter(keyword)
- this.tweets = twitterSearch.getTweets(this.tQ);
- }
- //if action is for print all tweets
- else if(action instanceof MyPrintAction){
- // Print the list of tweets
- ((MyPrintAction) action).print(tweets);
- }
- }
- //getter and setter of all instance variable
- @Override
- public void setLocationSearch(LocationSearch locationSearch) {
- this.locationSearch = (MyLocationSearch) locationSearch;
- }
- @Override
- public LocationSearch getLocationSearch() {
- return this.locationSearch;
- }
- @Override
- public void setTwitterSearch(TwitterSearch twitterSearch) {
- this.twitterSearch = (MyTwitterSearch) twitterSearch;
- }
- @Override
- public TwitterSearch getTwitterSearch() {
- return twitterSearch;
- }
- @Override
- public void setCache(Cache cache) {
- this.cache = (MyCache) cache;
- }
- @Override
- public Cache getCache() {
- return cache;
- }
- @Override
- public void setTweets(List<Tweet> tweets) {
- this.tweets = tweets;
- }
- @Override
- public List<Tweet> getTweets() {
- return tweets;
- }
- public static void main(String[] args) {
- //create twitter application object
- TwitterApplication app = new Twitter();
- //get cache and initilize
- app.getCache().init();
- //run twitter application
- app.run(args);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement