Execute CURL command from java code - java

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\""

Related

How to execute `docker exec -it netvertex bash` by Java Program

How to execute docker exec -it netvertex bash by Java Program.
By this i am trying to execute but not working
public void execute(String command) {
try {
System.out.println("===========>" + command);
Channel channel1 = session.openChannel("exec");
((ChannelExec) channel1).setPty(true);
((ChannelExec) channel1).setCommand(command);
// X Forwarding
// channel.setXForwarding(true);
//channel.setInputStream(System.in);
channel1.setInputStream(null);
//channel.setOutputStream(System.out);
//FileOutputStream fos=new FileOutputStream("/tmp/stderr");
//((ChannelExec)channel).setErrStream(fos);
((ChannelExec) channel1).setErrStream(System.err);
InputStream in1 = channel1.getInputStream();
channel1.connect();
byte[] tmp1 = new byte[1024];
while (true) {
while (in1.available() > 0) {
int i = in1.read(tmp1, 0, 1024);
if (i < 0) break;
System.out.print(new String(tmp1, 0, i));
}
if (channel1.isClosed()) {
if (in1.available() > 0) continue;
System.out.println("exit-status: " + channel1.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
} catch (Exception e) {
}
}
By above code my other Linux command are working. But docker exec it not working.
And the other option i tried
try {
String host = "root#10.121.21.224";
String passwd = "root#10";
Terminal exec = new Terminal(pageUiUtils);
exec.loginSSH(host, passwd);
String[] command = {"docker", "exec", "-it", "netvertex", "bash"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.inheritIO();
Process proc = pb.start();
InputStream is = proc.getInputStream();
OutputStream os = proc.getOutputStream();
BufferedReader reader
= new BufferedReader(new InputStreamReader(is));
BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(os));
writer.write("pwd");
writer.flush();
String line = "";
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
exec.execute("docker exec -it netvertex bash");
pageUiUtils.pause(1000);
exec.execute("pwd");
//proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
by above code also showing error that
The input device is not a TTY

IntellijIdea: FileNotFoundException for vim TOhtml

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 "";
}`

No output from Runtime.getRuntime().exec("ls")

ping and date returned output, but it's not returning anything from "ls" or "pwd". What I want to do ultimately is run an SSH command. Any idea what I am missing below?
//Works and shows the output
executeCommand("ping -c 3 " + "google.com");
//Works and shows the output
executeCommand("date");
//Does not work. No output
executeCommand("sudo ls");
//Does not work. No output
executeCommand("ls");
private void executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Output", "Output: " + output.toString());
}
I have two solutions
first solution (you need Java 7):
...
ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
second solution:
Process p=Runtime.getRuntime().exec("ls");
InputStream is = p.getInputStream();
int c;
StringBuilder commandResponse = new StringBuilder();
while( (c = is.read()) != -1) {
commandResponse.append((char)c);
}
System.out.println(commandResponse);
is.close();

execute sql statements in java at runtime using Runtime.getRuntime().exec()

In the below code while loop is not running. Can someone suggest me what is going wrong with this code.
import java.io.*;
public class A
{
public static void main(String args[]) {
int value = 0;
String sql = "SELECT * FROM A2A_TP_INFO";
String filename="file.txt";
String filepath="/home/mit"+"export/file.txt";
String exportQuery = "/home/mit/JavaProj/proj/export/query";
String cmd[] = {
"/bin/ksh",
"-c",
"" + exportQuery + " " +filepath+ " \""
+ sql + ";\" "
};
try {
//Process p = Runtime.getRuntime().exec(cmd);
Process p1=Runtime.getRuntime().exec(sql);
// p.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
p1.getInputStream()));
while ((value = input.read()) != -1) {
char c = (char) value;
System.out.println(c);
}
input.close();
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
Don't use an intermediary shell. And use a ProcessBuilder:
final List<String> fullCommand = Arrays.asList(exportQuery, filePath, sql + ';')
final ProcessBuilder builder = new ProcessBuilder(fullCommand);
final Process p = builder.start();
Note that using ProcessBuilder you can send stdout/stderr to a file, and even customize stdin. You can set the working directory, customize the environment etc. Use that. Really. Runtime.exec() has no reason to be used anymore.

Writing data to InputStream of grep program invoked in java

I'm trying to process data obtained from a run of diff to an instance of GNU grep in a java program. I've managed to get the output of diff using the Process object's outputStream, but I'm currently having programs sending this data to the standard input of grep (through another Process object created in Java). Running Grep with the input only returns status code 1. What am I doing wrong?
Below is the code I have so far:
public class TestDiff {
final static String diffpath = "/usr/bin/";
public static void diffFiles(File leftFile, File rightFile) {
Runtime runtime = Runtime.getRuntime();
File tmp = File.createTempFile("dnc_uemo_", null);
String leftPath = leftFile.getCanonicalPath();
String rightPath = rightFile.getCanonicalPath();
Process proc = runtime.exec(diffpath+"diff -n "+leftPath+" "+rightPath, null);
InputStream inStream = proc.getInputStream();
try {
proc.waitFor();
} catch (InterruptedException ex) {
}
byte[] buf = new byte[256];
OutputStream tmpOutStream = new FileOutputStream(tmp);
int numbytes = 0;
while ((numbytes = inStream.read(buf, 0, 256)) != -1) {
tmpOutStream.write(buf, 0, numbytes);
}
String tmps = new String(buf,"US-ASCII");
inStream.close();
tmpOutStream.close();
FileInputStream tmpInputStream = new FileInputStream(tmp);
Process addProc = runtime.exec(diffpath+"grep \"^a\" -", null);
OutputStream addProcOutStream = addProc.getOutputStream();
numbytes = 0;
while ((numbytes = tmpInputStream.read(buf, 0, 256)) != -1) {
addProcOutStream.write(buf, 0, numbytes);
addProcOutStream.flush();
}
tmpInputStream.close();
addProcOutStream.close();
try {
addProc.waitFor();
} catch (InterruptedException ex) {
}
int exitcode = addProc.exitValue();
System.out.println(exitcode);
inStream = addProc.getInputStream();
InputStreamReader sr = new InputStreamReader(inStream);
BufferedReader br = new BufferedReader(sr);
String line = null;
int numInsertions = 0;
while ((line = br.readLine()) != null) {
String[] p = line.split(" ");
numInsertions += Integer.parseInt(p[1]);
}
br.close();
}
}
Both leftPath and rightPath are File objects pointing to the files to be compared.
Just a couple of hints, you could:
pipe the output of diff directly into grep: diff -n leftpath rightPath | grep "^a"
read the output file from grep instead of stdin: grep "^a" tmpFile
use ProcessBuilder to get your Process where you can easily avoid a blocking process because you're not reading stderr by using redirectErrorStream

Categories

Resources