I am trying to execute the command present as the solution in the following link:https://apple.stackexchange.com/questions/258020/why-does-find-certificates-have-some-missing I am executing the command using processbuilder in java but for some reason i am not able to get the value from stringbuffer eventhough the command runs perfectly in terminal.
This is may java command:
ArrayList<String> lcommands = new ArrayList<String>();
ArrayList<ArrayList<String>> lcommandsets = new ArrayList<ArrayList<String>>();
lcommands = new ArrayList<String>();
//lcommands.add("security find-identity -p codesigning -v");
// lcommands.add("security");
// lcommands.add("find-identity");
// lcommands.add("-p");
// lcommands.add("codesigning");
// lcommands.add("-v");
lcommands.add("security find-certificate -a -p codesign ~/Library/Keychains/login.keychain \\\n| awk '/-----BEGIN CERTIFICATE-----/ { cert = \"\" } \\\n{ cert = cert $0 \"\\n\" } \\\n/-----END CERTIFICATE-----/ { \\\nopenssl = \"openssl x509 -text -enddate -noout\"; \\\nprint cert | openssl; \\\nclose(openssl) \\\n}'");
// lcommands.add("find-certificate");
// lcommands.add("-a");
// lcommands.add("-p");
// lcommands.add("codesign");
//lcommands.add("~/Library/Keychains/login.keychain \\\n| awk '/-----BEGIN CERTIFICATE-----/ { cert = \"\" } \\\n{ cert = cert $0 \"\\n\" } \\\n/-----END CERTIFICATE-----/ { \\\nopenssl = \"openssl x509 -text -enddate -noout\"; \\");
// lcommands.add("~/Library/Keychains/login.keychain \\");
// lcommands.add("| awk '/-----BEGIN CERTIFICATE-----/ { cert = \"\" } \\");
// lcommands.add("{ cert = cert $0 \"\\n\" } \\");
// lcommands.add("/-----END CERTIFICATE-----/ { \\");
// lcommands.add("openssl = \"openssl x509 -text -enddate -noout\"; \\");
// lcommands.add("print cert | openssl; \\");
// lcommands.add("close(openssl) \\");
// lcommands.add("}'");
System.out.println();
lcommandsets.add(lcommands);
for (int i = 0; i < lcommandsets.size(); i++) {
Process process = null;
try {
ArrayList lruncommands = (ArrayList) lcommandsets.get(i);
ProcessBuilder lprocessbuilder = new ProcessBuilder(lruncommands);
// lprocessbuilder.directory(new File("/Users/"));
// lprocessbuilder.directory(new File("/Users/Admin/Library/Keychains"));
lprocessbuilder.redirectErrorStream(true);
process = lprocessbuilder.start();
try (BufferedReader bri = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = bri.readLine()) != null) {
//System.out.println(line);
if (line.contains(":") && line.contains("(")) {
lcertname = line.substring(line.indexOf(":") + 1, line.indexOf("(")).trim();
lteamid = line.substring(line.indexOf("(") + 1, line.lastIndexOf(")")).trim();
String ltrim=line.trim().substring(line.indexOf(')')+1);
luuid=ltrim.substring(0,ltrim.indexOf(" "));
//System.out.println("");
ArrayList<String> lval=new ArrayList<String>();
lval.add(0, luuid);
lval.add(1, lcertname);
lkeys.put(lteamid,lval );
}
}
} catch (Exception e) {
e.printStackTrace();
}
All the commented lines are the different combinations that i tried.If anyone knows how to split the command,it would be verymuch useful.Thanks in advance.
The problem seems to be the "pipe" inside your command.
As far as I know you have to start a shell (cmd on windows) and pass your command-string as a parameter.
The following code starts a "git bash" under windows and executes the command "dig www.kde.org | grep kde".
public static void main(String[] args) throws IOException {
ArrayList<String> lst = new ArrayList<String>();
lst.add("c:\\Anwendungen\\git\\bin\\bash");
lst.add("-c");
lst.add("dig www.kde.org |grep kde");
ProcessBuilder bld = new ProcessBuilder(lst);
Process proc = bld.start();
BufferedReader bfRdr = new BufferedReader(new InputStreamReader(proc.getInputStream()));
bfRdr.lines().forEach((String line) -> {
System.out.println(line);
});
}
As an alternative you can try using another approach that I have used in my project.
public static void main(String args[]) throws IOException
{
String line = null;
InputStream in = null;
String logFilePath = System.getProperty("user.dir") + "/logs/log1.log";
String s1 = "grep -n 'Start' " + logFilePath + " | tail -n 1 | cut -d : -f 1";
String[] cmd = { "/bin/sh", "-c", s1 };
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
in = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
line = br.readLine();
// operations to be performed on matched line
} finally {
if (in != null)
in.close();
}
}
}
Related
I have a file containing lines with the format of a,b,c,d,e,f.
I wrote the following Java code to return the list myextracting b,c,d,e,f by looking for b as key.
public static List<String> getThirdFourthFifthColumnBySecondColumnByCliTools(String filePath, String key) throws IOException {
List<String> list = new ArrayList<>();
String command = "grep " + key + " " + filePath + " | awk -F ',' '{print $3,$4,$5}'";
Process process = Runtime.getRuntime().exec(command);
Scanner sc = new Scanner(process.getInputStream());
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] split = line.split(" ");
for (int i = 0; i < split.length; i++) {
list.add(split[i]);
}
}
return list;
}
However I receive IndexOutOfBoundExcecption in my Java.
Can anyone please point out the problem in my code?
I want to execute curl command from java code. I have already seen couple of documents, stackoverflow questions regarding the same. But it is not giving the desired result, I am trying to run this curl command :
curl --noproxy <ip>
-i
-d "INSERT IN GRAPH <http://graph.com>{ <prop/Advanced_Data_Types> rdf:type owl:NamedIndividual ,
<http://abcd/Video> ,
<http://abcd/LearningResource/BookChapter> ;
<http://abcd/hasAuthor> <prop/Eric_Grimson> ;
<http://abcd/inLanguage> <http://abcd/#Hindi> ;
<http://abcd/sourceOrganization> <prop/IIT_Hyderabad> .}"
-u "demo:demo"
-H "Content-Type: application/sparql-query" http://<ip>:<port>/DAV/home/dba/xx
And the JAVA code :
ProcessBuilder pb = new ProcessBuilder(
"curl",
"-i",
"-d \"INSERT IN GRAPH <http://graph.com>{ <prop/Advanced_Data_Types> rdf:type owl:NamedIndividual ,<http://abcd/Video> ,<http://abcd/LearningResource/BookChapter> ;<http://abcd/hasAuthor> <prop/Eric_Grimson> ;<http://abcd/inLanguage> <http://abcd/#Hindi> ;<http://abcd/sourceOrganization> <prop/IIT_Hyderabad> .} ",
"-u \"demo:demo\"",
"-H \"Content-Type: application/sparql-query\"",
"http://<ip>:<port>/DAV/home/dba/xx");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
String line;
BufferedInputStream bis = new BufferedInputStream(is);
System.out.println(bis);
Is anything wrong in my code? I want to use this particular curl command. Please help.
I used it like this that executing curl in java.
public static String invokeCurlGet(String _host, int _connectTimeout, int _maxTimeout, int _maxResLength, Charset _charset) throws IOException
{
byte[] res = execute("curl --connect-timeout " + _connectTimeout + " --max-time " + _maxTimeout + " -X GET " + _host, _maxResLength);
return new String(res, _charset);
}
public static byte[] execute(String _cmd, int _maxResLength) throws IOException
{
Process process = Runtime.getRuntime().exec(_cmd);
try
{
int result = process.waitFor();
if(result != 0)
{
throw new IOException("Fail to execute cammand. Exit Value[" + result + "], cmd => " + _cmd);
}
}
catch(InterruptedException e)
{
process.destroyForcibly();
throw new IOException(e);
}
BufferedInputStream in = null;
try
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
in = new BufferedInputStream(process.getInputStream());
byte[] buf = new byte[1024];
int read = 0;
while((read = in.read(buf)) != -1)
{
out.write(buf, 0, read);
out.flush();
if(_maxResLength > 0 && out.size() > _maxResLength)
{
throw new IOException("Response length exceeded.");
}
}
return out.toByteArray();
}
finally
{
if(in != null)
{
in.close();
}
}
}
public static void main(String[] args) throws Exception
{
System.out.println(invokeCurlGet("http://127.0.0.1:9000?messageId=aaaaaaaa&to=asdfsefwaf", 3, 10, 0, Charset.defaultCharset()));
// System.out.println(invokeCurlGet("https://github.com", 1, 1, 0, Charset.defaultCharset()));
}
Your understanding on how to convert a command line to a list of string arguments is slightly incorrect. (This is roughly equivalent to how a Unix shell works).
Generally when a space is present on the command line it means starting a new argument. So
"-H \"Content-Type: application/sparql-query\""
should be
"-H", "\"Content-Type: application/sparql-query\""
I am using the following code for running an application:
private void RunApp2() throws IOException
{
StringBuilder sb = new StringBuilder();
String filePath = System.getProperty("user.dir");
String jarfile = filePath + "\\MyAppV2.jar";
File f = new File(jarfile);
if(f.exists() && !f.isDirectory()) {
// do something
}
else
{
AreThereProblem = true;
}
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar \""+jarfile + "\"");
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
//process.destroy();
}catch (Exception e){
lblInformation.setText(e.getMessage());
}
}
But how can I close MyAppV2.jar application if it is already running before I'm running it again?
I was trying to use https://developer.rackspace.com/blog/displaying-prepared-code-with-syntax-highlighting-on-android/ to display some code in html, so I wrote a custom formatter in Java, which has, among other things, this procedure:
String code2html( String s ) throws Exception {
if ( s == null || s.length() == 0 ) return "";
String t;
PrintWriter w = new PrintWriter(Konst.FPATH+"tmp.txt","UTF-8");
w.println(s);
w.close();
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("vim -c \"let html_use_css=0\" -c \"TOhtml\" -c \"w\" "+Konst.FPATH+"tmp.txt.html"+" -c \"wq\" -c \"q\" "+Konst.FPATH+"tmp.txt");
StringBuilder sb = new StringBuilder();
BufferedReader b = new BufferedReader(new FileReader(Konst.FPATH+"tmp.txt.html"));
while ( (t=b.readLine())!=null && !(t.length()>=5&&t.substring(0,5).equals("<body")) );
do {sb.append(t+"\n");} while ( (t=b.readLine())!=null && !(t.length()>=6&&t.substring(0,6).equals("</body")) );
sb.append(t);
return sb.toString();
}
However, I get FileNotFoundException for tmp.txt.html file, although the tmp.txt is created allright. Running the above vim command from commandline produces the desired result. What can be done?
EDIT: I added int retVal = pr.exitValue() and got Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited
EDIT: Ha, I've read this wonderful document: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2, implemented their recipe for dealing with this problem, and what I get is
ERROR>Vim: Warning: Output is not to a terminal
ERROR>Vim: Warning: Input is not from a terminal
Bram Moolenaar answers similar question on http://vim.1045645.n5.nabble.com/Vim-Warning-Output-is-not-to-a-terminal-td4648615.html
He says "If both input and output are redirected, you are really stuck".
I found a workaround by using gvim rather than terminal vim, and rewriting my above code as
String code2html( String s ) throws Exception {
if ( s == null || s.length() == 0 ) return "";
String t;
PrintWriter w = new PrintWriter(Konst.FPATH+"tmp.txt","UTF-8");
w.println(s);
w.close();
Runtime rt = Runtime.getRuntime();
String T;
try {
Process pr = rt.exec(T = "gvim -c \"let html_use_css=0\" -c \"TOhtml\" -c \"wqx\" -c \"q\" -c \"q\" " + Konst.FPATH + "tmp.txt");
FileOutputStream fos;
StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream(),"ERROR");
StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream(),"OUTPUT",fos=new FileOutputStream(Konst.FPATH+"garbage.out"));
errorGobbler.start();
outputGobbler.start();
int exitVal = pr.waitFor();
System.out.println("ExitValue: "+exitVal);
fos.flush();
fos.close();
StringBuilder sb = new StringBuilder();
BufferedReader b = new BufferedReader(new FileReader(Konst.FPATH + "tmp.txt.html"));
while ((t = b.readLine()) != null && !(t.length() >= 5 && t.substring(0, 5).equals("<body"))) ;
do {
sb.append(t + "\n");
} while ((t = b.readLine()) != null && !(t.length() >= 6 && t.substring(0, 6).equals("</body")));
sb.append(t);
return sb.toString();
}
catch ( Throwable e ) {
e.printStackTrace();
}
return "";
}`
I want to run grep command from java.
Here is what I had tried. Please let me know, why it is not displaying ouput.
public static void main(String args[]) throws IOException{
Runtime rt = Runtime.getRuntime();
String[] cmd = { "/bin/sh", "-c", "grep 'Report Process started' server.log|wc -l" };
Process proc = rt.exec(cmd);
BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
System.out.println("Done");
}
You don't need to pipe grep's output to wc -l. Just use grep -c like this:
String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"};
Though I must say that doing this right inside Java is much cleaner. Consider code like this:
String logdata = new Scanner(new File("/path/to/server.log")).useDelimiter("\\Z").next();
final String needle = "Report Process started";
int occurrences = 0;
int index = 0;
while (index < logdata.length() && (index = logdata.indexOf(needle, index)) >= 0) {
occurrences++;
index += needle.length();
}
You must check for any errors.
private static void printStream(InputStream in) throws IOException {
BufferedReader is = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
}
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
String[] cmd = {"/bin/sh", "-c", "grep 'Report Process started' server.log|wc -l"};
Process proc = rt.exec(cmd);
printStream(proc.getInputStream());
System.out.println("Error : ");
printStream(proc.getErrorStream());
} catch (Exception ex) {
ex.printStackTrace();
}
}