package main; import java.lang.reflect.Array; import java.util.Arrays; import mining.TwitterApi; /** * Class that creates executable commands from input. * @author Maurice Laveaux */ public class CommandParser { // the queue of commands. private final CommandQueue m_queue; // the twitter api. private final TwitterApi m_api; /** * Default constructor, requires the TwitterApi * @param queue A valid CommandQueue that can execute requests. * @param api the TwitterApi to use for the commands. */ public CommandParser(CommandQueue queue, TwitterApi api) { m_queue = queue; m_api = api; } /** * Parses a string and creates an executable command for it. * @param command The string to parse the command from. */ final public void parse(final String command) { // split the code for each space ' '. String[] seperated = command.split(" "); // parse the seperated code for each argument. parse(seperated); } /** * Parses a string and creates an executable command for it. * @param seperated A space seperated string for each argument. */ final public void parse(final String[] seperated) { if (seperated.length == 0) { return; } // The main command. String command = seperated[0]; // the first command issued switch (command) { case "help": showFullHelp(); return; case "-h": showFullHelp(); return; case "quit": // TODO: implement less hack way of quiting the program. System.exit(0); default: break; } // there is a command without errors but it was not switched. if (seperated.length == 1) { showUsageHelp(command); return; } // commands with multiple parameters String[] extra = Arrays.copyOfRange(seperated, 1, seperated.length); if (seperated.length < 3) { showUsageHelp(extra.toString()); return; } String[] parameters = Arrays.copyOfRange(extra, 1, extra.length); try { switch (command) { case "get": m_queue.add(new RequestCommand(m_api, extra[0], parameters)); return; } } catch (IllegalArgumentException ex) { System.out.println(ex); } } /** Show the basic usage help in console */ private void showUsageHelp(String unknown) { System.out.println("Unknown argument: \"" + unknown + "\"."); System.out.println(" Use help, -h for more help."); } /** Show the full manual page in the console */ private void showFullHelp() { System.out.println("Usage: [command] [arguments], see below for options."); System.out.println("\n command:"); System.out.println(" set, use the twitter Search/REST API."); System.out.println(" stream, use the twitter Stream API."); System.out.println("\n arguments:"); System.out.println("
, the information to get from api.twitter.com."); System.out.println(" , any number of arguments for the information"); } }