Get an error trying to execute curl command from java code - java

I have a trouble with executing curl command from java code. I am using Runtime.getRuntime().exec(cmd) construction to execute curl. Everything worked fine until I have been stuck on receiving response about 88kb. Executing of command is freezing. My code for executing command:
public String executeSimpleBash(String[] cmd) {
StringBuilder output = new StringBuilder();
Process p;
String result;
try {
p = Runtime.getRuntime().exec(cmd);
p.waitFor(40, TimeUnit.SECONDS);
if (p.exitValue() != 0) {
result = null;
} else {
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
result = output.toString();
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
result = null;
}
return result;
}
My command:
String[] cmd = new String[]{
"curl",
"-H",
"text/xml",
"--insecure",
"--max-time",
"30",
"-s",
"-d",
"languageSelect=enEn&xml=" + xmlBody,
endpointUrl
};

Related

Spring Boot - Should I implement multi-threading to resolve this problem?

I've been working on some web project and one of its requests execute command line using Java Process.
This is the method.
#ResponseBody
#RequestMapping(value = "/startTest", method = RequestMethod.POST)
public String startTest(int test_id) {
...
String cmd = "..."
ProcessUtil pu = new ProcessUtil();
try {
pu.execute(cmd);
File file = new File(System.getProperty("user.dir")
+ "\\datas\\cypress\\videos\\examples\\main.spec.js.mp4");
File fileToMove = new File(
".\\\\datas\\\\results\\" + uitest.getTest_filename() + ".mp4");
file.renameTo(fileToMove);
return "success";
} catch (Exception e) {
return "fail";
}
}
And Here is the ProcessUtil.java
public class ProcessUtil {
public static void execute(String cmd) {
Process process = null;
Runtime runtime = Runtime.getRuntime();
StringBuffer successOutput = new StringBuffer();
StringBuffer errorOutput = new StringBuffer();
BufferedReader successBufferReader = null;
BufferedReader errorBufferReader = null;
String msg = null;
List<String> cmdList = new ArrayList<String>();
if (System.getProperty("os.name").indexOf("Windows") > -1) {
cmdList.add("cmd");
cmdList.add("/c");
} else {
cmdList.add("/bin/sh");
cmdList.add("-c");
}
cmdList.add(cmd);
String[] array = cmdList.toArray(new String[cmdList.size()]);
try {
process = runtime.exec(array);
successBufferReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
while ((msg = successBufferReader.readLine()) != null) {
successOutput.append(msg + System.getProperty("line.separator"));
}
errorBufferReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
while ((msg = errorBufferReader.readLine()) != null) {
errorOutput.append(msg + System.getProperty("line.separator"));
}
process.waitFor();
if (process.exitValue() == 0) {
System.out.println("success!");
System.out.println(successOutput.toString());
} else {
System.out.println("fail...");
System.out.println(successOutput.toString());
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
process.destroy();
if (successBufferReader != null)
successBufferReader.close();
if (errorBufferReader != null)
errorBufferReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The problem that I'm facing is when I open two Windows command windows and execute simultaneously it seemingly works fine. However, when I run that 'startTest' method by requesting to my server simultaneously, it pushes my CPU and RAM to nearly 100% and results seemed odd. I don't know much about multi-threading, but I guess I should execute the command via multiple windows(I think my commands were executed in the same environment and they crashed each other...). Please give me some advice to resolve this problem... Thank you in advance.

ProcessBuilder doesn't recognize gcc command

I'm trying to run gcc via ProcessBuilder, but it says:
'gcc' is not recognized as an internal or external command,
operable program or batch file.
But running gcc via cmd works.
Here is code:
public static void main(String[] args) {
String command = "gcc C:\\Users\\pawel\\Desktop\\CFG-master\\test.c";
System.out.println(executeCommand(command));
}
public static String executeCommand(String command) {
String line;
String result = "";
try {
ProcessBuilder builder;
builder = new ProcessBuilder("cmd.exe", "/c", command);
builder.directory(new File("C:\\Users\\pawel"));
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
result += line + "\n";
}
} catch (IOException e) {
System.out.println("Exception = " + e.getMessage());
}
return result;
}
cmd screen

Execute powershell script in Java JSFrame

I have developed a demo app in JSFrame which should execute powershell script in my folder.
I am trying following code.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("powershell C:\\helloworld.ps1");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
proc.getOutputStream().close();
}
catch(Exception ex)
{
}
}
And in helloworld.ps1, I am having following command :
$strString = "Hello World 123"
write-host $strString
But I am not getting any output.

How to execute shell command from android app?

I want to execute android shell command from my android app to execute a uiautomator test jar.
i have tried following options. but neither of them is working for me...
public void execute(String shellcommand) {
Runtime rt = Runtime.getRuntime();
Process p = r.exec(new String[]{"/system/bin/sh", "-c", shellcommand});
}
Also tried...
public void execute(String shellcommand) {
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes(shellcommand + "\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}
Please tell what mistake i m doing?
Android 5.0 solved your problem. Here is new API using which you can execute shell commands.Check here : executeShellCommand (String command)
Enjoy!!!
Try this, i added an output reading process also. But you'll need to cut up your shell command:
ProcessBuilder pb = new ProcessBuilder("adb", "shell", "uiautomator", "runtest", "/data/local/tmp/MyJar.jar", "-c", "com.my.test.Class#testmethod", "-e someparameter someparameterName");
Process pc;
try {
pc = pb.start();
InputStream stdin = pc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
InputStreamReader esr = new InputStreamReader(pc.getErrorStream());
BufferedReader errorReader = new BufferedReader(esr);
pc.waitFor();
} catch (IOException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail(e.getMessage());
}

ProcessBuilder throwing java.lang.Exception:

I am trying to figure out why the code below is throwing a
java.lang.Exception: No such file or directory
Exception
ProcessBuilder send = new ProcessBuilder("/bin/bash","/opt/ftp/scripts/XFER.sh | /opt/ftp/myftp -c /opt/ftp/ftp.conf >> /logging/ftp.log2>&1");
Process sendProcess = send.start();
br = new BufferedReader(new InputStreamReader(sendProcess.getErrorStream()));
builder = new StringBuilder();
line = null;
while ( (line = br.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
if(!builder.toString().isEmpty()){
throw new Exception( "ERROR with XFER.sh: "+builder.toString() );
}
I've tried isolating the arguments within a String Array, but that did not work either. Any ideas as to what may be causing this stacktrace?
I have success using the following code. Maybe you have to use the -c option:
private static int execute(String command) {
Runtime runtime = null;
Process process = null;
int exitValue = -1;
BufferedInputStream bis = null;
try {
runtime = Runtime.getRuntime();
process = runtime.exec(new String[] { "/bin/bash", "-c", command });
bis = new BufferedInputStream(process.getInputStream());
byte[] b = new byte[1892];
while (bis.read(b) != -1) {
}
exitValue = process.waitFor();
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
if (process != null) {
process.destroy();
}
} catch (Exception e) {
//Logging
}
return exitValue;
}

Categories

Resources