Writing to Subprocess's Standard Input - java

I'm spawning a process in Java using the following code:
Process newExec = null;
BufferedReader outStream = null;
BufferedReader inStream = null;
BufferedReader errStream = null;
StringBuffer outputBuffer = new StringBuffer();
String PATH_TO_EXEC = config.getExecPath();
try {
newExec = Runtime.getRuntime().exec(PATH_TO_EXEC + " " + args);
}
catch(IOException e){
outputBuffer.append("Error in running executable.");
e.printStackTrace();
return outputBuffer.toString();
}
After the process is spawned it expects some input through stdin. How would I stream strings to this newly-spawned program?

Process newExec = null;
BufferedReader outStream = null;
BufferedReader inStream = null;
BufferedReader errStream = null;
StringBuffer outputBuffer = new StringBuffer();
String PATH_TO_EXEC = config.getExecPath();
try {
newExec = Runtime.getRuntime().exec(PATH_TO_EXEC + " " + args);
PrintWriter o = new PrintWriter(newExec.getOutoutStream());
o.println("input to process");
o.flush();
}
catch(IOException e){
outputBuffer.append("Error in running executable.");
e.printStackTrace();
return outputBuffer.toString();
}

Related

Closing a Stream after instantiating a bufferedWriter

Just wondering if my bufferedWrites will work outside this try clause as it should as. i atm have no way of checking the outcome atm but. As in i only need the stream to be open for the instantiation of the BufferedWriter correct.
So this code should work:
BufferedWriter bufferedWriter;
// ServletOutputStream responseOutputStream = null;
FileOutputStream fos = new FileOutputStream(file);
if (zip) {
try (ZipOutputStream zOut = new ZipOutputStream(fos);) {
String fileName = file.getName().replace(".zip", "");
zOut.putNextEntry(new ZipEntry(fileName));
bufferedWriter = new BufferedWriter(new OutputStreamWriter(zOut, Charset.forName(enc)));
}
} else {
try (OutputStreamWriter opsw = new OutputStreamWriter(fos, Charset.forName(enc))) {
bufferedWriter = new BufferedWriter(opsw);
}
}
File fin = new File(tempFile);
FileInputStream fis = new FileInputStream(fin);
BufferedReader bufferedReader;
try(InputStreamReader ipsr = new InputStreamReader(fis)){
bufferedReader = new BufferedReader(ipsr);
}
String aLine = null;
int rowCount = 1;
logger.info("Copy file for output");
while ((aLine = bufferedReader.readLine()) != null) {
if (rowCount == 1) {
// Ful fix wax klarar nog inte att s�tta encoding.
if (encoding.equals(ProductFeedOutputController.ENCODING_88591)) {
bufferedWriter.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
} else {
bufferedWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
......

creating Socket to connect to windows 10 machine from Raspberry pi 4 Raspbian does not work (Java)

I have a Raspberry pi 4 with Raspbian installed, and I have a computer with Windows 10 installed.I wrote two functions one send a file and the other one receive the file.
when I run this function that sends a file on the raspberry pi 4:
public static void sendFile(String fileName, String ip)
{
BufferedOutputStream outputStream = null;
PrintWriter writer = null;
BufferedReader reader = null;
FileInputStream filein = null;
File file = new File(fileName);
if (!file.exists())
{
System.out.println(fileName + " does not exist");
return;
}
try
{
Socket socket = new Socket(ip, port);
outputStream = new BufferedOutputStream(socket.getOutputStream());
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
filein = new FileInputStream(file);
long fileSize = file.length();
writer.println(fileName); // sending file name
writer.println(fileSize); // sending file size in bytes
writer.flush();
byte[] dataBuffer = new byte[1024];
int numberOfReadBytes = 0; // the number of read bytes for each read() function call
System.out.println("Entering the loop");
for(long i = 0; i < fileSize && numberOfReadBytes > -1;)
{
numberOfReadBytes = filein.read(dataBuffer); // read read() function returns the number of bytes tha has been assigned to the array or -1 if EOF(end of file) is reached
outputStream.write(dataBuffer, 0, numberOfReadBytes); // writing the bytes in dataBuffer from index 0 to index numberOfBytes
i += numberOfReadBytes;
}
outputStream.flush();
System.out.println(fileName + " sent to " + ip);
String status = reader.readLine();
System.out.println("Status: " + status + "\t file save successfully on the other machine.");
}
catch(IOException ioe)
{
System.err.println("Status: 0\n" + ioe.getMessage());
}
finally // closing streams
{
try
{
outputStream.close();
reader.close();
writer.close();
filein.close();
}
catch (IOException ioe)
{
System.err.println("Error closing the connection.");
}
}
}
it stops at this line Socket socket = new Socket(ip, port);
and this is the other function that runs on windows 10
public static void receiveFile()
{
// 1- read the file name
// 2- read the size of the file
// 3- read the file and write it
ServerSocket server = null;
Socket socket = null;
BufferedReader reader = null;
BufferedInputStream inputStream = null;
FileOutputStream fileout = null;
PrintWriter writer = null;
try
{
server = new ServerSocket(9999);
socket = server.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inputStream = new BufferedInputStream(socket.getInputStream());
writer = new PrintWriter(socket.getOutputStream());
String fileName = reader.readLine(); // reading file name
long fileSize = Long.parseLong(reader.readLine()); // reading file size
System.out.println(fileSize);
// reading file data and write the data
File file = new File(fileName);
fileout = new FileOutputStream(file);
for (long i = 0; i < fileSize; ++i)
{
fileout.write(inputStream.read());
System.out.println(i);
}
fileout.flush();
fileout.close();
writer.println('1');
System.out.println("Status: 1");
System.out.println(fileName+ " is saved successfully");
}
catch (IOException ioe)
{
System.err.println("Status: 0");
System.err.println(ioe.getMessage());
}
finally
{
try
{
reader.close();
inputStream.close();
}
catch(IOException ioe)
{
System.err.println("Error closing connection\n" + ioe.getMessage());
}
}
}
I think windows 10 firewall blocks connection, but I am not sure.
It turns out it was the firewall blocking connection from the raspberry pi

how to pass data between 2 #RequestMapping

i have 2 #RequestMapping; the first uploades a video to my server and the second execute a transcoding linux command.
every #RequestMapping is working but i am tryig from a week to get the filename of the uploaded file from the first #RequestMapping and send it to the second one.
please help me !
this is the first One:
#RequestMapping(value = "/uploadajax", method = RequestMethod.POST)
#ResponseBody
public List<ObjectNode> uploadMultipleFiles(Model model, MultipartHttpServletRequest request, HttpServletResponse response,
Principal principal) throws IOException {
CommonsMultipartFile multipartFile = null;
Iterator<String> iterator = request.getFileNames();
ObjectMapper objectMapper = new ObjectMapper();
FileMeta fileMeta = null;
while (iterator.hasNext()) {
String key = iterator.next();
multipartFile = (CommonsMultipartFile) request.getFile(key);
String uploadedFileName = multipartFile.getOriginalFilename();
try {
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
byte[] bytes = multipartFile.getBytes();
String phyPath = request.getSession().getServletContext().getRealPath("/");
String repoUserPath=phyPath+"resources/"+user.getId();
System.out.println("-------------"+user.getId()+"------------------");
System.out.println("####"+repoUserPath);
File repoUSer = new File(repoUserPath);
if (!repoUSer.exists()) {
repoUSer.mkdir();
String filepath =repoUserPath+"/"+multipartFile.getOriginalFilename();
System.out.println("####"+filepath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filepath));
stream.write(bytes);
stream.close();
fileMeta = new FileMeta();
fileMeta.setFileName(multipartFile.getOriginalFilename());
fileMeta.setFileSize((multipartFile.getSize()/1024)/1024+" Mb");
fileMeta.setFileType(multipartFile.getContentType());
fileMeta.setPathfile("http://89.40.113.84:8080/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
fileMeta.setLinkdelete("/var/lib/tomcat7/webapps/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
serviceMangerTranscode.save(fileMeta);
fileMeta.setUser(user);
serviceMangerTranscode.updateFile(fileMeta);
file= fileMeta;
model.addAttribute("Nomf", file.getFileName());
System.out.println("created!!");
String[] cmdArray = {"ffprobe","-show_streams","-i",filepath };
model.addAttribute("filepath",filepath);
System.out.println("ffprobe2........!!");
//String[] cmdArray = {"ping","www.google.com" };
Process process = Runtime.getRuntime().exec(cmdArray);
InputStream processInputStream =process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = bufferedReader.readLine()) != null){
ObjectNode node = objectMapper.createObjectNode();
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
line ="aaa";
ObjectNode node = objectMapper.createObjectNode();
node.put("line",line );
System.out.println("</OUTPUT>");
return listFileNode;
}else {
long size = FileUtils.sizeOfDirectory(repoUSer);
System.out.println("size 1"+(size/1024)/1024);
if ((size/1024)/1024 >100) {
ObjectNode node = objectMapper.createObjectNode();
node.put("error","Size Not Supported for Your repository !");
listFileNode.add(node);
}else{
System.out.println("choix2!!++");
String filepath =repoUserPath+"//"+multipartFile.getOriginalFilename();
System.out.println("####"+filepath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filepath));
stream.write(bytes);
stream.close();
// fileMeta = new FileMeta();
fileMeta.setFileName(multipartFile.getOriginalFilename());
fileMeta.setFileSize((multipartFile.getSize()/1024)/1024+" Mb");
fileMeta.setFileType(multipartFile.getContentType());
fileMeta.setPathfile(filepath);
fileMeta.setLinkdelete("/var/lib/tomcat7/webapps/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
serviceMangerTranscode.save(fileMeta);
fileMeta.setUser(user);
serviceMangerTranscode.updateFile(fileMeta);
file= fileMeta;
model.addAttribute("filedetails", fileMeta);
System.out.println("fichier créé!!");
String[] cmdArray = {"ffprobe","-show_streams","-i",filepath };
System.out.println("ffprobe executee........!!");
Process process = Runtime.getRuntime().exec(cmdArray);
InputStream processInputStream =process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = bufferedReader.readLine()) != null){
ObjectNode node = objectMapper.createObjectNode();
// if (line.contains("codec_type") || line.contains("duration_ts")){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}//}
line ="bbb";
ObjectNode node = objectMapper.createObjectNode();
node.put("line",line );
System.out.println("</OUTPUT>");
System.out.println("size 2"+(size/1024)/1024);
return listFileNode;
}
}
} catch (Exception e) {
return null;
}
}
return null;
}
and this is the second one:
#RequestMapping(value ="/Transcodage", method = RequestMethod.POST)
public String Trascoood(Model model, HttpServletRequest request, HttpServletResponse response
) throws IOException {
//Recuperation des valeurs utilisateur:
String userIDD =request.getParameter("useridd");
String newFileName =request.getParameter("newFileName");
String encolist=request.getParameter("encolist");
String codeclist=request.getParameter("codeclist");
String bitrate=request.getParameter("bitratevideo");
String Nomf= request.getParameter("mapping1Form");
System.out.println("NOMFFFFFFFFFFF: " + Nomf);
int userIDDD = Integer.parseInt(userIDD);
User user = userv.getUserById(userIDDD);
ObjectMapper objectMapper = new ObjectMapper();
org.codehaus.jackson.node.ObjectNode node = objectMapper.createObjectNode();
//file= serviceMangerTranscode.getFileById(idfile);
ModelAndView modelUserHome = new ModelAndView("userhome");
//System.out.println("file path : " + file.getPathfile() +"*************************************************");
System.out.println("userIDD: " + userIDD + "...............................................");
System.out.println("newFileName: " + newFileName + "...............................................");
System.out.println("encolist: " + encolist + "...............................................");
String newFileN = new StringBuilder().append(".").append(newFileName).append(".").append(encolist).toString();
System.out.println("FILE NAME + EXTENTION: " + newFileN + "...............................................");
//node.put("success", "true");
String[] cmdArray = {"sudo", "ssh", "-tt", "root#89.40.113.84", "/root/dved", "-l", "89.40.112.120,89.40.112.248", "you.mp4", "-s",newFileN};
//String[] cmdArray = {"sudo", "/root/dve", "-l", "89.40.112.120,89.40.112.248", "/root/greece.mkv", "-s",".teeeeeeeeeeeeest.avi" };
//String[] cmdArray = {"sudo","/root/dve","-s",".encoded.avi","-l","89.40.112.248","/root/greece.mkv" };
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
try{
Runtime rt = Runtime.getRuntime();
ProcessBuilder pb = new ProcessBuilder(cmdArray);
Process proc = pb.start();
//Process proc = rt.exec(cmdArray);
int rc =0;
rc = proc.waitFor(); // Wait for the process to finish.
System.out.printf("Script executed successfully in ", rc);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR___EXEC>");
while ( (line = br.readLine()) != null){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
System.out.println("</ERROR___EXEC>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
InputStream processInputStream =proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
System.out.println("<RESULTAT___EXEC>");
while ( (line = bufferedReader.readLine()) != null){
System.out.println(line);
node.put("lineR",line );
listFileNode.add(node);
}
System.out.println("</RESULTAT___EXEC>");
}catch (Throwable t)
{
t.printStackTrace();
}
model.addAttribute("usersize",user.getUserfiles().size());
model.addAttribute("listfiles",user.getUserfiles());
model.addAttribute("user",user);
model.addAttribute("MsgTranscode","Votre video a bien ete encodee, vous pouvez desormais la telecharger de votre portfolio!");
return "userhome";
}
Thank you for your reply, i think it cannot be done so i put the data in the database than recover it in the second RequestMapping

Android Socket Error- >libcore.io.IoBridge.connect(Iobridge.java.114)

In the below code i am just creating a socket to run the Shell command in my App but the problem is some times it runs and most of the time it through the error (libcore.io.IoBridge)
PrintWriter writer = null;
BufferedReader in = null;
String inputLine;
try {
Socket clientSocket = null;
clientSocket = new Socket(LOCAL_ADDRESS, PORT);
Log.d("ExecuteService", (clientSocket.isConnected() ? "Connected" : "Not Connected"));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
writer.println(cmd);
writer.flush();
Log.d("ExecuteService", "Lineis in:" + cmd);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((inputLine = in.readLine()) != null) {
Log.d("ExecuteService", "Lines :" + inputLine);
}
Log.d("ExecuteService", "Lineis out:" + cmd);
writer.close();
writer = null;
in.close();
in = null;
clientSocket.close();
clientSocket = null;
} catch (Exception exception) {
for(StackTraceElement st : exception.getStackTrace())
Log.d("ExecuteService", st.toString());
}
}
Can any one please let me know how n when this error gets occur?

java write netstat in cmd

My goal is to print all the internet connections on my computer. When i type netstat on cmd i get the internet connections list. I wanted to do the same in java, automatically.
My code:
Runtime runtime = Runtime.getRuntime();
process = runtime.exec(pathToCmd);
byte[] command1array = command1.getBytes();//writing netstat in an array of bytes
OutputStream out = process.getOutputStream();
out.write(command1array);
out.flush();
out.close();
readCmd(); //read and print cmd
But with this code i get C:\eclipse\workspace\Tracker>Mais? instead of the list of connections. Obviously i'm working with eclipse, in windows 7. What am I doing wrong? I've looked in similar topics but i cound't find whats wrong. Thank you for the answers.
EDIT:
public static void readCmd() throws IOException {
is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
Try this : I was able to create a file in my default temporary directory with all the connections
final String cmd = "netstat -ano";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
File tmp = File.createTempFile("allConnections","txt");
byte[] buf = new byte[256];
OutputStream outputConnectionsToFile = new FileOutputStream(tmp);
int numbytes = 0;
while ((numbytes = in.read(buf, 0, 256)) != -1) {
outputConnectionsToFile.write(buf, 0, numbytes);
}
System.out.println("File is present at "+tmp.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace(System.err);
}
You can also use an instance of java.util.Scanner to read the output of the command.
public static void main(String[] args) throws Exception {
String[] cmdarray = { "netstat", "-o" };
Process process = Runtime.getRuntime().exec(cmdarray);
Scanner sc = new Scanner(process.getInputStream(), "IBM850");
sc.useDelimiter("\\A");
System.out.println(sc.next());
sc.close();
}
final String cmd = "netstat -ano";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace(System.err);
} finally{
in = null;
isr = null;
br = null;
}

Categories

Resources