BrightSide Workbench Full Report + Source Code
ShellExecutor.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2011 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 package org.turro.elephant.impl.util;
19 
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 import org.turro.elephant.context.ElephantContext;
27 
32 public class ShellExecutor {
33 
34  class StreamExecutor extends Thread {
35 
36  InputStream is;
37  Level level;
38 
39  StreamExecutor(InputStream is, Level level) {
40  this.is = is;
41  this.level = level;
42  }
43 
44  @Override
45  public void run() {
46  try {
47  InputStreamReader isr = new InputStreamReader(is);
48  BufferedReader br = new BufferedReader(isr);
49  String line = null;
50  while ((line = br.readLine()) != null) {
51  Logger.getLogger(StreamExecutor.class.getName()).log(level, line);
52  }
53  } catch (IOException ioe) {
54  ioe.printStackTrace();
55  }
56  }
57  }
58 
59  public ShellExecutor() {
60  }
61 
62  public int execute(String command) {
63 
64  try {
65  String cmd[] = new String[3];
66 
67  cmd[0] = "sh";
68  cmd[1] = "-c";
69  cmd[2] = command;
70 
71  Runtime rt = Runtime.getRuntime();
72  Logger.getLogger(ShellExecutor.class.getName()).log(Level.INFO, "Executor: " + command);
73 
74  Process proc = rt.exec(cmd);
75 
76  StreamExecutor errorStream = new StreamExecutor(proc.getErrorStream(), Level.SEVERE);
77 
78  StreamExecutor outputStream = new StreamExecutor(proc.getInputStream(), Level.INFO);
79 
80  errorStream.start();
81  outputStream.start();
82 
83  int exitVal = proc.waitFor();
84 
85  Logger.getLogger(ShellExecutor.class.getName()).log(Level.INFO, "Executor exit value for " + command + ": " + exitVal);
86 
87  return exitVal;
88 
89  } catch (Throwable t) {
90  Logger.getLogger(ShellExecutor.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), t);
91  }
92 
93  return -1;
94  }
95 }