001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2011 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
019 */
020 package org.sonar.api.utils.command;
021
022 import com.google.common.base.Joiner;
023 import com.google.common.collect.Lists;
024 import org.apache.commons.lang.StringUtils;
025
026 import java.util.Arrays;
027 import java.util.Collections;
028 import java.util.List;
029
030 /**
031 * @since 2.7
032 */
033 public final class Command {
034
035 private String executable;
036 private List<String> arguments = Lists.newArrayList();
037
038 private Command(String executable) {
039 this.executable = executable;
040 }
041
042 public String getExecutable() {
043 return executable;
044 }
045
046 public List<String> getArguments() {
047 return Collections.unmodifiableList(arguments);
048 }
049
050 public Command addArgument(String arg) {
051 arguments.add(arg);
052 return this;
053 }
054
055 public Command addArguments(List<String> args) {
056 arguments.addAll(args);
057 return this;
058 }
059
060 public Command addArguments(String[] args) {
061 arguments.addAll(Arrays.asList(args));
062 return this;
063 }
064
065 String[] toStrings() {
066 List<String> command = Lists.newArrayList();
067 command.add(executable);
068 command.addAll(arguments);
069 return command.toArray(new String[command.size()]);
070 }
071
072 public String toCommandLine() {
073 return Joiner.on(" ").join(toStrings());
074 }
075
076 @Override
077 public String toString() {
078 return toCommandLine();
079 }
080
081 /**
082 * Create a command line without any arguments
083 * @param executable
084 */
085 public static Command create(String executable) {
086 if (StringUtils.isBlank(executable)) {
087 throw new IllegalArgumentException("Command executable can not be blank");
088 }
089 return new Command(executable);
090 }
091 }