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.io.File; 027 import java.util.Arrays; 028 import java.util.Collections; 029 import java.util.List; 030 031 /** 032 * @since 2.7 033 */ 034 public final class Command { 035 036 private String executable; 037 private List<String> arguments = Lists.newArrayList(); 038 private File directory; 039 040 private Command(String executable) { 041 this.executable = executable; 042 } 043 044 public String getExecutable() { 045 return executable; 046 } 047 048 public List<String> getArguments() { 049 return Collections.unmodifiableList(arguments); 050 } 051 052 public Command addArgument(String arg) { 053 arguments.add(arg); 054 return this; 055 } 056 057 public Command addArguments(List<String> args) { 058 arguments.addAll(args); 059 return this; 060 } 061 062 public Command addArguments(String[] args) { 063 arguments.addAll(Arrays.asList(args)); 064 return this; 065 } 066 067 public File getDirectory() { 068 return directory; 069 } 070 071 public Command setDirectory(File d) { 072 this.directory = d; 073 return this; 074 } 075 076 String[] toStrings() { 077 List<String> command = Lists.newArrayList(); 078 command.add(executable); 079 command.addAll(arguments); 080 return command.toArray(new String[command.size()]); 081 } 082 083 public String toCommandLine() { 084 return Joiner.on(" ").join(toStrings()); 085 } 086 087 @Override 088 public String toString() { 089 return toCommandLine(); 090 } 091 092 /** 093 * Create a command line without any arguments 094 * @param executable 095 */ 096 public static Command create(String executable) { 097 if (StringUtils.isBlank(executable)) { 098 throw new IllegalArgumentException("Command executable can not be blank"); 099 } 100 return new Command(executable); 101 } 102 }