1 /* 2 * Copyright (C) 2011 The Libphonenumber Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.i18n.phonenumbers; 18 19 /** 20 * This class is designed to execute a requested command among a set of provided commands. 21 * The dispatching is performed according to the requested command name, which is provided as the 22 * first string of the 'args' array. The 'args' array also contains the command arguments available 23 * from position 1 to end. The verification of the arguments' consistency is under the 24 * responsibility of the command since the dispatcher can't be aware of its underlying goals. 25 * 26 * @see Command 27 * @author Philippe Liard 28 */ 29 public class CommandDispatcher { 30 // Command line arguments passed to the command which will be executed. Note that the first one is 31 // the name of the command. 32 private final String[] args; 33 // Supported commands by this dispatcher. 34 private final Command[] commands; 35 CommandDispatcher(String[] args, Command[] commands)36 public CommandDispatcher(String[] args, Command[] commands) { 37 this.args = args; 38 this.commands = commands; 39 } 40 41 /** 42 * Executes the command named `args[0]` if any. If the requested command (in args[0]) is not 43 * supported, display a help message. 44 * 45 * <p> Note that the command name comparison is case sensitive. 46 */ start()47 public boolean start() { 48 if (args.length != 0) { 49 String requestedCommand = args[0]; 50 51 for (Command command : commands) { 52 if (command.getCommandName().equals(requestedCommand)) { 53 command.setArgs(args); 54 return command.start(); 55 } 56 } 57 } 58 displayUsage(); 59 return false; 60 } 61 62 /** 63 * Displays a message containing the list of the supported commands by this dispatcher. 64 */ displayUsage()65 private void displayUsage() { 66 StringBuilder msg = new StringBuilder("Usage: java -jar /path/to/jar [ "); 67 int i = 0; 68 69 for (Command command : commands) { 70 msg.append(command.getCommandName()); 71 if (i++ != commands.length - 1) { 72 msg.append(" | "); 73 } 74 } 75 msg.append(" ] args"); 76 System.err.println(msg.toString()); 77 } 78 } 79