001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 *
019 *
020 */
021 package org.apache.qpid.tools.utils;
022
023 import java.io.BufferedReader;
024 import java.io.IOException;
025 import java.util.StringTokenizer;
026
027 public class SimpleCommandParser implements CommandParser
028 {
029 private static final String COMMAND_SEPERATOR = ";";
030
031 /** Input source of commands */
032 protected BufferedReader _reader;
033
034 /** The next list of commands from the command line */
035 private StringBuilder _nextCommand = null;
036
037 public SimpleCommandParser(BufferedReader reader)
038 {
039 _reader = reader;
040 }
041
042 public boolean more()
043 {
044 return _nextCommand != null;
045 }
046
047 public boolean isBackground()
048 {
049 return false;
050 }
051
052 public String[] parse() throws IOException
053 {
054 String[] commands = null;
055
056 String input = null;
057
058 if (_nextCommand == null)
059 {
060 input = _reader.readLine();
061 }
062 else
063 {
064 input = _nextCommand.toString();
065 _nextCommand = null;
066 }
067
068 if (input == null)
069 {
070 return null;
071 }
072
073 StringTokenizer tok = new StringTokenizer(input, " ");
074
075 int tokenCount = tok.countTokens();
076 int index = 0;
077
078 if (tokenCount > 0)
079 {
080 commands = new String[tokenCount];
081 boolean commandComplete = false;
082
083 while (tok.hasMoreTokens())
084 {
085 String next = tok.nextToken();
086
087 if (next.equals(COMMAND_SEPERATOR))
088 {
089 commandComplete = true;
090 _nextCommand = new StringBuilder();
091 continue;
092 }
093
094 if (commandComplete)
095 {
096 _nextCommand.append(next);
097 _nextCommand.append(" ");
098 }
099 else
100 {
101 commands[index] = next;
102 index++;
103 }
104 }
105
106 }
107
108 //Reduce the String[] if not all the tokens were used in this command.
109 // i.e. there is more than one command on the line.
110 if (index != tokenCount)
111 {
112 String[] shortCommands = new String[index];
113 System.arraycopy(commands, 0, shortCommands, 0, index);
114 return shortCommands;
115 }
116 else
117 {
118 return commands;
119 }
120 }
121 }
|