Skip to content

Instantly share code, notes, and snippets.

@froop
Created January 13, 2012 03:00
Show Gist options
  • Save froop/1604358 to your computer and use it in GitHub Desktop.
Save froop/1604358 to your computer and use it in GitHub Desktop.
[Java][Windows] OSコマンド実行、WSH用スクリプト実行
public class WindowsCommandUtils {
public static void executeCommand(ProcessBuilder builder) {
ProcessResult result = executeAndCollectResult(builder);
validateProcessResult(result);
}
/**
* For Windows Scripting Host. (VBScript, etc.)
*/
public static void executeWshScript(File file, File workDir,
String... args) {
ProcessBuilder builder =
new ProcessBuilder(buildWshCommandList(file, args))
.directory(workDir);
ProcessResult result = executeAndCollectResult(builder);
validateWshProcessResult(result);
}
private static class ProcessResult {
private int code;
private String message;
}
private static ProcessResult executeAndCollectResult(ProcessBuilder builder) {
try {
Process process = builder.redirectErrorStream(true).start();
int retCode = process.waitFor();
ProcessResult result = new ProcessResult();
result.code = retCode;
result.message = readProcessResult(process);
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static String readProcessResult(Process process) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
return readAllText(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String readAllText(BufferedReader reader) throws IOException {
try {
StringBuilder text = new StringBuilder();
for (;;) {
String line = reader.readLine();
if (line == null) {
break;
}
text.append(line);
}
return text.toString();
} finally {
IOUtils.closeQuietly(reader);
}
}
private static void validateProcessResult(ProcessResult result) {
if (result.code != 0) {
throw new RuntimeException(buildMessage(result));
}
}
private static String buildMessage(ProcessResult result) {
return "code=" + result.code + ": " + result.message;
}
private static List<String> buildWshCommandList(File file, String... args) {
List<String> list = new ArrayList<String>();
list.add(buildWshPath());
list.add("//nologo");
list.add(file.getPath());
list.addAll(Arrays.asList(args));
return list;
}
/**
* Call 32bit version WSH. Even 64bit OS.
*/
private static String buildWshPath() {
String exeName = "cscript.exe";
String systemRoot = System.getenv("SystemRoot");
String sep = File.separator;
String commandPath = systemRoot + sep + "SysWow64" + sep + exeName;
if (!new File(commandPath).exists()) {
commandPath = exeName;
}
return commandPath;
}
private static void validateWshProcessResult(ProcessResult result) {
validateProcessResult(result);
validateWshResult(result);
}
private static void validateWshResult(ProcessResult result) {
if (result.code == 0 && StringUtils.isNotBlank(result.message)) {
throw new RuntimeException(result.message);
}
}
private WindowsCommandUtils() { };
}
public class WindowsCommandUtilsTest {
private File tempDir;
private File vbsFile;
@Before
public void setUp() throws Exception {
tempDir = new File(System.getProperty("java.io.tmpdir"));
vbsFile = copyVbs();
}
private File copyVbs() throws IOException {
String vbsName = "test.vbs";
File file = new File(tempDir.getPath(), vbsName);
file.deleteOnExit();
InputStream in = null;
OutputStream out = null;
try {
in = this.getClass().getResourceAsStream(vbsName);
out = new FileOutputStream(file);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
return file;
}
@Test
public void testExecuteCommandNotExists() {
try {
WindowsCommandUtils.executeCommand(new ProcessBuilder("abc"));
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage(), e.getMessage().startsWith(
"java.io.IOException: Cannot run program \"abc\""
+ ": CreateProcess error=2,"));
}
}
@Test
public void testExecuteCommandErrorParam() {
try {
WindowsCommandUtils.executeCommand(new ProcessBuilder("find"));
fail();
} catch (RuntimeException e) {
assertEquals(
"code=2: FIND: パラメーターの書式が違います",
e.getMessage());
}
}
@Test
public void testExecuteCommandOk() {
WindowsCommandUtils.executeCommand(new ProcessBuilder("hostname"));
assertTrue(true);
}
@Test
public void testExecutWshErrorMessage() {
try {
WindowsCommandUtils.executeWshScript(vbsFile, tempDir, "2", "b");
fail();
} catch (RuntimeException e) {
assertEquals(
tempDir.getPath() + "\\test.vbs"
+ "(8, 2) Microsoft VBScript 実行時エラー: 型が一致しません。"
+ ": 'detarame'",
e.getMessage());
}
}
@Test
public void testExecutWshErrorCode() {
try {
WindowsCommandUtils.executeWshScript(vbsFile, tempDir, "3", "c");
fail();
} catch (RuntimeException e) {
assertEquals("code=1: エラー:c", e.getMessage());
}
}
@Test
public void testExecutWshOk() {
WindowsCommandUtils.executeWshScript(vbsFile, tempDir, "1", "a");
assertTrue(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment