Path: blob/master/test/jdk/java/lang/RuntimeTests/exec/UnixCommands.java
41153 views
/*1* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.File;24import java.util.HashMap;25import java.util.Map;2627/**28* Utility class for finding the command on the current system29*/30public class UnixCommands {3132public static final boolean isUnix = ! System.getProperty("os.name").startsWith("Windows");33public static final boolean isLinux = System.getProperty("os.name").startsWith("Linux");3435private static final String[] paths = {"/bin", "/usr/bin"};3637private static Map<String,String> nameToCommand = new HashMap<>(16);3839/**40* Throws Error unless every listed command is available on the system41*/42public static void ensureCommandsAvailable(String... commands) {43for (String command : commands) {44if (findCommand(command) == null) {45throw new Error("Command '" + command + "' not found; bailing out");46}47}48}4950/**51* If the path to the command could be found, returns the command with the full path.52* Otherwise, returns null.53*/54public static String cat() { return findCommand("cat"); }55public static String sh() { return findCommand("sh"); }56public static String kill() { return findCommand("kill"); }57public static String sleep() { return findCommand("sleep"); }58public static String tee() { return findCommand("tee"); }59public static String echo() { return findCommand("echo"); }6061public static String findCommand(String name) {62if (nameToCommand.containsKey(name)) {63return nameToCommand.get(name);64}65String command = findCommand0(name);66nameToCommand.put(name, command);67return command;68}6970private static String findCommand0(String name) {71for (String path : paths) {72File file = new File(path, name);73if (file.canExecute()) {74return file.getPath();75}76}77return null;78}79}808182